【日志篇】Spring Boot 日志输出到文件

写在最前

在 【数据篇】SpringBoot 整合 MyBatis-Plus 增强 MyBatis ,基友搭配,效率翻倍 Demo 中增加日志输出文件。Demo 地址:mingyue-springboot-mybatis-plus

日志输出文件

增加配置文件

resource 目录下增加 logback-spring.xml




<configuration debug="false" scan="false">
  <springProperty scop="context" name="spring.application.name" source="spring.application.name" defaultValue=""/>
  <property name="log.path" value="/data/logs/${spring.application.name}"/>
  
  <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}}"/>
  
  <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"/>
  
  <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>${CONSOLE_LOG_PATTERN}pattern>
    encoder>
  appender>

  
  <appender name="debug" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${log.path}/debug.logfile>
    <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
      <fileNamePattern>${log.path}/%d{yyyy-MM, aux}/debug.%d{yyyy-MM-dd}.%i.log.gzfileNamePattern>
      <maxFileSize>50MBmaxFileSize>
      <maxHistory>30maxHistory>
    rollingPolicy>
    <encoder>
      <pattern>%date [%thread] %-5level [%logger{50}] %file:%line - %msg%npattern>
    encoder>
  appender>

  
  <appender name="error" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${log.path}/error.logfile>
    <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
      <fileNamePattern>${log.path}/%d{yyyy-MM}/error.%d{yyyy-MM-dd}.%i.log.gzfileNamePattern>
      <maxFileSize>50MBmaxFileSize>
      <maxHistory>30maxHistory>
    rollingPolicy>
    <encoder>
      <pattern>%date [%thread] %-5level [%logger{50}] %file:%line - %msg%npattern>
    encoder>
    <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
      <level>ERRORlevel>
    filter>
  appender>

  
  <logger name="com.alibaba.nacos" level="OFF">
    <appender-ref ref="error"/>
  logger>

  
  <root level="INFO">
    <appender-ref ref="console"/>
    <appender-ref ref="debug"/>
    <appender-ref ref="error"/>
  root>
configuration>

测试日志输出

data\logs${spring.application.name} 下有日志文件:

  • debug.log
  • error.log

你可能感兴趣的:(Spring,全家桶,log,日志)