欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

gradle boot log4j2

程序员文章站 2022-03-04 18:07:40
...
[list]
  • 1.首先去掉logback依赖, 在gradle中添加如下
  • configurations {
    	all*.exclude module: 'spring-boot-starter-logging'
        all*.exclude module: 'logback-classic'
        all*.exclude module: 'log4j-over-slf4j'
    }
    
  • 2.再添加log4j2的依赖和log4j2读取yaml文件依赖
  • compile ('org.springframework.boot:spring-boot-starter-log4j2')	
    compile group: 'com.fasterxml.jackson.dataformat', name: 'jackson-dataformat-yaml', version: '2.9.2'
    
  • 3.classpath下面添加文件log4j2.yaml, 示例内容如下(Unknown property 'Configuration'这个提示请忽略).自行更改包路径和日志写盘位置
  • Configuration:  
      status: warn  
      
      Properties: # 定义全局变量  
        Property: # 缺省配置(用于开发环境)。其他环境需要在VM参数中指定,如下:  
          #测试:-Dlog.level.console=warn -Dlog.level.ccl=trace  
          #生产:-Dlog.level.console=warn -Dlog.level.ccl=info        
          - name: log.level.console  
            value: trace  
          - name: log.level.ccl  
            value: trace         
          - name: log.path  
            value: C:/logs  
          - name: project.name  
            value: my-spring-boot  
        
      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}:%4p %X{user} %t (%F:%L) - %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}:%4p %t (%F:%L) - %m%n"  
            Policies:  
              SizeBasedTriggeringPolicy:  
                size: "128 MB"  
            DefaultRolloverStrategy:  
              max: 1000  
      
      Loggers:  
        Root:  
          level: info  
          AppenderRef:  
            - ref: CONSOLE  
            - ref: ROLLING_FILE  
        Logger: # 为com.ccl包配置特殊的Log级别,方便调试  
          - name: com.ccl  
            additivity: false  
            level: ${sys:log.level.ccl}  
            AppenderRef:  
              - ref: CONSOLE  
              - ref: ROLLING_FILE  
    
  • 4.application.yaml中配置输出级别, 如下在针对app启动的日志无效了(测试用例中仍有效):
  • 这个时候参考log4j.yaml中的[定义全局变量]下方的name:value进行配置才会对boot启动日志有效
    logging:
      level:
        root: warn 
    
  • 5.测试用例
  • 
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.slf4j.MDC;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    import com.ccl.Application;
    
    @SpringBootTest(classes = Application.class)
    @RunWith(SpringJUnit4ClassRunner.class)
    public class Log4j2Test {
    
    	private final Logger logger = LoggerFactory.getLogger(this.getClass());
    
    	@Test
    	public void test() throws Exception {
    		MDC.put("user", "开车不直播, 出事贴吧找老哥.");//对应配置文件pattern中%X{user}变量
    		logger.trace("I am trace log.");
    		logger.debug("I am debug log.");
    		logger.warn("I am warn log.");
    		logger.error("I am error log.");
    	}
    }
    

    [/list]