Spring Boot 日志配置-logback和log4j2

原创
2017/08/21 10:43
阅读数 423

支持日志框架:Java Util Logging, Log4J2 and Logback,默认是使用logback

配置方式:默认配置文件配置和引用外部配置文件配置

 

一、 默认配置文件配置(不建议使用:不够灵活,对log4j2等不够友好)

# 日志文件名,比如:gus.log,或者是 /var/log/gus.log

logging.file=gus.log

# 日志级别配置,比如: logging.level.org.springframework=DEBUG

logging.level.*=info

logging.level.org.springframework=DEBUG

 

二、 引用外部配置文件

2.1 logback配置方式:

spring boot默认会加载classpath:logback-spring.xml或者classpath:logback-spring.groovy

 

使用自定义配置文件,配置方式为:

logging.config=classpath:logback-gus.xml

注意:不要使用logback这个来命名,否则spring boot将不能完全实例化

 

1.使用基于spring boot的配置

<?xml version="1.0" encoding="UTF-8"?>

<configuration>

<include resource="org/springframework/boot/logging/logback/base.xml"/>

<logger name="org.springframework.web" level="DEBUG"/>

</configuration>

 

2.自定义配置

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

	<!-- 文件输出格式 -->
	<property name="PATTERN" value="%-12(%d{yyyy-MM-dd HH:mm:ss.SSS}) |-%-5level [%thread] %c [%L] -| %msg%n" />
	<!-- test文件路径 -->
	<property name="TEST_FILE_PATH" value="c:/opt/gus/logs" />
	<!-- pro文件路径 -->
	<property name="PRO_FILE_PATH" value="/opt/gus/logs" />

	<!-- 开发环境 -->
	<springProfile name="dev">
		<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
			<encoder>
				<pattern>${PATTERN}</pattern>
			</encoder>
		</appender>
		
		<logger name="com.gus.education" level="debug"/>

		<root level="info">
			<appender-ref ref="CONSOLE" />
		</root>
	</springProfile>

	<!-- 测试环境 -->
	<springProfile name="test">
		<!-- 每天产生一个文件 -->
		<appender name="TEST-FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
			<!-- 文件路径 -->
			<file>${TEST_FILE_PATH}</file>
			<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
				<!-- 文件名称 -->
				<fileNamePattern>${TEST_FILE_PATH}/info.%d{yyyy-MM-dd}.log</fileNamePattern>
				<!-- 文件最大保存历史数量 -->
				<MaxHistory>100</MaxHistory>
			</rollingPolicy>
			
			<layout class="ch.qos.logback.classic.PatternLayout">
				<pattern>${PATTERN}</pattern>
			</layout>
		</appender>
		
		<root level="info">
			<appender-ref ref="TEST-FILE" />
		</root>
	</springProfile>

	<!-- 生产环境 -->
	<springProfile name="prod">
		<appender name="PROD_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
			<file>${PRO_FILE_PATH}</file>
			<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
				<fileNamePattern>${PRO_FILE_PATH}/warn.%d{yyyy-MM-dd}.log</fileNamePattern>
				<MaxHistory>100</MaxHistory>
			</rollingPolicy>
			<layout class="ch.qos.logback.classic.PatternLayout">
				<pattern>${PATTERN}</pattern>
			</layout>
		</appender>
		
		<root level="warn">
			<appender-ref ref="PROD_FILE" />
		</root>
	</springProfile>
</configuration>

 

