Log4j 日志框架(旧版)
小于 1 分钟
"最早" 的日志框架
注意
该日志框架已处于日落生命周期中。
直接使用
依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.example</groupId>
<artifactId>demo-java-log</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>demo-usage-log4j-basic</artifactId>
<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</dependency>
</dependencies>
</project>
配置文件
# 日志级别,appender,... (rootLogger 表示全局)
log4j.rootLogger=INFO,stdout,a2
# 日志级别,appender,... (作用范围 org.example 包下) (appender 继承父级)
log4j.logger.org.example=DEBUG
# 配置输出器 (这里 stdout 自定义输出器名称) —— 输出到控制台
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.Threshold=DEBUG
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# %p 日志级别 %c 全类名 %L 行数 %m 日志信息 %n 换行
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %20c %L:%m %n
# 配置输出器 —— 输出到文件
log4j.appender.a2=org.apache.log4j.RollingFileAppender
# log4j.appender.a2.File=${user.home}/temp/log-demo/log4j/a2.log
log4j.appender.a2.File=target/log-demo/log4j/a2.log
log4j.appender.a2.MaxFileSize=100MB
log4j.appender.a2.MaxBackupIndex=7
log4j.appender.a2.Threshold=INFO
log4j.appender.a2.layout=org.apache.log4j.PatternLayout
log4j.appender.a2.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %20c %L:%m %n
注意
缺少日志配置,所以提示下面信息:
log4j:WARN No appenders could be found for logger (org.example.InitTest).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
使用例子
package org.example;
import org.apache.log4j.Logger;
import org.junit.jupiter.api.Test;
public class InitTest {
private final static Logger logger = Logger.getLogger(InitTest.class);
@Test
void testLog4jInit() {
/*
缺少日志配置,所以提示下面信息:
log4j:WARN No appenders could be found for logger (org.example.InitTest).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
*/
logger.debug("debug");
logger.info("info");
}
}
输出
2024-05-01 17:33:28 DEBUG org.example.InitTest 16:debug
2024-05-01 17:33:28 INFO org.example.InitTest 17:info
引入 Slf4j 门面
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>