Spring Boot使用log4j2

版权声明:转载请注明链接 https://blog.csdn.net/weixin_38569499/article/details/89473772

    Spring Boot定制了log4j2的桥接包,可以通过添加spring boot - log4j2的桥接包并配置log42的配置文件,来实现在spring boot项目中使用log4j2的目的。

1、添加Spring Boot - log4j2桥接包

    maven项目中添加桥接包依赖,并排除默认logging的依赖:

    <!-- spring boot -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
      <version>2.1.2.RELEASE</version>
      <exclusions>
        <exclusion>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

    <!-- Add Log4j2 Dependency -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-log4j2</artifactId>
    </dependency>

2、添加log4j2的配置文件

    log4j2官方支持的配置文件即可,放入到resource资源目录中,命名随意。这里我采用的是properties格式的配置文件,文件名是log4j2_virtual.properties:

status=info
name=PropertiesConfig
rootLogger.level=info
rootLogger.appenderRef.stdout.ref=STDOUT
rootLogger.appenderRef.rolling.ref=RollingFile
appender.console.type=Console
appender.console.name=STDOUT
appender.console.layout.type=PatternLayout
appender.console.layout.pattern=%d [%t] %-5p %c{2} - %X{msgId} - %m%n
appender.rolling.type=RollingFile
appender.rolling.name=RollingFile
appender.rolling.fileName=/home/servlets/logs/virtual/virtual.log
appender.rolling.filePattern=/home/servlets/logs/virtual/virtual.log.%d{yyyy-MM-dd}
appender.rolling.layout.type=PatternLayout
appender.rolling.layout.pattern=%d [%t] %-5p %c{2} - %X{msgId} - %m%n
appender.rolling.policies.type=Policies
appender.rolling.policies.time.type=TimeBasedTriggeringPolicy
appender.rolling.policies.time.interval=1

    记住这里的文件名,会在下一步中使用到。

3、配置Spring Boot

    Spring Boot在resource资源目录下通过application.properties文件保存了一些配置,比如这里我们需要的log4j的配置,就可以在这里添加。在resource资源目录中创建文件application.properties,并向其中添加:

logging.config=classpath:log4j2_virtual.properties

    这里是在配置log4j2配置文件的路径,这个路径是上面第2步中添加的log4j2的配置文件相对于resource资源目录的相对路径。

猜你喜欢

转载自blog.csdn.net/weixin_38569499/article/details/89473772