文章目录[隐藏]
最近想尝试在通过Gradle配置Log4j,运行后并未有相关日志输出以及任何报错或警告。找了一圈感觉总少一个步骤,后续尝试配置出来了,感觉主要是配置以及相关java文件路径这块很多教程都未提及。
Gradle 配置添加依赖
dependencies {
implementation 'org.apache.logging.log4j:log4j-api:2.19.0'
implementation 'org.apache.logging.log4j:log4j-core:2.19.0'
}
配置文件
- 路径参考
|--main
| |--java
| |--info.emperinter
| |--main.java
|--resources
| |--log4j2.xml
- log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{yyyy-MM-dd' 'HH:mm:ss.SSS} [%8t] [%-4level] %-36logger{36} - | %msg%n"/>
</Console>
<File name="all_logs_file" fileName="logs/all.log">
<PatternLayout>
<pattern>%d %p %c{1.} [%t] %m%n</pattern>
</PatternLayout>
</File>
<File name="important_logs_file" fileName="logs/important.log">
<Filters>
<ThresholdFilter level="warn" onMatch="ACCEPT" onMismatch="DENY"/>
</Filters>
<PatternLayout>
<pattern>%d %p %c{1.} [%t] %m%n</pattern>
</PatternLayout>
</File>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="console"/>
<AppenderRef ref="all_logs_file"/>
<AppenderRef ref="important_logs_file"/>
</Root>
</Loggers>
</Configuration>
使用
- main.java
package info.emperinter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class main {
static Logger logger = LogManager.getLogger(main.class.getName());
public static void main(String[] args) {
long start = System.currentTimeMillis();
logger.info("log4j start test");
logger.info("log4j end test");
long end = System.currentTimeMillis();
logger.info("main thread cost:" + (end - start) + "ms");
}
}
参考
- https://logging.apache.org/log4j/2.x/