springboot之整合log4j2

sprongboot使用的默认日志框架是Logback, 本文展示整合 log4j2 的操作;

pom配置, 要将默认的logging去掉 ,

        
			org.springframework.boot
			spring-boot-starter
			
				
					org.springframework.boot
					spring-boot-starter-logging
				
			
		

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

		
			org.springframework.boot
			spring-boot-starter-log4j2
		

配置文件

application.properties 中的配置

logging.config=classpath:log4j2.yml

在resource目录下添加配置文件

log4j2.yml

Configuration:
  status: warn
  Properties: # 定义变量  
    Property:
    - name: log.path
      value: logs/application.log
    - name: project.name
      value: common
Appenders:
  Console: #输出到控制台
    name: CONSOLE
    target: SYSTEM_OUT
    ThresholdFilter: 
      level: trace
      onMatch: ACCEPT
      onMismatch: DENY
    PatternLayout:
      pattern: '%d{yyyy-MM-dd HH:mm:ss,SSS}:%4p %t (%F:%L) - %m%n'
      
  RollingFile: # 输出到文件,超过128MB归档
  - name: ROLLING_FILE
    ignoreExceptions: false
    fileName: logs/application.log
    filePattern: logs/$${date:yyyy-MM}/common-%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: 100 MB
    DefaultRolloverStrategy:
      max: 1000
Loggers:
  Root:
    level: info
    AppenderRef:
    - ref: CONSOLE
    - ref: ROLLING_FILE

写个Controller测试

package com.bus365.root.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/log")
@RestController
public class LoggerController {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@RequestMapping("/logtest")
	public String logtest() {
		logger.info("info message");
		logger.error("error message");
		return "success";
	}
}

可以看到logs 目录下的 日志文件;

你可能感兴趣的:(java,log4j)