KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > jorphan > logging > LoggingManager


1 // $Header: /home/cvs/jakarta-jmeter/src/jorphan/org/apache/jorphan/logging/LoggingManager.java,v 1.13 2004/03/22 02:09:56 sebb Exp $
2
/*
3  * Copyright 2001-2004 The Apache Software Foundation.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17 */

18
19 package org.apache.jorphan.logging;
20
21 import java.io.FileWriter JavaDoc;
22 import java.io.IOException JavaDoc;
23 import java.io.PrintWriter JavaDoc;
24 import java.io.Writer JavaDoc;
25 import java.util.Iterator JavaDoc;
26 import java.util.Properties JavaDoc;
27
28 import org.apache.avalon.excalibur.logger.LogKitLoggerManager;
29 import org.apache.avalon.framework.configuration.Configuration;
30 import org.apache.avalon.framework.configuration.ConfigurationException;
31 import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
32 import org.apache.avalon.framework.context.Context;
33 import org.apache.avalon.framework.context.ContextException;
34 import org.apache.avalon.framework.context.DefaultContext;
35 import org.apache.jorphan.util.ClassContext;
36 import org.apache.log.Hierarchy;
37 import org.apache.log.LogTarget;
38 import org.apache.log.Logger;
39 import org.apache.log.Priority;
40 import org.apache.log.format.PatternFormatter;
41 import org.apache.log.output.NullOutputLogTarget;
42 import org.apache.log.output.io.WriterTarget;
43 import org.xml.sax.SAXException JavaDoc;
44
45 /**
46  * @version $Revision: 1.13 $ on $Date: 2004/03/22 02:09:56 $
47  */

