spring boot log4j2配置(使用log4j2.yml文件)

在spring boot中,配置log4j2的几个步骤(使用yml文件):


1、pom文件的依赖配置中,去掉spring boot默认的log配置,引入log4j2依赖包:

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

2、log4j2.yml文件配置(放置在resources文件夹中):

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.xjj
        value: trace       
      - name: log.path
        value: /opt/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 %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.xjj包配置特殊的Log级别,方便调试
      - name: com.xjj
        additivity: false
        level: ${sys:log.level.xjj}
        AppenderRef:
          - ref: CONSOLE
          - ref: ROLLING_FILE

3、测试用例:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MySpringBootApplication.class)
public class MySpringBootApplicationTests {
	protected final Logger logger = LoggerFactory.getLogger(this.getClass());
	protected final ObjectMapper objectMapper = new ObjectMapper();
	
	@Test
	public void contextLoads() {
		logger.trace("I am trace log.");
		logger.debug("I am debug log.");
		logger.warn("I am warn log.");
		logger.error("I am error log.");
	}

}

测试结果:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.3.5.RELEASE)

2016-05-25 15:36:30,245:INFO main (StartupInfoLogger.java:48) - Starting MySpringBootApplicationTests on WIN-UCBBGRHGRK9 with PID 27276 (C:\workspace-sts\my-spring-boot\target\test-classes started by Xu in C:\workspace-sts\my-spring-boot)
2016-05-25 15:36:30,245:DEBUG main (StartupInfoLogger.java:51) - Running with Spring Boot v1.3.5.RELEASE, Spring v4.2.6.RELEASE
2016-05-25 15:36:30,245:INFO main (SpringApplication.java:666) - No active profile set, falling back to default profiles: default
2016-05-25 15:36:30,285:INFO main (AbstractApplicationContext.java:578) - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@638ef7ed: startup date [Wed May 25 15:36:30 CST 2016]; root of context hierarchy
2016-05-25 15:36:30,522:INFO background-preinit (Version.java:30) - HV000001: Hibernate Validator 5.2.4.Final
2016-05-25 15:36:31,673:INFO main (StartupInfoLogger.java:57) - Started MySpringBootApplicationTests in 1.726 seconds (JVM running for 2.749)
2016-05-25 15:36:31,681:TRACE main (MySpringBootApplicationTests.java:20) - I am trace log.
2016-05-25 15:36:31,681:DEBUG main (MySpringBootApplicationTests.java:21) - I am debug log.
2016-05-25 15:36:31,682:WARN main (MySpringBootApplicationTests.java:22) - I am warn log.
2016-05-25 15:36:31,682:ERROR main (MySpringBootApplicationTests.java:23) - I am error log.
2016-05-25 15:36:31,689:INFO Thread-1 (AbstractApplicationContext.java:960) - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@638ef7ed: startup date [Wed May 25 15:36:30 CST 2016]; root of context hierarchy

可以看到4个log都出来了,调整log.level参数可以决定让哪个级别的log出来。

同时,硬盘中/opt/logs/目录下也自动生成了一个叫做my-spring-boot.log的文件,保存了相同的log内容。

详细的源代码参考:https://github.com/xujijun/my-spring-boot




评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值