高级配置示例:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

	<!-- 文件输出格式 -->
	<property name="PATTERN"
		value="%-12(%d{yyyy-MM-dd HH:mm:ss.SSS}) [%thread] %c [%L]  %n %-10level %msg%n" />
	<!-- test文件路径 -->
	<property name="TEST_FILE_PATH" value="/opt/xxx/logs/tcc/manage/running.log" />
	<!-- pro文件路径 -->
	<property name="PRO_FILE_PATH" value="/opt/xxx/logs/tcc/manage/${PID}/" />
	<property name="PRO_FILE_INFO" value="${PRO_FILE_PATH}/info.log" />
	<property name="PRO_FILE_ERROR" value="${PRO_FILE_PATH}/error.log" />

	<!-- 开发环境 -->
	<springProfile name="dev">
		<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
			<encoder>
				<pattern>${PATTERN}</pattern>
			</encoder>
		</appender>

		<logger name="com.xxx.architecture" level="debug" />
		<logger name="org.springframework.web.client" level="debug" />


		<root level="info">
			<appender-ref ref="CONSOLE" />
		</root>
	</springProfile>

	<!-- 测试环境 -->
	<springProfile name="test">
		<appender name="PROD_FILE"
			class="ch.qos.logback.core.rolling.RollingFileAppender">
			<file>${PRO_FILE_PATH}</file>
			<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
				<fileNamePattern>${PRO_FILE_PATH}/running.%d{yyyy-MM-dd}.log
				</fileNamePattern>
				<MaxHistory>100</MaxHistory>
			</rollingPolicy>
			<layout class="ch.qos.logback.classic.PatternLayout">
				<pattern>${PATTERN}</pattern>
			</layout>
		</appender>

		<root level="info">
			<appender-ref ref="PROD_FILE" />
		</root>
	</springProfile>

	<!-- 生产环境 -->
	<springProfile name="prd">
		<appender name="INFO_FILE"
			class="ch.qos.logback.core.rolling.RollingFileAppender">
			<file>${PRO_FILE_INFO}</file>
			<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
				<fileNamePattern>${PRO_FILE_PATH}/info.%d{yyyy-MM-dd}.%i.log
				</fileNamePattern>
				<MaxHistory>300</MaxHistory>

				<timeBasedFileNamingAndTriggeringPolicy
					class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
					<maxFileSize>500MB</maxFileSize>
				</timeBasedFileNamingAndTriggeringPolicy>
			</rollingPolicy>

			<encoder>
				<pattern>${PATTERN}</pattern>
				<charset>UTF-8</charset>
			</encoder>
			
			<filter class="ch.qos.logback.classic.filter.LevelFilter">
				<level>INFO</level>
				<onMatch>ACCEPT</onMatch>
				<onMismatch>DENY</onMismatch>
			</filter>
		</appender>
		
		<appender name="ERROR_FILE"
			class="ch.qos.logback.core.rolling.RollingFileAppender">
			<file>${PRO_FILE_ERROR}</file>
			<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
				<fileNamePattern>${PRO_FILE_PATH}/error.%d{yyyy-MM-dd}.%i.log
				</fileNamePattern>
				<MaxHistory>300</MaxHistory>

				<timeBasedFileNamingAndTriggeringPolicy
					class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
					<maxFileSize>500MB</maxFileSize>
				</timeBasedFileNamingAndTriggeringPolicy>
			</rollingPolicy>

			<encoder>
				<pattern>${PATTERN}</pattern>
				<charset>UTF-8</charset>
			</encoder>
			
			<filter class="ch.qos.logback.classic.filter.LevelFilter">
				<level>ERROR</level>
				<onMatch>ACCEPT</onMatch>
				<onMismatch>DENY</onMismatch>
			</filter>
		</appender>

		<logger name="com.tuandai.architecture" level="info" />

		<root level="error">
			<appender-ref ref="INFO_FILE" />
			<appender-ref ref="ERROR_FILE" />
		</root>
	</springProfile>
</configuration>

 

 

2.2 log4j配置

2.2.1去除logback的依赖包,添加log4j2的依赖包

                <exclusions>

                   <exclusion>

                       <groupId>org.springframework.boot</groupId>

                       <artifactId>spring-boot-starter-logging</artifactId>

                   </exclusion>

              </exclusions>

 