48 public final class LoggingManager
49 {
50     // N.B time pattern is passed to java.text.SimpleDateFormat
51
/*
52      * Predefined format patterns, selected by the property log_format_type
53      * (see jmeter.properties)
54      * The new-line is added later
55      */

56     private static final String JavaDoc DEFAULT_PATTERN =
57         "%{time:yyyy/MM/dd HH:mm:ss} %5.5{priority} - "
58         + "%{category}: %{message} %{throwable}";
59     
60     private static final String JavaDoc PATTERN_THREAD_PREFIX =
61         "%{time:yyyy/MM/dd HH:mm:ss} %5.5{priority} "
62         + "%12{thread} %{category}: %{message} %{throwable}";
63
64     private static final String JavaDoc PATTERN_THREAD_SUFFIX =
65         "%{time:yyyy/MM/dd HH:mm:ss} %5.5{priority} "
66         + "%{category}[%{thread}]: %{message} %{throwable}";
67
68
69     private static PatternFormatter format = null;
70     
71     /** Used to hold the default logging target. */
72     private static LogTarget target;
73     
74     // Hack to detect when System.out has been set as the target, to avoid closing it
75
private static boolean isTargetSystemOut = false;// Is the target System.out?
76
private static boolean isWriterSystemOut = false;// Is the Writer System.out?
77

78     public final static String JavaDoc LOG_FILE = "log_file";
79     public final static String JavaDoc LOG_PRIORITY = "log_level";
80     private static LoggingManager logManager = null;
81
82     private LoggingManager()
83     {
84         // ensure that target is valid initially
85
target = new NullOutputLogTarget();
86     }
87
88     public static LoggingManager getLogManager()
89     {
90         return logManager;
91     }
92
93     /**
94      * Initialise the logging system from the Jmeter properties.
95      * Logkit loggers inherit from their parents.
96      *
97      * Normally the jmeter properties file defines a single log file, so
98      * set this as the default from "log_file", default "jmeter.log"
99      * The default priority is set from "log_level", with a default of INFO
100      *
101      */

102     public static void initializeLogging(Properties JavaDoc properties)
103     {
104         if (logManager == null)
105         {
106             logManager = new LoggingManager();
107         }
108
109         setFormat(properties);
110         
111         // Set the top-level defaults
112
setTarget(
113             makeWriter(
114                 properties.getProperty(LOG_FILE, "jmeter.log"),
115                 LOG_FILE));
116         setPriority(properties.getProperty(LOG_PRIORITY, "INFO"));
117
118         setLoggingLevels(properties);
119         // now set the individual categories (if any)
120

121         setConfig(properties);// Further configuration
122
}
123
124     private static void setFormat(Properties JavaDoc properties)
125     {
126             String JavaDoc pattern = DEFAULT_PATTERN;
127             String JavaDoc type = properties.getProperty("log_format_type","");
128             if (type.length()==0)
129             {
130                 pattern=properties.getProperty("log_format",DEFAULT_PATTERN);
131             }
132             else
133             {
134                 if (type.equalsIgnoreCase("thread_suffix"))
135                 {
136                     pattern=PATTERN_THREAD_SUFFIX;
137                 }
138                 else
139                 if (type.equalsIgnoreCase("thread_prefix"))
140                 {
141                     pattern=PATTERN_THREAD_PREFIX;
142                 }
143                 else
144                 {
145                     pattern=DEFAULT_PATTERN;
146                 }
147             }
148             format = new PatternFormatter(pattern+"\n");
149     }
150
151
152     private static void setConfig(Properties JavaDoc p)
153     {
154         String JavaDoc cfg = p.getProperty("log_config");
155         if (cfg==null) return;
156         
157         //Make sure same hierarchy is used
158
Hierarchy hier = Hierarchy.getDefaultHierarchy();
159         LogKitLoggerManager manager = new LogKitLoggerManager(
160                 null,hier,null,null
161                 );
162         
163         DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
164         try {
165             Configuration c = builder.buildFromFile(cfg);
166             Context ctx = new DefaultContext();
167             manager.contextualize(ctx);
168             manager.configure(c);
169         } catch (IllegalArgumentException JavaDoc e) {
170             // This happens if the default log-target id-ref specifies a non-existent target
171
System.out.println("Error processing logging config "+cfg);
172             System.out.println(e.toString());
173         } catch (NullPointerException JavaDoc e) {
174             // This can happen if a log-target id-ref specifies a non-existent target
175
System.out.println("Error processing logging config "+cfg);
176             System.out.println("Perhaps a log target is missing?");
177         } catch (ConfigurationException e) {
178             System.out.println("Error processing logging config "+cfg);
179             System.out.println(e.toString());
180         } catch (SAXException JavaDoc e) {
181             System.out.println("Error processing logging config "+cfg);
182             System.out.println(e.toString());
183         } catch (IOException JavaDoc e) {
184             System.out.println("Error processing logging config "+cfg);
185             System.out.println(e.toString());
186         } catch (ContextException e) {
187             System.out.println("Error processing logging config "+cfg);
188             System.out.println(e.toString());
189         }
190     }
191     /*
192      * Helper method to ensure that format is initialised if initializeLogging()
193      * has not yet been called.
194     */

195     private static PatternFormatter getFormat()
196     {
197         if (format == null)
198         {
199             format = new PatternFormatter(DEFAULT_PATTERN+"\n");
200         }
201         return format;
202     }
203     
204
205     /*
206      * Helper method to handle log target creation.
207      * If there is an error creating the file, then it uses System.out.
208      */

209     private static Writer JavaDoc makeWriter(String JavaDoc logFile, String JavaDoc propName)
210     {
211         Writer JavaDoc wt;
212         isWriterSystemOut=false;
213         try
214         {
215             wt = new FileWriter JavaDoc(logFile);
216         }
217         catch (Exception JavaDoc e)
218         {
219             System.out.println(propName + "=" + logFile + " " + e.toString());
220             System.out.println("[" + propName + "-> System.out]");
221             isWriterSystemOut=true;
222             wt = new PrintWriter JavaDoc(System.out);
223         }
224         return wt;
225     }
226
227     /*
228      * Handle LOG_PRIORITY.category=priority and LOG_FILE.category=file_name
229      * properties. If the prefix is detected, then remove it to get the
230      * category.
231      */

232     private static void setLoggingLevels(Properties JavaDoc appProperties)
233     {
234         Iterator JavaDoc props = appProperties.keySet().iterator();
235         while (props.hasNext())
236         {
237             String JavaDoc prop = (String JavaDoc) props.next();
238             if (prop.startsWith(LOG_PRIORITY + "."))
239                 // don't match the empty category
240
{
241                 String JavaDoc category = prop.substring(LOG_PRIORITY.length() + 1);
242                 setPriority(appProperties.getProperty(prop), category);
243             }
244             if (prop.startsWith(LOG_FILE + "."))
245             {
246                 String JavaDoc category = prop.substring(LOG_FILE.length() + 1);
247                 String JavaDoc file = appProperties.getProperty(prop);
248                 setTarget(
249                     new WriterTarget(makeWriter(file, prop), getFormat()),
250                     category);
251             }
252         }
253     }
254
255     private final static String JavaDoc PACKAGE_PREFIX = "org.apache.";
256
257     /*
258      * Stack contains the follow when the context is obtained:
259      * 0 - getCallerClassNameAt()
260      * 1 - this method
261      * 2 - getLoggerForClass
262      *
263      */

264     private static String JavaDoc getCallerClassName()
265     {
266         String JavaDoc name = ClassContext.getCallerClassNameAt(3);
267         if (name.startsWith(PACKAGE_PREFIX))
268         { // remove the package prefix
269
name = name.substring(PACKAGE_PREFIX.length());
270         }
271         return name;
272     }
273
274     /**
275      * Get the Logger for a class - no argument needed because the calling
276      * class name is derived automatically from the call stack.
277      *
278      * @return Logger
279      */

280     public static Logger getLoggerForClass()
281     {
282         String JavaDoc className = getCallerClassName();
283         return Hierarchy.getDefaultHierarchy().getLoggerFor(className);
284     }
285
286     public static Logger getLoggerFor(String JavaDoc category)
287     {
288         return Hierarchy.getDefaultHierarchy().getLoggerFor(category);
289     }
290
291     public static void setPriority(String JavaDoc p, String JavaDoc category)
292     {
293         setPriority(Priority.getPriorityForName(p), category);
294     }
295     public static void setPriority(Priority p, String JavaDoc category)
296     {
297         Hierarchy.getDefaultHierarchy().getLoggerFor(category).setPriority(p);
298     }
299     public static void setPriority(String JavaDoc p)
300     {
301         setPriority(Priority.getPriorityForName(p));
302     }
303     public static void setPriority(Priority p)
304     {
305         Hierarchy.getDefaultHierarchy().setDefaultPriority(p);
306     }
307     public static void setTarget(LogTarget target, String JavaDoc category)
308     {
309         Logger logger = Hierarchy.getDefaultHierarchy().getLoggerFor(category);
310         logger.setLogTargets(new LogTarget[] { target });
311     }
312     
313     /**
314      * Sets the default log target from the parameter.
315      * The existing target is first closed if necessary.
316      *
317      * @param targetFile (Writer)
318      */

319     public static void setTarget(Writer JavaDoc targetFile)
320     {
321         if (target == null)
322         {
323             target = getTarget(targetFile, getFormat());
324             isTargetSystemOut=isWriterSystemOut;
325         }
326         else
327         {
328             if (!isTargetSystemOut && target instanceof WriterTarget)
329             {
330                 ((WriterTarget) target).close();
331             }
332             target = getTarget(targetFile, getFormat());
333             isTargetSystemOut=isWriterSystemOut;
334         }
335         Hierarchy.getDefaultHierarchy().setDefaultLogTarget(target);
336     }
337     
338     private static LogTarget getTarget(Writer JavaDoc targetFile, PatternFormatter fmt)
339     {
340         return new WriterTarget(targetFile, fmt);
341     }
342 }
343
Popular Tags