自学内容网 自学内容网

Java程序打印日志

一、maven依赖

POM文件中添加以下依赖,maven依赖的jar包版本可以在maven central repository 查看

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.34</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.13</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>2.0.13</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-to-slf4j</artifactId>
<version>2.23.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.23.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.23.1</version>
<scope>compile</scope>
</dependency>

二、配置文件

在resources目录下新建log4j.properties配置文件,配置内容如下。

#指定打印级别和打印位置
log4j.rootLogger=DEBUG,console,infoFile,errorFile

#控制台输出
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Target=System.out
log4j.appender.console.Threshold=INFO
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [%-5p] [%t] - [%X{traceId}] - %c.%M():%L - %m%n

#输出info日志
log4j.appender.infoFile=org.apache.log4j.RollingFileAppender
log4j.appender.infoFile.File=./log/info.log
log4j.appender.infoFile.MaxFileSize=50mb
log4j.appender.infoFile.Threshold=INFO
log4j.appender.infoFile.layout=org.apache.log4j.PatternLayout
log4j.appender.infoFile.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [%-5p] [%t] - [%X{traceId}] - %c.%M():%L - %m%n

#info日志中指定打印的最低级别和最高级别
log4j.appender.infoFile.filter.infoFilter=org.apache.log4j.varia.LevelRangeFilter
log4j.appender.infoFile.filter.infoFilter.levelMin=INFO
log4j.appender.infoFile.filter.infoFilter.levelMax=INFO

#输出error日志
log4j.appender.errorFile=org.apache.log4j.RollingFileAppender
log4j.appender.errorFile.File=./log/error.log
log4j.appender.errorFile.MaxFileSize=50mb
log4j.appender.errorFile.Threshold=ERROR
log4j.appender.errorFile.layout=org.apache.log4j.PatternLayout
log4j.appender.errorFile.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [%-5p] [%t] - [%X{traceId}] - %c.%M():%L - %m%n

#打印sql日志
log4j.logger.org.mybatis=INFO
log4j.logger.java.sql=INFO
log4j.logger.java.sql.Statement=INFO
log4j.logger.java.sgl.ResultSet=INFO
log4j.logger.java.sq1.PreparedStatement=INFO

原文地址:https://blog.csdn.net/mingyonghu/article/details/140350539

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!