Log4J 自定义字段介绍:进展:问题:下载代码溶液
介绍:
我正在尝试使用log4j记录其他字段,并且它的工作原理,但只有当我在代码中创建追加器而不是在log4j.properties中创建追加器时
进展:
- 本文使用了将转换字符添加到 log4j 1.1.3 的 PatternLayout
- 为log4j 1.2制作了一个示例应用程序
问题:
使用它将运行的属性文件,但不会使用 AppServerPatternLayout,因此不会显示自定义字段。
下载代码
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
主.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");
主.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");
并将其拉出在log4j.properties中,大写X
log4j.appender.stdout.layout.ConversionPattern=%X{Version}