View Javadoc

1   package org.yajul.log;
2   
3   import org.apache.log4j.Priority;
4   import org.apache.log4j.Logger;
5   
6   import java.text.MessageFormat;
7   import java.util.logging.Handler;
8   import java.util.logging.Level;
9   import java.util.logging.LogRecord;
10  
11  /***
12   * A JULI (java.util.logging) handler that redirects java.util.logging messages to Log4J
13   * http://wiki.apache.org/myfaces/Trinidad_and_Common_Logging
14   * <br>
15   * User: josh
16   * Date: Jun 4, 2008
17   * Time: 3:31:21 PM
18   */
19  public class JuliToLog4jHandler extends Handler {
20  
21      public void publish(LogRecord record) {
22          org.apache.log4j.Logger log4j = getTargetLogger(record.getLoggerName());
23          Priority priority = toLog4j(record.getLevel());
24          log4j.log(priority, toLog4jMessage(record), record.getThrown());
25      }
26  
27      static Logger getTargetLogger(String loggerName) {
28          return Logger.getLogger(loggerName);
29      }
30  
31      public static Logger getTargetLogger(Class clazz) {
32          return getTargetLogger(clazz.getName());
33      }
34      
35      private String toLog4jMessage(LogRecord record) {
36          String message = record.getMessage();
37          // Format message
38          try {
39              Object parameters[] = record.getParameters();
40              if (parameters != null && parameters.length != 0) {
41                  // Check for the first few parameters ?
42                  if (message.indexOf("{0}") >= 0 ||
43                          message.indexOf("{1}") >= 0 ||
44                          message.indexOf("{2}") >= 0 ||
45                          message.indexOf("{3}") >= 0) {
46                      message = MessageFormat.format(message, parameters);
47                  }
48              }
49          }
50          catch (Exception ex) {
51              // ignore Exception
52          }
53          return message;
54      }
55  
56      private org.apache.log4j.Level toLog4j(Level level) {//converts levels
57          if (Level.SEVERE == level) {
58              return org.apache.log4j.Level.ERROR;
59          } else if (Level.WARNING == level) {
60              return org.apache.log4j.Level.WARN;
61          } else if (Level.INFO == level) {
62              return org.apache.log4j.Level.INFO;
63          } else if (Level.OFF == level) {
64              return org.apache.log4j.Level.OFF;
65          }
66          return org.apache.log4j.Level.OFF;
67      }
68  
69      @Override
70      public void flush() {
71          // nothing to do
72      }
73  
74      @Override
75      public void close() {
76          // nothing to do
77      }
78  }