KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openlaszlo > iv > flash > util > Log


1 /*
2  * $Id: Log.java,v 1.1 2002/02/24 02:11:24 skavish Exp $
3  *
4  * ===========================================================================
5  *
6  * The JGenerator Software License, Version 1.0
7  *
8  * Copyright (c) 2000 Dmitry Skavish (skavish@usa.net). All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  * notice, this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  * notice, this list of conditions and the following disclaimer in
18  * the documentation and/or other materials provided with the
19  * distribution.
20  *
21  * 3. The end-user documentation included with the redistribution, if
22  * any, must include the following acknowlegement:
23  * "This product includes software developed by Dmitry Skavish
24  * (skavish@usa.net, http://www.flashgap.com/)."
25  * Alternately, this acknowlegement may appear in the software itself,
26  * if and wherever such third-party acknowlegements normally appear.
27  *
28  * 4. The name "The JGenerator" must not be used to endorse or promote
29  * products derived from this software without prior written permission.
30  * For written permission, please contact skavish@usa.net.
31  *
32  * 5. Products derived from this software may not be called "The JGenerator"
33  * nor may "The JGenerator" appear in their names without prior written
34  * permission of Dmitry Skavish.
35  *
36  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
37  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
38  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
39  * DISCLAIMED. IN NO EVENT SHALL DMITRY SKAVISH OR THE OTHER
40  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
42  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
43  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
44  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
45  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
46  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47  * SUCH DAMAGE.
48  *
49  */

50
51 package org.openlaszlo.iv.flash.util;
52
53 import org.openlaszlo.iv.flash.api.*;
54 import java.io.*;
55 import java.net.*;
56 import java.util.*;
57
58 import org.apache.log4j.*;
59 import org.apache.log4j.spi.*;
60 import org.apache.log4j.helpers.*;
61
62 /**
63  * Logger
64  * <P>
65  * After replacing jgenerator native logging system with log4j
66  * all the jgenerator classes like FileLogger, ConsoleLogger etc. are gone.
67  * But I decided to keep this class Log to avoid changing a lot of code
68  * which uses it.
69  * <P>
70  * Instead I changed its implementation to make it a wrapper for log4j.
71  * <P>
72  * log4j has several level methods, like 'debug', 'warn' etc., but jgenerator Log
73  * has only one method 'log' which takes the level of a message from its
74  * resource key's first character. I preserved this schema, so now if you use
75  * this class's log method it will call corresponding log4j method based
76  * on the first character of the message key, otherwise you can call any of
77  * log4j methods directly or using new Log methods with the same signature.
78  * <P>
79  * The default initialization procedure:
80  * <UL>
81  * <LI>get property org.openlaszlo.iv.flash.log4j.configuration from iv.property file
82  * <LI>if it exists and contains valid url or file name (either relative to jgen home or absolute)
83  * then use this url to initialize log4j (it can be either xml or property based configuration)
84  * <LI>if the property does not exist or is not valid then use standard log4 initialization procedure,
85  * i.e. read system property log4j.configuration etc
86  * </UL>
87  *
88  * @author Dmitry Skavish
89  */

