KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jacorb > config > LogKitLoggerFactory


1 package org.jacorb.config;
2
3 /*
4  * JacORB - a free Java ORB
5  *
6  * Copyright (C) 1997-2004 Gerald Brose.
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the Free
20  * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21  */

22
23 import org.apache.avalon.framework.logger.Logger;
24 import org.apache.avalon.framework.logger.LogKitLogger;
25 import org.apache.avalon.framework.configuration.ConfigurationException;
26
27 import org.apache.log.*;
28 import org.apache.log.format.*;
29 import org.apache.log.output.io.*;
30 import org.apache.log.output.io.rotate.*;
31
32 import java.util.*;
33 import java.io.*;
34
35 /**
36  * JacORB logger factory that creates named Avalon loggers with logkit
37  * as the underlying log mechanism. <BR> The semantics here is that any
38  * names logger retrieved using the logkit naming conventions for
39  * nested loggers will inherit its parent loggers log target e.g., a
40  * logger retrieved for <code>jacorb.naming</code>
41  * inherits the root logger's target (ie. <code>System.err</code>, or
42  * a file.
43  * <P>
44  * Log priorities for new loggers are also inherited from the parent
45  * logger. If no parent logger is available the priority defaults to the
46  * value of this factory's <code>defaultPriority</code> field. The
47  * priorities for loggers can be set via
48  * configuration properties that have the same name as the requested
49  * logger, plus a suffix of <code>.log.verbosity</code>.
50  * <P>
51  * The priority for all loggers that do not have a specific <name>.log.verbosity
52  * prop defined will be set to the value of the jacorb.log.default.verbosity
53  * property, if it's set. If not, the default is 0.
54  *
55  * @author Gerald Brose
56  * @version $Id: LogKitLoggerFactory.java,v 1.3 2004/05/06 12:39:58 nicolas Exp $
57  * @since JacORB 2.0 beta 3
58  */

