SpringBoot2.x使用slf4j+logback日志,以及动态修改日志级别

前言:记录一下SpringBoot学习历程

SpringBoot中内置了slf4j日志框架,我们直接使用就好了。

使用slf4j

新建一个测试controller,如:


    public final Logger log = LoggerFactory.getLogger(getClass());

    @GetMapping("/test")
    public void test() {
        log.info("Logger Level :{}", "info");
        log.error("Logger Level :{}", "error");
        log.debug("Logger Level :{}", "debug");
        log.warn("Logger Level :{}", "warn");
    }

启动项目,访问test请求,log日志就可以打印了。
每次都写:==public final Logger log = LoggerFactory.getLogger(getClass());==是不是觉得很繁琐,有一种更方便的办法就是使用注解。
首先,修改pom文件,导入依赖:

		<dependency>
			<groupId>org.projectlombokgroupId>
			<artifactId>lombokartifactId>
		dependency>

关于lombok还有很多别的功能,比如使用@Data注解可以为一个bean自动生成getter , setter方法及toString 方法

然后在测试controller中使用注解:@Slf4j

@Slf4j
@RestController()
public class HelloController {

    @GetMapping("/test")
    public void test() {
        log.info("Logger Level :{}", "info");
        log.error("Logger Level :{}", "error");
        log.debug("Logger Level :{}", "debug");
        log.warn("Logger Level :{}", "warn");
    }
}

这样即使不用写public final Logger log = LoggerFactory.getLogger(getClass());,都可以打印日志了

使用slf4j + logback 记录日志

新建一个logback-spring.xml(或者logback.xml,官方推荐使用-spring,可以使用springProfile
实现多环境日志配置),logback-spring.xml示例:






<configuration  scan="true" scanPeriod="10 seconds">
    <contextName>logbackcontextName>

    
    <property name="log.path" value="logs" />
    <property name="service.name" value="demo" />

    
    
    <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />
    <conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />
    <conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />
    
    <property name="CONSOLE_LOG_PATTERN" value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>

    
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>debuglevel>
        filter>
        <encoder>
            <Pattern>${CONSOLE_LOG_PATTERN}Pattern>
            
            <charset>UTF-8charset>
        encoder>
    appender>

    <appender name="LOGFILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        
        <file>${log.path}/${service.name}.logfile>
        
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%npattern>
            <charset>UTF-8charset> 
        encoder>
        
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            
            <fileNamePattern>${log.path}/${service.name}-%d{yyyy-MM-dd}.%i.logfileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>100MBmaxFileSize>
            timeBasedFileNamingAndTriggeringPolicy>
            
            <maxHistory>15maxHistory>
        rollingPolicy>
        
    appender>

    
    
    <appender name="DEBUG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        
        <file>${log.path}/${service.name}-DEBUG.logfile>
        
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%npattern>
            <charset>UTF-8charset> 
        encoder>
        
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            
            <fileNamePattern>${log.path}/web-debug-%d{yyyy-MM-dd}.%i.logfileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>100MBmaxFileSize>
            timeBasedFileNamingAndTriggeringPolicy>
            
            <maxHistory>15maxHistory>
        rollingPolicy>
        
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>debuglevel>
            <onMatch>ACCEPTonMatch>
            <onMismatch>DENYonMismatch>
        filter>
    appender>

    
    <appender name="INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        
        <file>${log.path}/${service.name}-INFO.logfile>
        
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%npattern>
            <charset>UTF-8charset>
        encoder>
        
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            
            <fileNamePattern>${log.path}/${service.name}-INFO-%d{yyyy-MM-dd}.%i.logfileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>100MBmaxFileSize>
            timeBasedFileNamingAndTriggeringPolicy>
            
            <maxHistory>15maxHistory>
        rollingPolicy>
        
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>infolevel>
            <onMatch>ACCEPTonMatch>
            <onMismatch>DENYonMismatch>
        filter>
    appender>

    
    <appender name="WARN_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        
        <file>${log.path}/${service.name}-WARN.logfile>
        
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%npattern>
            <charset>UTF-8charset> 
        encoder>
        
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${log.path}/${service.name}-WARN-%d{yyyy-MM-dd}.%i.logfileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>100MBmaxFileSize>
            timeBasedFileNamingAndTriggeringPolicy>
            
            <maxHistory>15maxHistory>
        rollingPolicy>
        
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>warnlevel>
            <onMatch>ACCEPTonMatch>
            <onMismatch>DENYonMismatch>
        filter>
    appender>

    
    <appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        
        <file>${log.path}/${service.name}-ERROR.logfile>
        
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%npattern>
            <charset>UTF-8charset> 
        encoder>
        
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${log.path}/${service.name}-ERROR-%d{yyyy-MM-dd}.%i.logfileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>100MBmaxFileSize>
            timeBasedFileNamingAndTriggeringPolicy>
            
            <maxHistory>15maxHistory>
        rollingPolicy>
        
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>ERRORlevel>
            <onMatch>ACCEPTonMatch>
            <onMismatch>DENYonMismatch>
        filter>
    appender>

    

    

    

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


    
    <springProfile name="test">
        <root level="info">
            <appender-ref ref="LOGFILE" />
            <appender-ref ref="DEBUG_FILE" />
            <appender-ref ref="INFO_FILE" />
            <appender-ref ref="ERROR_FILE" />
            <appender-ref ref="WARN_FILE" />
        root>
    springProfile>

    
    <springProfile name="prod">
        <root level="info">
            <appender-ref ref="LOGFILE" />
            <appender-ref ref="INFO_FILE" />
            <appender-ref ref="ERROR_FILE" />
            <appender-ref ref="WARN_FILE" />
        root>
    springProfile>

