`

log4j 入门实例 (三) 输出布局(layout)

阅读更多
log4j提供了以下几种layout
- org.apache.log4j.HTMLLayout (以HTML表格形式布局)
- org.apache.log4j.SimpleLayout (包含日志信息的级别和信息字符串)
- org.apache.log4j.TTCCLayout (包含日志产生的时间,执行绪,类别等信息。)
- org.apache.log4j.PatternLayout (可以灵活的指定布局模式)


这里看一下SimpleLayout的输出:

DEBUG - In the main method
INFO - This is info message
ERROR - This is error message
FATAL - This is fatal message

只有级别和信息被显示了出来

这里的难点是日志信息的样式的自定义。
自定义是通过log4j的转换字符实现的。具体信息在http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html

自定义实例1:
log4j.appender.appender2=org.apache.log4j.ConsoleAppender
log4j.appender.appender2.layout=org.apache.log4j.PatternLayout
log4j.appender.appender2.layout.ConversionPattern=%r [%t] %p %c %l %m%n
这个设定会输出以下的console信息:
0 [main] DEBUG com.lj.log4j.HelloLog4J com.lj.log4j.HelloLog4J.main(HelloLog4J.java:12) In the main method
4 [main] INFO com.lj.log4j.HelloLog4J com.lj.log4j.HelloLog4J.main(HelloLog4J.java:13) This is info message
5 [main] ERROR com.lj.log4j.HelloLog4J com.lj.log4j.HelloLog4J.main(HelloLog4J.java:14) This is error message
5 [main] FATAL com.lj.log4j.HelloLog4J com.lj.log4j.HelloLog4J.main(HelloLog4J.java:15) This is fatal message

%r -表示从创建该layout到该事件发生之间所经过的时间
[%t] -中括号没有特殊意义,表示就那么放在信息中。 %t表示执行该事件的线程的名称
%p -表示该日志事件的优先级, 比如INFO ,DEBUG
%c -表示该事件所在的完整类别名。 这里如果写%c{1},就会显示为HelloLog4J,就没有包名了。
%m -输出日志信息
%n -换行符



自定义实例2:
log4j.appender.appender2=org.apache.log4j.ConsoleAppender
log4j.appender.appender2.layout=org.apache.log4j.PatternLayout
log4j.appender.appender2.layout.ConversionPattern=[%d{yy/MM/dd HH:mm:ss:SSS}][%C-%M]%m%n

上面的代码会生成以下的log信息:
hello log4j
[13/12/12 19:20:17:802][com.lj.log4j.HelloLog4J-main]In the main method
[13/12/12 19:20:17:807][com.lj.log4j.HelloLog4J-main]This is info message
[13/12/12 19:20:17:807][com.lj.log4j.HelloLog4J-main]This is error message
[13/12/12 19:20:17:807][com.lj.log4j.HelloLog4J-main]This is fatal message

前面的是日期格式, 是由%d{}设定的。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics