Java Log4j 日志中的类路径显示首字母缩写 有更新!

  |   0 评论   |   192 浏览

Java在Log4j日志中显示首字母,如com.abc.def.ClassName日志中显示为c.a.d.ClassName,配置如下:

log4j.rootLogger=stdout, dailyFile

#stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.EnhancedPatternLayout
#log4j.appender.stdout.layout.ConversionPattern=%d %-5p [%c{5}] - %m%n
log4j.appender.stdout.layout.ConversionPattern=%d{MM-dd HH:mm} [%-30.30c{1.}] %m%n

#DailyFile
log4j.appender.dailyFile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.dailyFile.File=C:/logs/hour/log.log
log4j.appender.dailyFile.ImmediateFlush=true
log4j.appender.dailyFile.DatePattern='.'yyyy-MM-dd-HH'.log'
log4j.appender.dailyFile.layout=org.apache.log4j.EnhancedPatternLayout
log4j.appender.dailyFile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p [%-30.30c{1.}] %m%n

首先,将默认使用的PatternLayout替换为EnhancedPatternLayout,然后将显示类路径的参数c后增加{1.},如上示例所示,其中1表示显示最终的类名称,2表示显示倒数两层路径全名,打印日志如下:

03-21 13:37 [c.x.m.b.d.O.findList    ] ==>  Preparing: SELEC T a.id, a.title, a.content, a.tags FROM blog a limit 15
03-21 13:37 [c.x.m.b.d.O.findList    ] ==> Parameters: 
03-21 13:37 [c.x.m.b.d.O.findList    ] <==      Total: 15
03-21 13:38 [c.x.m.s.i.LogInterceptor] [admin],结束: 2019.03.21 13:38:20  耗时:0:0:03.445  地址: /blog/oschinaBlog 

参见:https://stackoverflow.com/questions/7891910/log4j-abbreviate-shorten-package-names

评论

发表评论