KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jivesoftware > util > Log


1 /**
2  * $RCSfile: Log.java,v $
3  * $Revision: 1.9 $
4  * $Date: 2005/05/27 18:55:44 $
5  *
6  * Copyright (C) 1999-2004 Jive Software. All rights reserved.
7  *
8  * This software is the proprietary information of Jive Software.
9  * Use is subject to license terms.
10  */

11
12 package org.jivesoftware.util;
13
14 import org.jivesoftware.util.log.Hierarchy;
15 import org.jivesoftware.util.log.LogTarget;
16 import org.jivesoftware.util.log.Logger;
17 import org.jivesoftware.util.log.Priority;
18 import org.jivesoftware.util.log.format.ExtendedPatternFormatter;
19 import org.jivesoftware.util.log.output.io.StreamTarget;
20 import org.jivesoftware.util.log.output.io.rotate.RevolvingFileStrategy;
21 import org.jivesoftware.util.log.output.io.rotate.RotateStrategyBySize;
22 import org.jivesoftware.util.log.output.io.rotate.RotatingFileTarget;
23
24 import java.io.File JavaDoc;
25 import java.io.IOException JavaDoc;
26 import java.io.PrintWriter JavaDoc;
27 import java.io.StringWriter JavaDoc;
28 import java.util.ArrayList JavaDoc;
29 import java.util.List JavaDoc;
30 import java.util.logging.Handler JavaDoc;
31 import java.util.logging.Level JavaDoc;
32 import java.util.logging.LogRecord JavaDoc;
33
34 /**
35  * Simple wrapper to the incorporated LogKit to log under a single logging name.
36  *
37  * @author Bruce Ritchie
38  */

