IDEA添加Log4j2

emmm…想用Tex来写博客了(可惜目前啥都不会)

这是第几次被CSDN和IDEA的代码智能补全联合起来坑了呢?
忘了。

Log4j™2

起因:

1
import org.apache.log4j.Logger;

无法通过编译。

万能的Stack overflow告诉我log4jlog4j2API不同,这是引入log4 j2的包后误用log4j的API引起的。

The org.apache.log4j package is the Log4j 1.2 namespace. Log4j 2 uses the org.apache.logging.log4j namespace. Log4j 1.2 became End of Life in 2015 and users are recommended to upgrade to Log4j 2.

可恶。

参考资料:
  1. The import org.apache.log4j cannot be resolved

Log4j2的使用方法

施工中…

工程结构

将log生成在工程目录下:

how to configure log file path to current working target directory in log4j2 xml format

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="MyApp" packages="">
<Appenders>
// This section represents your properties
<File name="MyFile" fileName="./target/test-classes/example.log">
<PatternLayout>
<Pattern>%m%n</Pattern>
</PatternLayout>
</File>
</Appenders>
<Loggers>
<Root level="error">
<AppenderRef ref="MyFile"/>
</Root>
</Loggers>
</Configuration>

log4j2 doc

其他格式的配置文件与此类似。

参考资料
  1. log4j2使用教程
  2. log4j的2.6.2版本properties配置文件的使用举例
  3. log4j2 实际使用详解
  4. 详解log4j2(上) - 从基础到实战

Log4j2 Failed to load class “org.slf4j.impl.StaticLoggerBinder”

报如下错误时,检查是否引入slf4j

SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder”.
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

1
2
3
implementation 'org.apache.logging.log4j:log4j-api:2.13.3'
implementation 'org.apache.logging.log4j:log4j-core:2.13.3'
implementation 'org.apache.logging.log4j:log4j-slf4j-impl:2.13.3'
参考资料
  1. Java log: failed to load slf4j but I’m using log4j2. How to fix?
  2. log4j2 – Failed to load class “org.slf4j.impl.StaticLoggerBinder”

Log4j2的配置文件

参考资料1是配置文件节点中文解析,参考资料2是LOG4J™2的官方文档。

参考资料
  1. log4j2配置文件log4j2.xml配置详解
  2. LOG4J2 - Configuration
图片仓库