编程语言
首页 > 编程语言> > Java项目(非Web)整合lombok+slf4j1.7.x+log4j 2.x日志框架同时输出到文件和控制台

Java项目(非Web)整合lombok+slf4j1.7.x+log4j 2.x日志框架同时输出到文件和控制台

作者:互联网

项目依赖

项目依赖的版本号如下:

<properties>
    <lombok.version>1.18.2</lombok.version>
    <slf4j.version>1.7.36</slf4j.version>
    <log4j.version>2.17.2</log4j.version>
</properties>

项目的依赖包如下:

<dependencies>
  <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>${lombok.version}</version>
    <optional>true</optional>
  </dependency>
  
  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>${slf4j.version}</version>
  </dependency>

  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-slf4j-impl</artifactId>
    <version>${log4j.version}</version>
  </dependency>

  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>${log4j.version}</version>
  </dependency>

  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>${log4j.version}</version>
  </dependency>

</dependencies>

参考文档
Log4j Runtime Dependencies

下图是 log4j-slf4j-impl 的依赖树:

初始化log4j 2.x

创建文件 src/main/resources/log4j2.xml,内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
    <Appenders>
        <Console name="STDOUT" target="SYSTEM_OUT">
            <PatternLayout pattern="%m%n"/>
        </Console>
        <File name="FILE_APPENDER" fileName="logs/app.log">
            <PatternLayout>
                <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
            </PatternLayout>
        </File>
        <Async name="ASYNC_FILE_APPENDER">
            <AppenderRef ref="FILE_APPENDER"/>
        </Async>
    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="STDOUT" />
            <AppenderRef ref="ASYNC_FILE_APPENDER"/>
        </Root>
    </Loggers>
</Configuration>

参考更多 Log4j 2.x Appenders

标签:Web,依赖,Java,api,slf4j1.7,slf4j,version,org,log4j
来源: https://www.cnblogs.com/kendoziyu/p/16252567.html