Maven项目搭建Log4j日志环境
介绍一下Maven项目中如何搭建Log4j日志,具体如下:
- 构建一个
Maven
项目;
- 在项目的POM文件中引入Log4j的相关依赖包:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <properties> <slf4j-api-version>2.13.0</slf4j-api-version> <log4j-core-version>2.13.0</log4j-core-version> </properties> <dependencies> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>${slf4j-api-version}</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>${log4j-core-version}</version> </dependency> </dependencies>
|
- 构建一个测试类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| public class Main { private static Logger logger = LogManager.getLogger(Main.class.getName());
public static void main(String[] args) { add(1, 2); }
public static int add(int a , int b) { logger.entry(a+b); logger.info("我是info信息"); logger.warn("我是warn信息"); logger.error("我是error信息"); logger.fatal("我是fatal信息"); logger.printf(Level.INFO, "%d+%d=%d", a, b, a + b); logger.exit(a + b); logger.debug("one={}, two={}, three={}", 1, 2, 3); return a + b; } }
|
- 配置Log4j的配置文件(
log4j2.xml
),配置文件放在根目录
1 2 3 4 5 6 7 8 9 10 11 12 13
| <?xml version="1.0" encoding="UTF-8"?> <configuration status="off"> <appenders> <Console name="Console" target="SYSTEM_OUT"> <PatternLayout pattern="%highlight{%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n%throwable}{FATAL=white, ERROR=red, WARN=blue, INFO=black, DEBUG=green, TRACE=blue}"/> </Console> </appenders> <loggers> <root level="trace"> <appender-ref ref="Console"/> </root> </loggers> </configuration>
|
- 测试
参考资料