<!-- 使用log4j2 -->

         <dependency>

              <groupId>org.springframework.boot</groupId>

              <artifactId>spring-boot-starter-log4j2</artifactId>

         </dependency>

2.2.2 在classpath添加log4j2.xml或者log4j2-spring.xml(spring boot 默认加载)

2.3 自定义配置文件

<?xml version="1.0" encoding="utf-8"?>
<configuration>
	<properties>
		<!-- 文件输出格式 -->
		<property name="PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} |-%-5level [%thread] %c [%L] -| %msg%n</property>
	</properties>

	<appenders>
		<Console name="CONSOLE" target="system_out">
			<PatternLayout pattern="${PATTERN}" />
		</Console>
	</appenders>
	
	<loggers>
		<logger name="com.gus.education" level="debug" />
		<root level="info">
			<appenderref ref="CONSOLE" />
		</root>
	</loggers>

</configuration>

 

三.比较

性能比较:Log4J2 和 Logback 都优于 log4j(不推荐使用)

配置方式:Logback最简洁,spring boot默认,推荐使用

 

 

 

四、利用 actuator 动态设置 logging 的日志级别

    已经上线的服务通常情况下都会关闭日志打印功能。但是一但进行排错的时候,又必须开启日志输出,而修改日志级别的方式有多种。

定义 endpoint

import java.util.concurrent.atomic.AtomicBoolean;
import org.springframework.boot.actuate.endpoint.AbstractEndpoint;

public class MyLogEndpoint extends AbstractEndpoint<Boolean> {
    AtomicBoolean atomicBoolean = new AtomicBoolean();
    // mgrlogging 为该 endpoint 的请求子路径:  http://localhost:8080/mgrlogging
    public MyLogEndpoint() {
        super("mgrlogging", true, true);
    }

    @Override
    public Boolean invoke() {
        // 这里我的本意是 log 开关,一个布尔值。
        // 每次请求 http://localhost:8080/mgrlogging 都会调用该 invoke 方法
        // 通常情况下返回该 endpoint 的监控信息
        return atomicBoolean.getAndSet(!atomicBoolean.get());
    }
}

 

定义子节点


import org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.logback.LogbackLoggingSystem;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

public class MyLogMvcEndpoint extends EndpointMvcAdapter {

    String format = "change package name [%s] logging level to [%s]";

    public MyLogMvcEndpoint(MyLogEndpoint delegate) {
        super(delegate);
    }

    // 注意该 path 不是 http://localhost:8080/mgrlogging/{level}/{pkn}
    // 而是构造方法中 MyLogEndpoint 的 id 对应 path 下的请求节点。
    // http://localhost:8080/mgrlogging/{level}/{pkn}

    @RequestMapping(value = "/{level}/{pkn}")
    @ResponseBody
    public Object changeLog(@PathVariable LogLevel level, @PathVariable("pkn") String packageName) {
        System.err.println(String.format(format, packageName, level));

        try {
            // 处理日志 level 改变逻辑,根据个人需求改变
            LogbackLoggingSystem logbackLoggingSystem = new LogbackLoggingSystem(this.getClass().getClassLoader());
            logbackLoggingSystem.setLogLevel(packageName, level);

            // 处理成功(未抛出异常)返回 success
            return "success";
        } catch (Exception e) {
            // 处理失败返回异常信息
            return e.getMessage();
        }
    }

}

endpoint 注册


import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnWebApplication
public class MyLogConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public MyLogEndpoint changeLogEndpoint() {
        return new MyLogEndpoint();
    }

    @Bean
    @ConditionalOnBean(MyLogEndpoint.class)
    public MyLogMvcEndpoint changeLogMvcEndpoint(MyLogEndpoint delegate) {
        return new MyLogMvcEndpoint(delegate);
    }

}

 

请求示例:

http://localhost:8761/mgrlogging/ERROR/com.netflix.eureka.registry

 

 

 

展开阅读全文
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部