configurations { all*.exclude module: 'spring-boot-starter-logging' all*.exclude module: 'logback-classic' all*.exclude module: 'log4j-over-slf4j' }
compile ('org.springframework.boot:spring-boot-starter-log4j2') compile group: 'com.fasterxml.jackson.dataformat', name: 'jackson-dataformat-yaml', version: '2.9.2'
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
logging: level: root: warn
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]