90 public class Log {
91
92     private static final String JavaDoc FQCN = Log.class.getName();
93
94     private static Logger logger;
95     private static final String JavaDoc filePattern = "%d [%p] - %m%n";
96     private static final String JavaDoc consolePattern = "%r [%p] - %m%n";
97
98     static {
99
100         String JavaDoc log4j_conf = PropertyManager.getProperty("org.openlaszlo.iv.flash.log4j.configuration");
101
102         if( log4j_conf != null ) {
103             URL url = null;
104             try {
105                 url = new URL(log4j_conf);
106             } catch( MalformedURLException e ) {
107                 File file = Util.getSysFile(log4j_conf);
108                 try {
109                     url = file.toURL();
110                 } catch( MalformedURLException ee ) {
111                 }
112             }
113
114             // configure log4j
115
if( url != null ) {
116                 OptionConverter.selectAndConfigure(url, null, LogManager.getLoggerRepository());
117             }
118         }
119
120         logger = Logger.getLogger("org.openlaszlo.iv.flash.Generator");
121         logger.setResourceBundle(Resource.getInstance());
122     }
123
124     /**
125      * Gets current logger
126      *
127      * @return current logger
128      */

129     public static Logger getLogger() {
130         return logger;
131     }
132
133     /**
134      * Sets new logger
135      * <P>
136      * If you set new logger you probably also need to set ResourceBundle to it
137      *
138      * @param logger new logger
139      */

140     public static void setLogger( Logger logger ) {
141         Log.logger = logger;
142     }
143
144     /**
145      * Sets log to console
146      */

147     public static void setLogToConsole() {
148         logger.removeAllAppenders();
149         logger.addAppender(new ConsoleAppender(new PatternLayout(consolePattern)));
150     }
151
152     /**
153      * Sets log to file
154      * <P>
155      * File specified in property org.openlaszlo.iv.flash.logFile
156      *
157      * @deprecated logging system is configured now using log4j configuration file
158      */

159  /* public static void setLogToFile() {
160         String fileName = PropertyManager.getProperty("org.openlaszlo.iv.flash.logFile", "logs/generator.log");
161         File file = Util.getSysFile(fileName);
162         fileName = file.getAbsolutePath();
163         setLogToFile(fileName);
164     }
165 */

166     /**
167      * Sets log to the specified file
168      *
169      * @deprecated logging system is configured now using log4j configuration file
170      */

171 /* public static void setLogToFile( String fileName ) {
172         try {
173             logger.removeAllAppenders();
174             logger.addAppender(new FileAppender(new PatternLayout(filePattern), fileName, true));
175         } catch( IOException e ) {
176             setLogToConsole();
177             log(e);
178         }
179     }
180 */

181     /**
182      * Logs IVException
183      * <P>
184      * IVException contains message with parameters inside
185      * and probably nested exception
186      *
187      * @param e exception to log
188      */

189     public static void logRB( IVException e ) {
190         log(e);
191     }
192
193     public static void log( IVException e ) {
194         String JavaDoc key = e.getMessageKey();
195         Level level = getMessageLevel(key);
196         if( !logger.isEnabledFor(level) ) return;
197
198         logger.log(FQCN, level, e.getLocalizedMessage(), e);
199     }
200
201     /**
202      * Logs Exception
203      *
204      * @param e exception to log
205      */

206     public static void logRB( Throwable JavaDoc t ) {
207         log(t);
208     }
209
210     public static void log( Throwable JavaDoc t ) {
211         if( t instanceof IVException ) {
212             log( (IVException) t );
213         } else {
214             error(t.getLocalizedMessage(), t);
215         }
216     }
217
218     /**
219      * Logs exception as message specified by its resource key
220      *
221      * @param key resource key
222      * @param p array of parameters
223      * @param t exception to log
224      */

225     public static void logRB( String JavaDoc key, Object JavaDoc[] p, Throwable JavaDoc t ) {
226         _logif(key, p, t);
227     }
228
229     /**
230      * Logs exception as message specified by its resource key
231      *
232      * @param key resource key
233      * @param p array of parameters
234      */

235     public static void logRB( String JavaDoc key, Object JavaDoc[] p ) {
236         _logif(key, p, null);
237     }
238
239     /**
240      * Logs exception as message specified by its resource key
241      *
242      * @param key resource key
243      * @param p array of parameters
244      */

245     public static void logRB( String JavaDoc key ) {
246         _logif(key, null, null);
247     }
248
249     /**
250      * Logs exception as message specified by its resource key
251      *
252      * @param key resource key
253      * @param p array of parameters
254      */

255     public static void logRB( String JavaDoc key, Throwable JavaDoc t ) {
256         _logif(key, null, t);
257     }
258
259     public static void infoRB( String JavaDoc key, Object JavaDoc[] parms ) {
260         _logif(Level.INFO, key, parms, null);
261     }
262
263     public static void infoRB( String JavaDoc key, Object JavaDoc[] parms, Throwable JavaDoc t ) {
264         _logif(Level.INFO, key, parms, t);
265     }
266
267     public static void debugRB( String JavaDoc key, Object JavaDoc[] parms ) {
268         _logif(Level.DEBUG, key, parms, null);
269     }
270
271     public static void debugRB( String JavaDoc key, Object JavaDoc[] parms, Throwable JavaDoc t ) {
272         _logif(Level.DEBUG, key, parms, t);
273     }
274
275     public static void errorRB( String JavaDoc key, Object JavaDoc[] parms ) {
276         _logif(Level.ERROR, key, parms, null);
277     }
278
279     public static void errorRB( String JavaDoc key, Object JavaDoc[] parms, Throwable JavaDoc t ) {
280         _logif(Level.ERROR, key, parms, t);
281     }
282
283     public static void fatalRB( String JavaDoc key, Object JavaDoc[] parms ) {
284         _logif(Level.FATAL, key, parms, null);
285     }
286
287     public static void fatalRB( String JavaDoc key, Object JavaDoc[] parms, Throwable JavaDoc t ) {
288         _logif(Level.FATAL, key, parms, t);
289     }
290
291     public static void warnRB( String JavaDoc key, Object JavaDoc[] parms ) {
292         _logif(Level.WARN, key, parms, null);
293     }
294
295     public static void warnRB( String JavaDoc key, Object JavaDoc[] parms, Throwable JavaDoc t ) {
296         _logif(Level.WARN, key, parms, t);
297     }
298
299     //
300
// methods which take a string not a resource bundle key
301
//
302

303     public static void info( Object JavaDoc msg ) {
304         logger.info(msg);
305     }
306
307     public static void info( Object JavaDoc msg, Throwable JavaDoc t ) {
308         logger.info(msg, t);
309     }
310
311     public static void debug( Object JavaDoc msg ) {
312         logger.debug(msg);
313     }
314
315     public static void debug( Object JavaDoc msg, Throwable JavaDoc t ) {
316         logger.debug(msg, t);
317     }
318
319     public static void error( Object JavaDoc msg ) {
320         logger.error(msg);
321     }
322
323     public static void error( Object JavaDoc msg, Throwable JavaDoc t ) {
324         logger.error(msg, t);
325     }
326
327     public static void fatal( Object JavaDoc msg ) {
328         logger.fatal(msg);
329     }
330
331     public static void fatal( Object JavaDoc msg, Throwable JavaDoc t ) {
332         logger.fatal(msg, t);
333     }
334
335     public static void warn( Object JavaDoc msg ) {
336         logger.warn(msg);
337     }
338
339     public static void warn( Object JavaDoc msg, Throwable JavaDoc t ) {
340         logger.warn(msg, t);
341     }
342
343      /**
344      * Checks if a messages specified by given key is enabled under current log level
345      *
346      * @param key message key
347      * @return true if message has to be logged
348      */

349     public static Level getMessageLevel( String JavaDoc key ) {
350         if( key == null || key.length() == 0 ) return Level.FATAL;
351         char ch = key.charAt(0);
352         switch(ch) {
353             case '0': return Level.FATAL;
354             case '1': return Level.ERROR;
355             case '2': return Level.WARN;
356             case '3': return Level.INFO;
357             case '4': return Level.DEBUG;
358             default: return Level.FATAL;
359         }
360     }
361
362     public static void setFatalLevel() {
363         logger.setLevel(Level.FATAL);
364     }
365
366     public static void setErrorLevel() {
367         logger.setLevel(Level.ERROR);
368     }
369
370     public static void setWarnLevel() {
371         logger.setLevel(Level.WARN);
372     }
373
374     public static void setInfoLevel() {
375         logger.setLevel(Level.INFO);
376     }
377
378     public static void setDebugLevel() {
379         logger.setLevel(Level.DEBUG);
380     }
381
382     /**
383       * Checks if specified message is enabled under current level and logs the message if it is
384       *
385       * @param key message key
386       * @param parms optional message parameters
387       * @param t optional exception
388       */

389     protected static void _logif( String JavaDoc key, Object JavaDoc[] parms, Throwable JavaDoc t ) {
390         _logif(getMessageLevel(key), key, parms, t);
391     }
392
393     /**
394       * Checks if specified level is enabled and logs the message if it is
395       *
396       * @param level specified logger level
397       * @param key message key
398       * @param parms optional message parameters
399       * @param t optional exception
400       */

401     protected static void _logif( Level level, String JavaDoc key, Object JavaDoc[] parms, Throwable JavaDoc t ) {
402         if( !logger.isEnabledFor(level) ) return;
403         _log(level, key, parms, t);
404     }
405
406    /**
407      * Logs specified message to current logger
408      * <P>
409      * This method does not call those methods in Logger which are supposed
410      * to be used, but instead calls appenders directly thus avoiding double
411      * checking for levels, however this can be easily replaced with standard
412      * method, just swap the comments
413      *
414      * @param level specified logger level
415      * @param key message key
416      * @param parms optional message parameters
417      * @param t optional exception
418      */

419     protected static void _log( Level level, String JavaDoc key, Object JavaDoc[] parms, Throwable JavaDoc t ) {
420         String JavaDoc message = getMessage(key, parms);
421         //logger.log(FQCN, level, message, t);
422
logger.callAppenders(new LoggingEvent(FQCN, logger, level, message, t));
423     }
424
425     /**
426      * Retrieves and formats a message given by its resource key
427      * <P>
428      * The messages is retrieved from resource bundle associated with current logger,
429      * then formatted using java.util.MessageFormat
430      *
431      * @param key resource key, if message is not found in the resource then the key is used as a message
432      * @param parms optional parameters
433      * @return formatted message
434      */

435     public static String JavaDoc getMessage( String JavaDoc key, Object JavaDoc[] parms ) {
436         return getMessage(logger.getResourceBundle(), key, parms);
437     }
438
439     /**
440      * Retrieves and formats a message given by its resource key
441      * <P>
442      * The messages is retrieved from specified resource bundle or from standard jgenerator
443      * bundle if the specified one is null, then the message is formatted using java.util.MessageFormat
444      *
445      * @param rb specified resource bundle
446      * @param key resource key, if message is not found in the resource then the key is used as a message
447      * @param parms optional parameters
448      * @return formatted message
449      */

450     public static String JavaDoc getMessage( ResourceBundle rb, String JavaDoc key, Object JavaDoc[] parms ) {
451         if( rb == null ) {
452             rb = Resource.getInstance();
453         }
454
455         String JavaDoc msg;
456         try {
457             msg = rb.getString(key);
458         } catch( MissingResourceException e ) {
459             msg = "No resource is associated with key \""+key+"\".";
460             error(msg);
461         } catch( Throwable JavaDoc t ) {
462             msg = "Error retrieving resource by key \""+key+"\".";
463             error(msg, t);
464         }
465
466         if( parms != null ) {
467             msg = java.text.MessageFormat.format(msg, parms);
468         }
469
470         return msg;
471     }
472
473 }
474
Popular Tags