For log4j configuration, please refer to http://logging.apache.org/log4j/2.x/manual/configuration.html
1. 首先去官方下载apache-log4j-2.1-bin.tar.gz,解压后导入jar包,基本上你只需要导入下面两个jar包就可以了(xx是版本号):log4j-core-xx.jar和 log4j-api-xx.jar。
2. 将log4j-api-2.1.jar 和 log4j-core-2.1.jar 导入到project中。
3. 为log4j增加配置文件, 2.0版本中的配置只能为Xml和Json,而且要注意配置文件命名是log4j2.xml或者log4j2.json。
- <?xml version="1.0" encoding="UTF-8"?>
- <Configuration status="WARN">
- <Appenders>
- <Console name="Console" target="SYSTEM_OUT">
- <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
- </Console>
- </Appenders>
- <Loggers>
- <Root level="error">
- <AppenderRef ref="Console"/>
- </Root>
- </Loggers>
- </Configuration>
Once the file above is placed into the classpath as log4j2.xml you will get results identical to those listed above.
4. package com.logging;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
public class LogExample {
private static final Logger logger = LogManager.getLogger(LogExample.class);
public static void main(final String... args) {
logger.trace("Entering application.");
logger.error("Didn't do it.");
logger.trace("Exiting application.");
}
}
Comments: the result is like below:14:37:23.065 [main] ERROR com.logging.LogExample - Didn't do it.。
一直在寻找如何将log输出到一个特定的文件的xml配置,找了半天,在官网上找到了。http://logging.apache.org/log4j/2.x/manual/appenders.html#FileAppender
- <?xml version="1.0" encoding="UTF-8"?>
- <Configuration status="warn" name="MyApp" packages="">
- <Appenders>
- <File name="MyFile" fileName="logs/app.log">
- <PatternLayout>
- <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
- </PatternLayout>
- </File>
- <Async name="Async">
- <AppenderRef ref="MyFile"/>
- </Async>
- </Appenders>
- <Loggers>
- <Root level="error">
- <AppenderRef ref="Async"/>
- </Root>
- </Loggers>
- </Configuration>