作者:颖子_忒美 | 来源:互联网 | 2023-10-10 13:06
1 实现
第一步:在resources路径下创建日志的配置文件 logback-spring.xml
文件内容如下:
<configuration scan&#61;"true" scanPeriod&#61;"60 seconds"><contextName>logbackcontextName><property name&#61;"log.path" value&#61;"D:/logs"/><conversionRule conversionWord&#61;"clr"converterClass&#61;"org.springframework.boot.logging.logback.ColorConverter"/><conversionRule conversionWord&#61;"wex"converterClass&#61;"org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter"/><conversionRule conversionWord&#61;"wEx"converterClass&#61;"org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter"/><property name&#61;"CONSOLE_LOG_PATTERN"value&#61;"${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&#61;"CONSOLE" class&#61;"ch.qos.logback.core.ConsoleAppender"><filter class&#61;"ch.qos.logback.classic.filter.ThresholdFilter"><level>infolevel>filter><encoder><Pattern>${CONSOLE_LOG_PATTERN}Pattern><charset>UTF-8charset>encoder>appender><appender name&#61;"DEBUG_FILE" class&#61;"ch.qos.logback.core.rolling.RollingFileAppender"><file>${log.path}/log_debug.logfile><encoder><pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%npattern><charset>UTF-8charset>encoder><rollingPolicy class&#61;"ch.qos.logback.core.rolling.TimeBasedRollingPolicy"><fileNamePattern>${log.path}/debug/log-debug-%d{yyyy-MM-dd}.%i.logfileNamePattern><timeBasedFileNamingAndTriggeringPolicy class&#61;"ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"><maxFileSize>100MBmaxFileSize>timeBasedFileNamingAndTriggeringPolicy><maxHistory>15maxHistory>rollingPolicy><filter class&#61;"ch.qos.logback.classic.filter.LevelFilter"><level>debuglevel><onMatch>ACCEPTonMatch><onMismatch>DENYonMismatch>filter>appender><appender name&#61;"INFO_FILE" class&#61;"ch.qos.logback.core.rolling.RollingFileAppender"><file>${log.path}/log_info.logfile><encoder><pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%npattern><charset>UTF-8charset>encoder><rollingPolicy class&#61;"ch.qos.logback.core.rolling.TimeBasedRollingPolicy"><fileNamePattern>${log.path}/info/log-info-%d{yyyy-MM-dd}.%i.logfileNamePattern><timeBasedFileNamingAndTriggeringPolicy class&#61;"ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"><maxFileSize>100MBmaxFileSize>timeBasedFileNamingAndTriggeringPolicy><maxHistory>15maxHistory>rollingPolicy><filter class&#61;"ch.qos.logback.classic.filter.LevelFilter"><level>infolevel><onMatch>ACCEPTonMatch><onMismatch>DENYonMismatch>filter>appender><appender name&#61;"WARN_FILE" class&#61;"ch.qos.logback.core.rolling.RollingFileAppender"><file>${log.path}/log_warn.logfile><encoder><pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%npattern><charset>UTF-8charset>encoder><rollingPolicy class&#61;"ch.qos.logback.core.rolling.TimeBasedRollingPolicy"><fileNamePattern>${log.path}/warn/log-warn-%d{yyyy-MM-dd}.%i.logfileNamePattern><timeBasedFileNamingAndTriggeringPolicy class&#61;"ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"><maxFileSize>100MBmaxFileSize>timeBasedFileNamingAndTriggeringPolicy><maxHistory>15maxHistory>rollingPolicy><filter class&#61;"ch.qos.logback.classic.filter.LevelFilter"><level>warnlevel><onMatch>ACCEPTonMatch><onMismatch>DENYonMismatch>filter>appender><appender name&#61;"ERROR_FILE" class&#61;"ch.qos.logback.core.rolling.RollingFileAppender"><file>${log.path}/log_error.logfile><encoder><pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%npattern><charset>UTF-8charset>encoder><rollingPolicy class&#61;"ch.qos.logback.core.rolling.TimeBasedRollingPolicy"><fileNamePattern>${log.path}/error/log-error-%d{yyyy-MM-dd}.%i.logfileNamePattern><timeBasedFileNamingAndTriggeringPolicy class&#61;"ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"><maxFileSize>100MBmaxFileSize>timeBasedFileNamingAndTriggeringPolicy><maxHistory>15maxHistory>rollingPolicy><filter class&#61;"ch.qos.logback.classic.filter.LevelFilter"><level>ERRORlevel><onMatch>ACCEPTonMatch><onMismatch>DENYonMismatch>filter>appender><appender name&#61;"ASYNC-INFO" class&#61;"ch.qos.logback.classic.AsyncAppender"><discardingThreshold>0discardingThreshold><queueSize>256queueSize><appender-ref ref&#61;"INFO-LOG"/>appender><appender name&#61;"ASYNC-ERROR" class&#61;"ch.qos.logback.classic.AsyncAppender"><discardingThreshold>0discardingThreshold><queueSize>256queueSize><appender-ref ref&#61;"ERROR-LOG"/>appender><springProfile name&#61;"dev"><logger name&#61;"com.haoqian" level&#61;"info"/>springProfile><root level&#61;"info"><appender-ref ref&#61;"CONSOLE"/><appender-ref ref&#61;"DEBUG_FILE"/><appender-ref ref&#61;"INFO_FILE"/><appender-ref ref&#61;"WARN_FILE"/><appender-ref ref&#61;"ERROR_FILE"/>root>
configuration>
第二步&#xff1a;配置文件application.yml 中配置日志文件位置 &#xff08;如果 日志文件名为logback-spring.xml且放在resources路径下可一不配置&#xff09;
spring:......
logging:config: classpath:logback-spring.xml
第三步&#xff1a;使用Logger对象打印日志
方式一&#xff1a;使用工厂创建
&#64;RestController
public class EmployeeController {private final Logger log &#61; LoggerFactory.getLogger(this.getClass());&#64;GetMapping("testCustomException/{num}")&#64;TraceLogpublic Result testCustomException(&#64;PathVariable("num") int num) {try {int a &#61; 10 / num;return Result.success().data(a);} catch (Exception e) {log.error("error:", e);return Result.failure(ResultCodeEnum.PARAM_IS_INVALID);}}
}
方式二&#xff1a;使用lombok简化
import lombok.extern.slf4j.Slf4j;&#64;Slf4j
&#64;RestController
public class EmployeeController {&#64;GetMapping("testCustomException/{num}")&#64;TraceLogpublic Result testCustomException(&#64;PathVariable("num") int num) {try {int a &#61; 10 / num;return Result.success().data(a);} catch (Exception e) {log.error("error:", e);return Result.failure(ResultCodeEnum.PARAM_IS_INVALID);}}
}
注意&#xff1a;其中的Result和ResultCodeEnum类来源于另一片文章介绍的 “Java 统一封装响应结果”
https://blog.csdn.net/QiuHaoqian/article/details/113493682
2 验证
发送请求 http://localhost:8080/testCustomException/0
控制台日志打印如下&#xff1a;
日志打印文件如下&#xff1a;