39 public class Log {
40
41     private static final Logger debugLog = Hierarchy.getDefaultHierarchy().getLoggerFor("Jive-DEBUG");
42     private static final Logger infoLog = Hierarchy.getDefaultHierarchy().getLoggerFor("Jive-INFO");
43     private static final Logger warnLog = Hierarchy.getDefaultHierarchy().getLoggerFor("Jive-WARN");
44     private static final Logger errorLog = Hierarchy.getDefaultHierarchy().getLoggerFor("Jive-ERR");
45
46     private static String JavaDoc logNameDebug = null;
47     private static String JavaDoc logNameInfo = null;
48     private static String JavaDoc logNameWarn = null;
49     private static String JavaDoc logNameError = null;
50     private static String JavaDoc debugPattern = null;
51     private static String JavaDoc infoPattern = null;
52     private static String JavaDoc warnPattern = null;
53     private static String JavaDoc errorPattern = null;
54     private static String JavaDoc logDirectory = null;
55
56     private static long maxDebugSize = 1024;
57     private static long maxInfoSize = 1024;
58     private static long maxWarnSize = 1024;
59     private static long maxErrorSize = 1024;
60
61     private static boolean debugEnabled;
62
63     static {
64         initLog();
65     }
66
67     private Log() { }
68
69     /**
70      * This method is used to initialize the Log class. For normal operations this method
71      * should <b>never</b> be called, rather it's only publically available so that the class
72      * can be reset by the setup process once the home directory has been specified.
73      */

74     public static void initLog() {
75         try {
76             logDirectory = JiveGlobals.getXMLProperty("log.directory");
77             if (logDirectory == null) {
78                 if (JiveGlobals.getHomeDirectory() != null) {
79                     File JavaDoc messengerHome = new File JavaDoc(JiveGlobals.getHomeDirectory());
80                     if (messengerHome.exists() && messengerHome.canWrite()) {
81                         logDirectory = (new File JavaDoc(messengerHome, "logs")).toString();
82                     }
83                 }
84             }
85
86             if (!logDirectory.endsWith(File.separator)) {
87                 logDirectory = logDirectory + File.separator;
88             }
89
90             // Make sure the logs directory exists. If not, make it:
91
File JavaDoc logDir = new File JavaDoc(logDirectory);
92             if (!logDir.exists()) {
93                 logDir.mkdir();
94             }
95
96             logNameDebug = logDirectory + "debug.log";
97             logNameInfo = logDirectory + "info.log";
98             logNameWarn = logDirectory + "warn.log";
99             logNameError = logDirectory + "error.log";
100
101             debugPattern = JiveGlobals.getXMLProperty("log.debug.format");
102             infoPattern = JiveGlobals.getXMLProperty("log.info.format");
103             warnPattern = JiveGlobals.getXMLProperty("log.warn.format");
104             errorPattern = JiveGlobals.getXMLProperty("log.error.format");
105
106             try { maxDebugSize = Long.parseLong(JiveGlobals.getXMLProperty("log.debug.size")); }
107             catch (NumberFormatException JavaDoc e) { /* ignore */ }
108             try { maxInfoSize = Long.parseLong(JiveGlobals.getXMLProperty("log.info.size")); }
109             catch (NumberFormatException JavaDoc e) { /* ignore */ }
110             try { maxWarnSize = Long.parseLong(JiveGlobals.getXMLProperty("log.warn.size")); }
111             catch (NumberFormatException JavaDoc e) { /* ignore */ }
112             try { maxErrorSize = Long.parseLong(JiveGlobals.getXMLProperty("log.error.size")); }
113             catch (NumberFormatException JavaDoc e) { /* ignore */ }
114
115             debugEnabled = "true".equals(JiveGlobals.getXMLProperty("log.debug.enabled"));
116         }
117         catch (Exception JavaDoc e) {
118             // we'll get an exception if home isn't setup yet - we ignore that since
119
// it's sure to be logged elsewhere :)
120
}
121
122         if (debugPattern == null) {
123             debugPattern = "%{time:yyyy.MM.dd HH:mm:ss} %{message}\\n%{throwable}";
124         }
125         if (infoPattern == null) {
126             infoPattern = "%{time:yyyy.MM.dd HH:mm:ss} %{message}\\n%{throwable}";
127         }
128         if (warnPattern == null) {
129             warnPattern = "%{time:yyyy.MM.dd HH:mm:ss} %{message}\\n%{throwable}";
130         }
131         if (errorPattern == null) {
132             errorPattern = "%{time:yyyy.MM.dd HH:mm:ss} [%{method}] %{message}\\n%{throwable}";
133         }
134
135         createLogger(debugPattern, logNameDebug, maxDebugSize, debugLog, Priority.DEBUG);
136         createLogger(infoPattern, logNameInfo, maxInfoSize, infoLog, Priority.INFO);
137         createLogger(warnPattern, logNameWarn, maxWarnSize, warnLog, Priority.WARN);
138         createLogger(errorPattern, logNameError, maxErrorSize, errorLog, Priority.ERROR);
139
140         // set up the ties into jdk logging
141
Handler JavaDoc jdkLogHandler = new JiveLogHandler();
142         jdkLogHandler.setLevel(Level.ALL);
143         java.util.logging.Logger.getLogger("").addHandler(jdkLogHandler);
144     }
145
146     private static void createLogger(String JavaDoc pattern, String JavaDoc logName, long maxLogSize,
147             Logger logger, Priority priority)
148     {
149         // debug log file
150
ExtendedPatternFormatter formatter = new ExtendedPatternFormatter(pattern);
151         StreamTarget target = null;
152         Exception JavaDoc ioe = null;
153
154         try {
155             // home was not setup correctly
156
if (logName == null) {
157                 throw new IOException JavaDoc("LogName was null - MessengerHome not set?");
158             }
159             else {
160                 RevolvingFileStrategy fileStrategy = new RevolvingFileStrategy(logName, 5);
161                 RotateStrategyBySize rotateStrategy = new RotateStrategyBySize(maxLogSize * 1024);
162                 target = new RotatingFileTarget(formatter, rotateStrategy, fileStrategy);
163             }
164         }
165         catch (IOException JavaDoc e) {
166             ioe = e;
167             // can't log to file, log to stderr
168
target = new StreamTarget(System.err, formatter);
169         }
170
171         logger.setLogTargets(new LogTarget[] { target } );
172         logger.setPriority(priority);
173
174         if (ioe != null) {
175             logger.debug("Error occurred opening log file: " + ioe.getMessage());
176         }
177     }
178
179     public static void setProductName(String JavaDoc productName) {
180         debugPattern = productName + " " + debugPattern;
181         infoPattern = productName + " " + infoPattern;
182         warnPattern = productName + " " + warnPattern;
183         errorPattern = productName + " " + errorPattern;
184
185         createLogger(debugPattern, logNameDebug, maxDebugSize, debugLog, Priority.DEBUG);
186         createLogger(infoPattern, logNameInfo, maxInfoSize, infoLog, Priority.INFO);
187         createLogger(warnPattern, logNameWarn, maxWarnSize, warnLog, Priority.WARN);
188         createLogger(errorPattern, logNameError, maxErrorSize, errorLog, Priority.ERROR);
189     }
190
191     public static boolean isErrorEnabled() {
192         return errorLog.isErrorEnabled();
193     }
194
195     public static boolean isFatalEnabled() {
196         return errorLog.isFatalErrorEnabled();
197     }
198
199     public static boolean isDebugEnabled() {
200         return debugEnabled;
201     }
202
203     public static void setDebugEnabled(boolean enabled) {
204         JiveGlobals.setXMLProperty("log.debug.enabled", Boolean.toString(enabled));
205         debugEnabled = enabled;
206     }
207
208     public static boolean isInfoEnabled() {
209         return infoLog.isInfoEnabled();
210     }
211
212     public static boolean isWarnEnabled() {
213         return warnLog.isWarnEnabled();
214     }
215
216     public static void debug(String JavaDoc s) {
217         if (isDebugEnabled()) {
218             debugLog.debug(s);
219         }
220     }
221
222     public static void debug(Throwable JavaDoc throwable) {
223         if (isDebugEnabled()) {
224             debugLog.debug("", throwable);
225         }
226     }
227
228     public static void debug(String JavaDoc s, Throwable JavaDoc throwable) {
229         if (isDebugEnabled()) {
230             debugLog.debug(s, throwable);
231         }
232     }
233
234     public static void markDebugLogFile(String JavaDoc username) {
235         RotatingFileTarget target = (RotatingFileTarget) debugLog.getLogTargets()[0];
236         markLogFile(username, target);
237     }
238
239     public static void rotateDebugLogFile() {
240         RotatingFileTarget target = (RotatingFileTarget) debugLog.getLogTargets()[0];
241         try {
242             target.rotate();
243         }
244         catch (IOException JavaDoc e) {
245             System.err.println("Warning: There was an error rotating the Jive debug log file. " +
246                     "Logging may not work correctly until a restart happens.");
247         }
248     }
249
250     public static void info(String JavaDoc s) {
251         if (isInfoEnabled()) {
252             infoLog.info(s);
253         }
254     }
255
256     public static void info(Throwable JavaDoc throwable) {
257         if (isInfoEnabled()) {
258             infoLog.info("", throwable);
259         }
260     }
261
262     public static void info(String JavaDoc s, Throwable JavaDoc throwable) {
263         if (isInfoEnabled()) {
264             infoLog.info(s, throwable);
265         }
266     }
267
268     public static void markInfoLogFile(String JavaDoc username) {
269         RotatingFileTarget target = (RotatingFileTarget) infoLog.getLogTargets()[0];
270         markLogFile(username, target);
271     }
272
273     public static void rotateInfoLogFile() {
274         RotatingFileTarget target = (RotatingFileTarget) infoLog.getLogTargets()[0];
275         try {
276             target.rotate();
277         }
278         catch (IOException JavaDoc e) {
279             System.err.println("Warning: There was an error rotating the Jive info log file. " +
280                     "Logging may not work correctly until a restart happens.");
281         }
282     }
283
284     public static void warn(String JavaDoc s) {
285         if (isWarnEnabled()) {
286             warnLog.warn(s);
287         }
288     }
289
290     public static void warn(Throwable JavaDoc throwable) {
291         if (isWarnEnabled()) {
292             warnLog.warn("", throwable);
293         }
294     }
295
296     public static void warn(String JavaDoc s, Throwable JavaDoc throwable) {
297         if (isWarnEnabled()) {
298             warnLog.warn(s, throwable);
299         }
300     }
301
302     public static void markWarnLogFile(String JavaDoc username) {
303         RotatingFileTarget target = (RotatingFileTarget) warnLog.getLogTargets()[0];
304         markLogFile(username, target);
305     }
306
307     public static void rotateWarnLogFile() {
308         RotatingFileTarget target = (RotatingFileTarget) warnLog.getLogTargets()[0];
309         try {
310             target.rotate();
311         }
312         catch (IOException JavaDoc e) {
313             System.err.println("Warning: There was an error rotating the Jive warn log file. " +
314                     "Logging may not work correctly until a restart happens.");
315         }
316     }
317
318     public static void error(String JavaDoc s) {
319         if (isErrorEnabled()) {
320             errorLog.error(s);
321             if (isDebugEnabled()) {
322                 printToStdErr(s, null);
323             }
324         }
325     }
326
327     public static void error(Throwable JavaDoc throwable) {
328         if (isErrorEnabled()) {
329             errorLog.error("", throwable);
330             if (isDebugEnabled()) {
331                 printToStdErr(null, throwable);
332             }
333         }
334     }
335
336     public static void error(String JavaDoc s, Throwable JavaDoc throwable) {
337         if (isErrorEnabled()) {
338             errorLog.error(s, throwable);
339             if (isDebugEnabled()) {
340                 printToStdErr(s, throwable);
341             }
342         }
343     }
344
345     public static void markErrorLogFile(String JavaDoc username) {
346         RotatingFileTarget target = (RotatingFileTarget) errorLog.getLogTargets()[0];
347         markLogFile(username, target);
348     }
349
350     public static void rotateErrorLogFile() {
351         RotatingFileTarget target = (RotatingFileTarget) errorLog.getLogTargets()[0];
352         try {
353             target.rotate();
354         }
355         catch (IOException JavaDoc e) {
356             System.err.println("Warning: There was an error rotating the Jive error log file. " +
357                     "Logging may not work correctly until a restart happens.");
358         }
359     }
360
361     public static void fatal(String JavaDoc s) {
362         if (isFatalEnabled()) {
363             errorLog.fatalError(s);
364             if (isDebugEnabled()) {
365                 printToStdErr(s, null);
366             }
367         }
368     }
369
370     public static void fatal(Throwable JavaDoc throwable) {
371         if (isFatalEnabled()) {
372             errorLog.fatalError("", throwable);
373             if (isDebugEnabled()) {
374                 printToStdErr(null, throwable);
375             }
376         }
377     }
378
379     public static void fatal(String JavaDoc s, Throwable JavaDoc throwable) {
380         if (isFatalEnabled()) {
381             errorLog.fatalError(s, throwable);
382             if (isDebugEnabled()) {
383                 printToStdErr(s, throwable);
384             }
385         }
386     }
387
388     /**
389      * Returns the directory that log files exist in. The directory name will
390      * have a File.separator as the last character in the string.
391      *
392      * @return the directory that log files exist in.
393      */

394     public static String JavaDoc getLogDirectory() {
395         return logDirectory;
396     }
397
398     private static void markLogFile(String JavaDoc username, RotatingFileTarget target) {
399         List JavaDoc args = new ArrayList JavaDoc();
400         args.add(username);
401         args.add(JiveGlobals.formatDateTime(new java.util.Date JavaDoc()));
402         target.write(LocaleUtils.getLocalizedString("log.marker_inserted_by", args) + "\n");
403     }
404
405     private static void printToStdErr(String JavaDoc s, Throwable JavaDoc throwable) {
406         if (s != null) {
407             System.err.println(s);
408         }
409         if (throwable != null) {
410             StringWriter JavaDoc sw = new StringWriter JavaDoc();
411             PrintWriter JavaDoc pw = new PrintWriter JavaDoc(sw);
412             throwable.printStackTrace(pw);
413             System.err.print(sw.toString());
414             System.err.print("\n");
415         }
416     }
417
418     private static final class JiveLogHandler extends Handler JavaDoc {
419
420         public void publish(LogRecord JavaDoc record) {
421
422             Level JavaDoc level = record.getLevel();
423             Throwable JavaDoc throwable = record.getThrown();
424
425
426             if (Level.SEVERE.equals(level)) {
427
428                 if (throwable != null) {
429                     Log.error(record.getMessage(), throwable);
430                 }
431                 else {
432                     Log.error(record.getMessage());
433                 }
434
435             }
436             else if (Level.WARNING.equals(level)) {
437
438                 if (throwable != null) {
439                     Log.warn(record.getMessage(), throwable);
440                 }
441                 else {
442                     Log.warn(record.getMessage());
443                 }
444
445
446             }
447             else if (Level.INFO.equals(level)) {
448
449                 if (throwable != null) {
450                     Log.info(record.getMessage(), throwable);
451                 }
452                 else {
453                     Log.info(record.getMessage());
454                 }
455
456             }
457             else {
458                 // else FINE,FINER,FINEST
459

460                 if (throwable != null) {
461                     Log.debug(record.getMessage(), throwable);
462                 }
463                 else {
464                     Log.debug(record.getMessage());
465                 }
466
467             }
468         }
469
470         public void flush() {
471             // do nothing
472
}
473
474         public void close() throws SecurityException JavaDoc {
475             // do nothing
476
}
477     }
478
479 }
Popular Tags