java – Log4J自定义字段

介绍:

我正在尝试使用log4j获取额外的字段来记录,它的工作,但是只有当我在代码中创建一个appender而不是在log4j.properties中

进展:

>使用本文Adding Conversion Characters to PatternLayout for log4j 1.1.3
>制作sample app for log4j 1.2

问题:

使用它将运行的属性文件,但不会使用AppServerPatternLayout,因此不显示自定义字段.

Download Code

customlog.properties

log4j.rootLogger=FATAL
log4j.logger.some.log=INFO,stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=logging.AppServerPatternLayout
log4j.appender.stdout.layout.ConversionPattern=-----------------using log file------------------------%nTime:      %d%nHost:      %h%nServer:    %s%nComponent: %b%nVersion:   %v%nPriority:  %p%nThread Id: %t%nContext:   %x%nMessage:   %m%n

Main.java日志记录没有log4j属性文件

AppServerLoggerFactory factory;
factory = new AppServerLoggerFactory("MyServer", "MyComponent", "1.0");
AppServerLogger.setFactory(factory);
Logger logger = AppServerLogger.getLogger("some.log");
PatternLayout layout = new AppServerPatternLayout( formatString );
logger.addAppender( new ConsoleAppender(layout) );
logger.info("Hello");

Main.java日志记录与log4j属性文件

PropertyConfigurator.configure("customlog.properties");
AppServerLoggerFactory factory;
factory = new AppServerLoggerFactory("MyServer", "MyComponent", "1.0");
AppServerLogger.setFactory(factory);
Logger logger = AppServerLogger.getLogger("some.log");
logger.info("Hello");

预期产量

----------------using in code appender----------------------
Time:      2009-11-06 12:55:05,785
Host:      M1330
Server:    MyServer
Component: MyComponent
Version:   1.0
Priority:  INFO
Thread Id: main
Context:   
Message:   logging config from code

实际输出

-----------------using log file------------------------
Time:      2009-11-06 12:56:17,983
Host:      
Server:    
Component: 
Version:   
Priority:  INFO
Thread Id: main
Context:   
Message:   logging config from customlog.properties

使用MDC可以添加自定义字段

MDC.put("Version", versionName);
Logger log = LogManager.getLogger("some.log");        
log.info("Hello");

并使用UPPER案例X在log4j.properties中将其拉出

log4j.appender.stdout.layout.ConversionPattern=%X{Version}
从您发布的示例中,我只能猜测AppServerPatternLayout不在包日志记录中.一切都找到.加

log4j.DEBUG=true

到你的属性文件.然后,log4j将在读取属性时转储它所做的工作.也许这给你一个想法是什么问题.

如果没有帮助,考虑使用Nested Diagnostic Contexts.

http://stackoverflow.com/questions/1687473/log4j-custom-fields

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:java – Log4J自定义字段