Spring Boot之Log4j2配置(总结)

Log4j2配置步骤

前言

spring boot支持的日志框架有,logback,Log4j2,Log4j和Java Util  Logging,默认使用的是logback日志框架,一直在使用log4j2,决定仍使用log4j2,那么要使用新的日志管理就需要把默认的去掉;

1.Spring Boot在pom.xml中的配置

去掉有默认的logback日志管理,使用log4j2日志管理

<!-- log related -->
        <dependency> <!-- exclude掉spring-boot的默认log配置 -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <exclusions><!-- a. -->
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency> <!-- 引入log4j2依赖 --><!-- b. -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>
        <dependency>  <!-- 加上这个才能辨认到log4j2.yml文件 --><!-- c. -->
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-yaml</artifactId>
        </dependency>
        <!-- end of log related -->

a.忽略spring boot自带的日志管理;

b.配置加载log4j2的日志管理;

c.加入辨别yml文件或者ymal文件的依赖;

2.yml或者ymal文件配置(log4j2.yml)

Configuration:
  status: warn

  Properties: # 定义全局变量
    Property: # 缺省配置(用于开发环境)。其他环境需要在VM参数中指定,如下:
      # 测试:-Dlog.level.console=warn -Dlog.level.xjj=trace
      # 生产:-Dlog.level.console=warn -Dlog.level.xjj=info
      - name: log.level.console    #控制台日志输出的级别
        value: trace
      - name: log.level.com.mars.mybatis.mapper
        value: trace
      - name: log.path
        value: /Users/fandong/Desktop/logs  #日志文件存储的位置
      - name: project.name
        value: Mars-DashBoard # 项目名称

  Appenders:
    Console:  # 输出到控制台
      name: CONSOLE
      target: SYSTEM_OUT
      ThresholdFilter:
        level: ${sys:log.level.console} # “sys:”表示:如果VM参数中没指定这个变量值,则使用本文件中定义的缺省全局变量值
        onMatch: ACCEPT
        onMismatch: DENY
      PatternLayout:
        pattern: "%d{yyyy-MM-dd HH:mm:ss,SSS}:%5p %20t [%50F:%3L] - %m%n"
    RollingFile: # 输出到文件,超过128MB归档
      - name: ROLLING_FILE
        ignoreExceptions: false
        fileName: ${log.path}/${project.name}.log    #日志文件存储位置+文件名称
        filePattern: "${log.path}/$${date:yyyy-MM}/${project.name}-%d{yyyy-MM-dd}-%i.log.gz"
        PatternLayout:
          pattern: "%d{yyyy-MM-dd HH:mm:ss,SSS}:%5p %20t [%50F:%3L] - %m%n"
        Policies:
          SizeBasedTriggeringPolicy:
            size: "128 MB"    #最大日志文件大小
        DefaultRolloverStrategy:
          max: 1000

  Loggers:
    Root:
      level: info    #日志输出级别
      AppenderRef:
        - ref: CONSOLE
        - ref: ROLLING_FILE
    Logger: # 为 com.jeiker.demo.mapper 包配置特殊的Log级别,方便调试 SQL 语句输出
      - name: log.level.com.mars.mybatis.mapper
        additivity: false
        level: ${sys:log.level.com.mars.mybatis.mapper}
        AppenderRef:
          - ref: CONSOLE
          - ref: ROLLING_FILE

以上配置文件拿过去直接用就可以了,主要修改文件存放位置和项目名称(日志的名称)

3.测试

@Controller
public class TestController {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @RequestMapping("/xslsheet")
    public String xslsheet(){
        logger.trace("I am trace log.");
        logger.debug("I am debug log.");
        logger.warn("I am warn log.");
        logger.error("I am error log.");
        return "/xslsheet";
    }
}
输出结果
2018-05-25 15:36:31,681:TRACE main (TestController.java:20) - I am trace log.  
2018-05-25 15:36:31,681:DEBUG main (TestController.java:21) - I am debug log.  
2018-05-25 15:36:31,682:WARN main (TestController.java:22) - I am warn log.  
2018-05-25 15:36:31,682:ERROR main (TestController.java:23) - I am error log.

同时我们会发现/Users/fandong/Desktop/logs目录下会有日志文件.log生成;

4.其他

4.1为什么会替换掉spring boot默认的logback日志管理呢?

基于log4j2日志管理的性能和配置的灵活性;

更多的可以参考性能对比:https://www.jianshu.com/p/f18a9cff351d

4.2为什么只是配置了一个log4j2.yml就要就什么都不用管了就可以生成日志文件呢?

spring boot提供相应的缺省解析机制;

下面是自动的解析配置机制,不断的检测是否有符合规则的配置文件,检测到则加载?

