Java日志组件 log5j 使用介绍

大家都很熟悉log4j啦,log5j在log4j的基础上提供了几个改进,应该说是简单和实用的封装。有趣的是log5j主页对自己名字的解释,因为要感谢JDK 1.5,所以才叫了这个名字,不知道是不是升级到JDK1.7以后叫log7j :)

主页是:http://code.google.com/p/log5j/ 大家可以看看,现在的版本是2.1.2。

log5j有几个封装是非常实用的,解释功能的同时我们稍微看看代码,有些很有趣的地方:

1,不需要指定log所在的类名了


原来的用法:

 

1     private static final Logger log = Logger.getLogger( FeedTask.class );

新用法:

1     private static final Logger log = Logger.getLogger();

这个可以避免复制的时候忘记改类名。

我们看看代码,Logger里的:

 

1     public static Logger getLogger() {
2         return getLogger(getCallerClassName(), true);
3     }
4   
5     private static String getCallerClassName() {
6         //有趣
7         return new Exception().getStackTrace()[2].getClassName();
8     }

 取类名的时候用的是new了一个Exception,直接截取没用反射,简单直接。

2,支持message的format
原来:
 

1     log.debug( "This thing broke: " + foo + " due to bar: " + bar + " on this thing: " + car );

现在:
 

1     log.debug( "This thing broke: %s due to bar: %s on this thing: %s", foo, bar, car );

这个也很方便,效率也提高了,默认用了java.util.Formatter。
我们看看代码:

LogEvent里的:
 

1     public String message() {
2         if (_params == null || _params.length == ) {
3             return _formatMessage;
4         else {
5            //有趣
6             return __tlMessageFormatter.get().format(_formatMessage, _params);
7         }
8     }

 其中format那部分共了工厂模式,实现的地方是:

 

01     public class DefaultMessageFormatter implements MessageFormatter {
02         private final Formatter _formatter;
03   
04         public DefaultMessageFormatter(Locale locale) {   
05  
06             //定义一个formatter
07             _formatter = new Formatter(locale);
08       }
09    
10       public String format(String format, Object... args) {
11           StringBuilder sb = (StringBuilder) _formatter.out();
12           try {
13               //格式化message
14               _formatter.format(format, args);
15               return sb.toString();
16           finally {
17               sb.setLength();
18           }
19       }
20    }

3,新接口
可以这样用:

 

1     private static final Log log = LogFactory.getLog();
2     try {    
3         // do something    
4         log.d("Success! Parameters f=$.10f and i=%d", f, i);  
5     catch (Exception e) {    
6         log.e(e, "Failure! Parameters f=$.10f and i=%d", f, i);    
7         // note: exception passed first separate from parameters  
8     }

这个作者也说,仁者见仁,智者见智了。
Log实现在LogImpl里,其实Logger这个类实现在AbstractLoggable,这里有个问题,重复了。
我们回到主线Logger的调用方式上来吧。

4,可以显式关闭Log。
这样用:

1 // initialization phase  
2 com.spinn3r.log5j.LogManager.enableExplicitShutdown();    ...   
3 // in the very end of the shutdown routine  
4 com.spinn3r.log5j.LogManager.shutdown();

 这个是说如果可以接受log message丢失,并且本身应用程序可以控制自身的初始化和销毁的话,可以用。
这个和log5j的异步log方式有关。

5,性能
简化的写法,看代码:
  Logger:
  
 

1     public void debug(java.lang.Object message) {
2         super.debug(String.valueOf(message));
3     }


 AbstractLoggable:
  
 

1     public void debug(String formatMessage, Object... params) {
2         if (_logger.isEnabled(LogLevel.DEBUG)) {
3              log(LogEvent.create(_logger, _logName, LogLevel.DEBUG,
4                     formatMessage, params));
5         }
6     }

可见,不需要用logger.isDebugEnabled()这样的代码了。

另外log5j是默认使用异步方式的。
主要实现在AsyncLogger里:

 

01 private static final int MAX_QUEUE_SIZE = 100000;
02  
03 private static final AtomicLong __errorCounter = new AtomicLong();
04  
05 //存LogEvent的Queue
06  private final BlockingQueue<LogEvent> __logEventQueue =
07            new ArrayBlockingQueue<LogEvent>(MAX_QUEUE_SIZE);
08  
09 //写Log的线程
10  private final WriterThread _writerThread;
11  
12 //加入Event
13  public void add(LogEvent event) {
14        if (!__logEventQueue.offer(event)) {
15            logFallback(event);
16        }
17    }

 这个是个生产者消费者模式,WriterThread是消费者。

你可能感兴趣的:(java,日志,log5j)