configuration>

dev开发环境则只打印到控制台上(注意:springProfile name=“prod” name,需要配置不同的环境ID,配置不同环境可参考我之前博客:https://blog.csdn.net/qq_36174487/article/details/89419347),
我们以测试环境启动项目,生成日志为logs文件目录下:
SpringBoot2.x使用slf4j+logback日志,以及动态修改日志级别_第1张图片
这样日志就成功被记录到.log文件中了,并且按照日期来归档,可设置文件大小,过期天数等,附上博主归档日志:
SpringBoot2.x使用slf4j+logback日志,以及动态修改日志级别_第2张图片

动态修改日志级别

首先更改yml文件:

# 1.5.x 版本中是 management.security.enabled=false
management:
  endpoints:
    web:
      exposure:
        include: "loggers"

不然访问loggers端点时,会报如下错误:

{
		"timestamp": 1556596470000,
		"status": 401,
		"error": "Unauthorized",
		"message": "Full authentication is required to access this resource.",
		"path": "/loggers/com.didispace"
}

启动项目,访问地址:http://127.0.0.1:8081/actuator/loggers
结果:

{
    "levels": [
        "OFF",
        "ERROR",
        "WARN",
        "INFO",
        "DEBUG",
        "TRACE"
    ],
    "loggers": {
        "ROOT": {
            "configuredLevel": "INFO",
            "effectiveLevel": "INFO"
        },
        "com": {
            "configuredLevel": null,
            "effectiveLevel": "INFO"
        },
        "com.example": {
            "configuredLevel": null,
            "effectiveLevel": "INFO"
        },
        "com.example.demo": {
            "configuredLevel": null,
            "effectiveLevel": "INFO"
        },
        "com.example.demo.DemoApplication": {
            "configuredLevel": null,
            "effectiveLevel": "INFO"
        },
        "com.example.demo.task": {
            "configuredLevel": null,
            "effectiveLevel": "INFO"
        },
        "com.example.demo.task.Scheduling": {
            "configuredLevel": null,
            "effectiveLevel": "INFO"
        },
        "com.example.demo.web": {
            "configuredLevel": null,
            "effectiveLevel": "INFO"
        },
        "com.example.demo.web.HelloController": {
            "configuredLevel": null,
            "effectiveLevel": "INFO"
        },
        "io": {
            "configuredLevel": null,
            "effectiveLevel": "INFO"
        },
        "io.micrometer": {
            "configuredLevel": null,
            "effectiveLevel": "INFO"
        }
        //详细包日志级别省略
    }
}

其中com.com.example,com.example.demo 对应项目的包名,可针对性的更改不同包的日志级别,
比如更改 com.example.demo 级别为DEBUG
发起请求:http://127.0.0.1:8081/actuator/loggers/com.example.demo
参数:

{
	"configuredLevel":"DEBUG"
}

参数格式一定不能乱!
再次访问test请求:dubug级别日志就可被打印出来了
动态修改日志级别
还可以使用根据Actuator提供的RESTful API定制界面,或使用 Spring Boot Admin ,可视化修改日志级别
或者自定义请求,logger.setLevel(LEVELS.convertSystemToNative(level)); 等来更改,有兴趣的同学可以试试!

参考资料:
1.https://blog.csdn.net/dyc87112/article/details/54866244/
2.https://blog.csdn.net/heguiliang_123/article/details/80296745
3.https://my.oschina.net/eacdy/blog/3040211

你可能感兴趣的:(SpringBoot,Java)