Automatic Configuration
Log4j has the ability to automatically configure itself during initialization. When Log4j starts it will locate all the ConfigurationFactory plugins and arrange them in weighted order from highest to lowest. As delivered, Log4j contains four ConfigurationFactory implementations: one for JSON, one for YAML, one for properties, and one for XML.

Log4j will inspect the "log4j.configurationFile" system property and, if set, will attempt to load the configuration using the ConfigurationFactory that matches the file extension.
If no system property is set the properties ConfigurationFactory will look for log4j2-test.properties in the classpath.
If no such file is found the YAML ConfigurationFactory will look for log4j2-test.yaml or log4j2-test.yml in the classpath.
If no such file is found the JSON ConfigurationFactory will look for log4j2-test.json or log4j2-test.jsn in the classpath.
If no such file is found the XML ConfigurationFactory will look for log4j2-test.xml in the classpath.
If a test file cannot be located the properties ConfigurationFactory will look for log4j2.properties on the classpath.
If a properties file cannot be located the YAML ConfigurationFactory will look for log4j2.yaml or log4j2.yml on the classpath.
If a YAML file cannot be located the JSON ConfigurationFactory will look for log4j2.json or log4j2.jsn on the classpath.
If a JSON file cannot be located the XML ConfigurationFactory will try to locate log4j2.xml on the classpath.
If no configuration file could be located the DefaultConfiguration will be used. This will cause logging output to go to the console.

4.3错误配置方式

<dependency>  
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-web</artifactId> 
<exclusions>  
        <exclusion>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-starter-logging</artifactId>  
        </exclusion>  
    </exclusions>  
</dependency>    
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j2</artifactId> </dependency>

标红的地方是错误的配置数据;

4.4配置文件的格式是否只有yml一种?

log4j2日志管理配置文件会有多种格式配置;

79.2.1 Use YAML or JSON to Configure Log4j 2

In addition to its default XML configuration format, Log4j 2 also supports YAML and JSON configuration files. To configure Log4j 2 to use an alternative configuration file format, add the appropriate dependencies to the classpath and name your configuration files to match your chosen file format, as shown in the following example:

Format	Dependencies	File names
YAML

com.fasterxml.jackson.core:jackson-databind com.fasterxml.jackson.dataformat:jackson-dataformat-yaml

log4j2.yaml log4j2.yml

JSON

com.fasterxml.jackson.core:jackson-databind

log4j2.json log4j2.jsn

以上是支持格式说明,更多参考:

https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-configure-log4j-for-logging-yaml-or-json-config

4.5日志有哪些级别

log4j定义了8个级别的log(除去OFF和ALL,可以说分为6个级别),优先级从高到低依次为:OFF、FATAL、ERROR、WARN、INFO、DEBUG、TRACE、 ALL。

ALL 最低等级的,用于打开所有日志记录。

TRACE designates finer-grained informational events than the DEBUG.Since:1.2.12,很低的日志级别,一般不会使用。

DEBUG 指出细粒度信息事件对调试应用程序是非常有帮助的,主要用于开发过程中打印一些运行信息。

INFO 消息在粗粒度级别上突出强调应用程序的运行过程。打印一些你感兴趣的或者重要的信息,这个可以用于生产环境中输出程序运行的一些重要信息,但是不能滥用,避免打印过多的日志。
WARN 表明会出现潜在错误的情形,有些信息不是错误信息,但是也要给程序员的一些提示。
ERROR 指出虽然发生错误事件,但仍然不影响系统的继续运行。打印错误和异常信息,如果不想输出太多的日志,可以使用这个级别。
FATAL 指出每个严重的错误事件将会导致应用程序的退出。这个级别比较高了。重大错误,这种级别你可以直接停止程序了。
OFF 最高等级的,用于关闭所有日志记录。
如果将log level设置在某一个级别上,那么比此级别优先级高的log都能打印出来。例如,如果设置优先级为WARN,那么OFF、FATAL、ERROR、WARN 4个级别的log能正常输出,而INFO、DEBUG、TRACE、 ALL级别的log则会被忽略。Log4j建议只使用四个级别,优先级从高到低分别是ERROR、WARN、INFO、DEBUG。

从我们实验的结果可以看出,log4j默认的优先级为ERROR或者WARN(实际上是ERROR)。

4.6log4j2日志配置结构说明

参考:https://blog.csdn.net/qqhjqs/article/details/74095143


参考:

spring boot官网地址:https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-configure-log4j-for-logging-yaml-or-json-config

Log4j2配置官网地址:https://logging.apache.org/log4j/2.x/manual/configuration.html#AutomaticConfiguration

https://blog.csdn.net/shiyong1949/article/details/52643711

https://www.cnblogs.com/ly-radiata/articles/6026534.html

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值