59
60 class LogKitLoggerFactory
61     implements LoggerFactory
62 {
63     private final static String JavaDoc DEFAULT_LOG_PATTERN =
64         "[%.20{category}] %.7{priority} : %{message}\\n%{throwable}";
65
66     private final static String JavaDoc name = "logkit";
67     private PatternFormatter logFormatter = null;
68
69     /** default priority for loggers created with this factory */
70     private int defaultPriority = 0;
71
72     /** cache of created loggers */
73     private final Map namedLoggers = new HashMap();
74
75     /** append to a log file or overwrite ?*/
76     private boolean append = false;
77
78     /** the writer for console logging */
79     private Writer consoleWriter;
80
81     /** this target for console logging */
82     private LogTarget consoleTarget;
83
84     /** The default log file */
85     private LogTarget defaultTarget = null;
86
87     private Configuration configuration = null;
88
89     public void configure(org.apache.avalon.framework.configuration.Configuration configuration)
90         throws org.apache.avalon.framework.configuration.ConfigurationException
91     {
92         this.configuration = (Configuration)configuration;
93
94         defaultPriority =
95             configuration.getAttributeAsInteger("jacorb.log.default.verbosity", 0);
96
97         append =
98             configuration.getAttribute("jacorb.logfile.append","off").equals("on");
99
100         logFormatter =
101             new PatternFormatter(configuration.getAttribute("jacorb.log.default.log_pattern",
102                                                             DEFAULT_LOG_PATTERN));
103         switch (defaultPriority)
104         {
105             case 0:
106             case 1:
107             case 2:
108             case 3:
109             case 4:
110                 break;
111             default:
112                 throw new ConfigurationException("'" + defaultPriority + "' is an illegal"
113                                                  + " value for the property jacorb.log.default.verbosity. Valid values are [0-4]");
114         }
115         consoleWriter = new OutputStreamWriter(System.err);
116         consoleTarget = new WriterTarget(consoleWriter, logFormatter);
117     }
118
119     /**
120      * set the default log priority applied to all loggers on creation,
121      * if no specific log verbosity property exists for the logger.
122      */

123
124     public void setDefaultPriority(int priority)
125     {
126         defaultPriority = priority;
127     }
128
129     /**
130      * @return the name of the actual, underlying logging mechanism,
131      * here "logkit"
132      */

133
134     public final String JavaDoc getLoggingBackendName()
135     {
136         return name;
137     }
138
139     /**
140      * @param name the name of the logger, which also functions
141      * as a log category
142      * @return a Logger for a given name
143      */

144
145     public Logger getNamedLogger(String JavaDoc name)
146     {
147         return getNamedLogger(name, null);
148     }
149
150     /**
151      * @param name - the name of the logger, which also functions
152      * as a log category
153      * @return a root console logger for a logger name hierarchy
154      */

155
156     public Logger getNamedRootLogger(String JavaDoc name)
157     {
158         return getNamedLogger(name, consoleTarget);
159     }
160
161
162     /**
163      * @param name - the name of the logger, which also functions
164      * as a log category
165      * @param logFileName - the name of the file to log to
166      * @param maxLogSize - maximum size of the log file. When this size is reached
167      * the log file will be rotated and a new log file created. A value of 0
168      * means the log file size is unlimited.
169      *
170      * @return the new logger.
171      */

172
173     public Logger getNamedLogger(String JavaDoc name, String JavaDoc logFileName, long maxLogSize)
174         throws IOException
175     {
176         if (name == null)
177             throw new IllegalArgumentException JavaDoc("Log file name must not be null!");
178
179         FileOutputStream logStream =
180             new FileOutputStream(logFileName, append);
181
182         LogTarget target = null;
183         if (maxLogSize == 0)
184         {
185             // no log file rotation
186
Writer logWriter = new OutputStreamWriter(logStream);
187             target = new WriterTarget(logWriter, logFormatter);
188         }
189         else
190         {
191             // use log file rotation
192
target =
193                 new RotatingFileTarget(append,
194                                        logFormatter,
195                                        new RotateStrategyBySize(maxLogSize * 1000),
196                                        new RevolvingFileStrategy(new File(logFileName), 10000));
197         }
198         return getNamedLogger(name, target);
199     }
200
201
202     /**
203      * @param name the name of the logger, which also functions
204      * as a log category
205      * @param the log target for the new logger. If null, the new logger
206      * will log to System.err
207      * @return the logger
208      */

209     public Logger getNamedLogger(String JavaDoc name, LogTarget target)
210     {
211         Object JavaDoc o = namedLoggers.get(name);
212
213         if ( o != null )
214         {
215             return (Logger)o;
216         }
217
218         org.apache.log.Logger logger =
219             Hierarchy.getDefaultHierarchy().getLoggerFor(name);
220
221         int priority = getPriorityForNamedLogger(name);
222
223         logger.setPriority(intToPriority(priority));
224
225         if (target != null )
226         {
227             // LogTarget was provided by caller
228
logger.setLogTargets( new LogTarget[] { target } );
229         }
230         else
231         {
232             // use default LogTarget
233
if (defaultTarget == null)
234             {
235             logger.setLogTargets(new LogTarget[] { consoleTarget } );
236         }
237             else
238             {
239                 logger.setLogTargets(new LogTarget[] { defaultTarget } );
240             }
241         }
242
243         Logger result = new LogKitLogger(logger);
244
245         namedLoggers.put(name, result);
246
247         return result;
248     }
249
250
251     /**
252      * return the priority for a named logger. if no priority is
253      * specified for the requested name the priority of the first
254      * matching parent logger is returned.
255      * If there's no parent logger the factory default is returned.
256      *
257      * @param name the name of a logger
258      * @return the priority for that logger
259      */

260     public int getPriorityForNamedLogger(String JavaDoc name)
261     {
262         String JavaDoc prefix = name;
263
264         while (!prefix.equals(""))
265         {
266             String JavaDoc priorityString = null;
267
268             try
269             {
270                 int priorityForLogger =
271                     configuration.getAttributeAsInteger( prefix + ".log.verbosity");
272                 if (priorityForLogger > 4)
273                     priorityForLogger = 4;
274                 else if (priorityForLogger < 0)
275                     priorityForLogger = 0;
276                 return priorityForLogger;
277             }
278             catch( ConfigurationException ce )
279             {
280             }
281
282             if (prefix.lastIndexOf(".") >= 0)
283             {
284                 prefix = prefix.substring(0, prefix.lastIndexOf("."));
285             }
286             else
287             {
288                 prefix = "";
289             }
290         }
291
292         // nothing found, return default
293
return defaultPriority;
294     }
295
296
297     /**
298      * <code>intToPriority</code> returns the priority level for a given integer.
299      *
300      * @param priority an <code>int</code> value
301      * @return an <code>org.apache.log.Priority</code> value
302      */

303     public static org.apache.log.Priority intToPriority(int priority)
304     {
305         switch (priority)
306         {
307             case 4 :
308                 return org.apache.log.Priority.DEBUG;
309             case 3 :
310                 return org.apache.log.Priority.INFO;
311             case 2 :
312                 return org.apache.log.Priority.WARN;
313             case 1 :
314                 return org.apache.log.Priority.ERROR;
315             case 0 :
316             default :
317                 return org.apache.log.Priority.FATAL_ERROR;
318         }
319     }
320
321     public void setDefaultLogFile(String JavaDoc fileName, long maxLogSize) throws java.io.IOException JavaDoc
322     {
323         FileOutputStream logStream =
324             new FileOutputStream(fileName, append);
325
326         if (maxLogSize == 0)
327         {
328             // no log file rotation
329
Writer logWriter = new OutputStreamWriter(logStream);
330             defaultTarget = new WriterTarget(logWriter, logFormatter);
331         }
332         else
333         {
334             // use log file rotation
335
defaultTarget =
336                 new RotatingFileTarget(append,
337                                        logFormatter,
338                                        new RotateStrategyBySize(maxLogSize * 1000),
339                                        new RevolvingFileStrategy(new File(fileName), 10000));
340         }
341     }
342 }
343
Popular Tags