Java 使用 slf4j + log4j 写日志
没有SpringBoot等框架的情况下
pom.xml:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<properties> <slf4j.version>1.7.26</slf4j.version> </properties> <dependencies> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> </dependencies>
log4j.properties:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# priority: debug<info<warn<error # you cannot specify every priority with different file for log4j log4j.rootLogger=info,stdout,info,error #console log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} [%p] %m%n #info log4j.logger.info=info log4j.appender.info=org.apache.log4j.DailyRollingFileAppender log4j.appender.info.DatePattern='_'yyyy-MM-dd'.log' log4j.appender.info.File=logs/info/info.log log4j.appender.info.Append=true log4j.appender.info.Threshold=INFO log4j.appender.info.layout=org.apache.log4j.PatternLayout log4j.appender.info.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} [%p] %m%n log4j.appender.info.filter.infoFilter=org.apache.log4j.varia.LevelRangeFilter log4j.appender.info.filter.infoFilter.LevelMin=INFO log4j.appender.info.filter.infoFilter.LevelMax=INFO #error log4j.logger.error=error log4j.appender.error=org.apache.log4j.DailyRollingFileAppender log4j.appender.error.DatePattern='_'yyyy-MM-dd'.log' log4j.appender.error.File=logs/error/error.log log4j.appender.error.Append=true log4j.appender.error.Threshold=ERROR log4j.appender.error.layout=org.apache.log4j.PatternLayout log4j.appender.error.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} [%p] %m%n log4j.appender.error.filter.infoFilter=org.apache.log4j.varia.LevelRangeFilter log4j.appender.error.filter.infoFilter.LevelMin=ERROR log4j.appender.error.filter.infoFilter.LevelMax=ERROR
代码:
变量定义:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
private static final Logger log = LoggerFactory.getLogger(TestES_Insert.class);
使用:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
log.info("创建索引" + indexName + "成功!");
log.error("TestES_Insert 出错", e);