使用logback实现按自己的需求打印日志到自定义的文件里

 更新时间:2021年08月30日 10:51:18   作者:烛火下的乌托邦丶  
这篇文章主要介绍了使用logback实现按自己的需求打印日志到自定义的文件里,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
  • 定义工具类-创建对应的日志对象
  • 定义枚举类-存储定义的日志文件名称
  • logback.xml里配置对应的日志名称和日志等级

1、工具类 LoggerUtils

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LoggerUtils {
    public static <T> Logger Logger(Class<T> clazz) {
        return LoggerFactory.getLogger(clazz);
    }
    /**
     * 打印到指定的文件下
     *
     * @param desc 日志文件名称
     * @return
     */
    public static Logger Logger(LogFileName desc) {
        return LoggerFactory.getLogger(desc.getLogFileName());
    }
}

2、枚举类 LogFileName

import org.apache.commons.lang3.StringUtils;
public enum LogFileName {
    //配置到logback.xml中的logger name="getNextHh"
    GET_NEXT_HH("getNextHh"),
    GET_AGAIN_HH("getAgainHh"),
    GET_AI_ACTION("getAiAction"),
    TRAIN_ERROR("trainError"),
    USER_ERROR("userError"),
    PAY_ERROR("payError"),
    REVIEW_ERROR("reviewError"),
    WX_ERROR("wxError"),
    SYSTEM_ERROR("systemError"),
    PAY_DEBUG("payDebug");
    private String logFileName;
    LogFileName(String fileName) {
        this.logFileName = fileName;
    }
    public String getLogFileName() {
        return logFileName;
    }
    public void setLogFileName(String logFileName) {
        this.logFileName = logFileName;
    }
    public static LogFileName getAwardTypeEnum(String value) {
        LogFileName[] arr = values();
        for (LogFileName item : arr) {
            if (null != item && StringUtils.isNotBlank(item.logFileName)) {
                return item;
            }
        }
        return null;
    }
}

3、logger.xml, 按需配置即可

<?xml version="1.0" encoding="UTF-8"?>
<configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xsi:noNamespaceSchemaLocation="http://www.padual.com/java/logback.xsd" debug="false"
               scan="true" scanPeriod="30 second">
    <property name="PROJECT" value="poker_system"/>
    <property name="ROOT" value="C:/Users/Administrator/Desktop/logs/${PROJECT}/"/>
    <property name="FILESIZE" value="50MB"/>
    <property name="MAXHISTORY" value="30"/>
    <!-- 彩色日志 -->
    <!-- 彩色日志依赖的渲染类 -->
    <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}}"/>
    <timestamp key="DATETIME" datePattern="yyyy-MM-dd HH:mm:ss"/>
    <!-- 控制台打印 -->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
            <charset>UTF-8</charset>
        </encoder>
    </appender>
    <!-- ERROR 输入到文件,按日期和文件大小 -->
    <appender name="ERROR-OUT" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <encoder>
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <!--过滤器,只打ERROR级别的日志-->
            <level>ERROR</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${ROOT}%d/error/systemError.%i.log</fileNamePattern>
            <maxHistory>${MAXHISTORY}</maxHistory>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${FILESIZE}</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
    </appender>
    <appender name="TRAINERROR-OUT" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <encoder>
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <!--过滤器,只打ERROR级别的日志-->
            <level>ERROR</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${ROOT}%d/error/trainError.%i.log</fileNamePattern>
            <maxHistory>${MAXHISTORY}</maxHistory>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${FILESIZE}</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
    </appender>
    <appender name="USERERROR-OUT" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <encoder>
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <!--过滤器,只打ERROR级别的日志-->
            <level>ERROR</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${ROOT}%d/error/userError.%i.log</fileNamePattern>
            <maxHistory>${MAXHISTORY}</maxHistory>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${FILESIZE}</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
    </appender>
    <appender name="PAYERROR-OUT" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <encoder>
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <!--过滤器,只打ERROR级别的日志-->
            <level>ERROR</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${ROOT}%d/error/payError.%i.log</fileNamePattern>
            <maxHistory>${MAXHISTORY}</maxHistory>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${FILESIZE}</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
    </appender>
    <appender name="REVIEWERROR-OUT" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <encoder>
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <!--过滤器,只打ERROR级别的日志-->
            <level>ERROR</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${ROOT}%d/error/reviewError.%i.log</fileNamePattern>
            <maxHistory>${MAXHISTORY}</maxHistory>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${FILESIZE}</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
    </appender>
    <!-- WARN 输入到文件,按日期和文件大小 -->
    <appender name="WARN-OUT" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <encoder>
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>WARN</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${ROOT}%d/warn.%i.log</fileNamePattern>
            <maxHistory>${MAXHISTORY}</maxHistory>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${FILESIZE}</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
    </appender>
    <!-- INFO 输入到文件,按日期和文件大小 -->
    <appender name="INFO-OUT" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <encoder>
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>INFO</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${ROOT}%d/info.%i.log</fileNamePattern>
            <maxHistory>${MAXHISTORY}</maxHistory>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${FILESIZE}</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
    </appender>
    <!-- DEBUG 输入到文件,按日期和文件大小 -->
    <appender name="DEBUG-OUT" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <encoder>
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>DEBUG</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${ROOT}%d/debug.%i.log</fileNamePattern>
            <maxHistory>${MAXHISTORY}</maxHistory>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${FILESIZE}</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
    </appender>
    <!-- DEBUG 输入到文件,按日期和文件大小 -->
    <appender name="PAYDEBUG-OUT" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <encoder>
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>DEBUG</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${ROOT}%d/debug/payDebug.%i.log</fileNamePattern>
            <maxHistory>${MAXHISTORY}</maxHistory>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${FILESIZE}</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
    </appender>
    <!-- TRACE 输入到文件,按日期和文件大小 -->
    <appender name="TRACE-OUT" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <encoder>
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>TRACE</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${ROOT}%d/trace.%i.log</fileNamePattern>
            <maxHistory>${MAXHISTORY}</maxHistory>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${FILESIZE}</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
    </appender>
    <!-- Logger 根目录 -->
    <root level="INFO">
        <appender-ref ref="STDOUT"/>
        <!--<appender-ref ref="ERROR-OUT"/>-->
        <!--<appender-ref ref="WARN-OUT"/>-->
        <!--<appender-ref ref="INFO-OUT"/>-->
        <!--<appender-ref ref="TRACE-OUT"/>-->
        <!--<appender-ref ref="REVIEWERROR-OUT"/>-->
        <!--<appender-ref ref="PAYDEBUG-OUT"/>-->
        <!--<appender-ref ref="PAYERROR-OUT"/>-->
        <!--<appender-ref ref="USERERROR-OUT"/>-->
        <!--<appender-ref ref="TRAINERROR-OUT"/>-->
    </root>
    <logger name="com.xxx" additivity="false" level="DEBUG">
        <appender-ref ref="DEBUG-OUT"/>
    </logger>
    <logger name="com.xxx" additivity="false" level="ERROR">
        <appender-ref ref="ERROR-OUT"/>
    </logger>
    <logger name="com.xxx" additivity="false" level="INFO">
        <appender-ref ref="INFO-OUT"/>
    </logger>
    <logger name="com.xxx" additivity="false" level="TRACE">
        <appender-ref ref="TRACE-OUT"/>
    </logger>
    <logger name="com.xxx" level="STDOUT">
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="ERROR-OUT"/>
        <appender-ref ref="WARN-OUT"/>
        <appender-ref ref="INFO-OUT"/>
        <appender-ref ref="TRACE-OUT"/>
        <appender-ref ref="REVIEWERROR-OUT"/>
        <appender-ref ref="DEBUG-OUT"/>
        <!--<appender-ref ref="PAYDEBUG-OUT"/>-->
        <appender-ref ref="PAYERROR-OUT"/>
        <appender-ref ref="USERERROR-OUT"/>
        <appender-ref ref="TRAINERROR-OUT"/>
    </logger>
    <!-- 不同的业务逻辑日志打印到指定文件夹-->
    <logger name="trainError" level="ERROR">
        <appender-ref ref="TRAINERROR-OUT"/>
    </logger>
    <logger name="userError" level="ERROR">
        <appender-ref ref="USERERROR-OUT"/>
    </logger>
    <logger name="payError" level="ERROR">
        <appender-ref ref="PAYERROR-OUT"/>
    </logger>
    <logger name="payDebug" additivity="false" level="DEBUG">
        <appender-ref ref="PAYDEBUG-OUT"/>
    </logger>
    <logger name="reviewError" level="ERROR">
        <appender-ref ref="REVIEWERROR-OUT"/>
    </logger>
    <logger name="systemError" level="ERROR">
        <appender-ref ref="ERROR-OUT"/>
    </logger>
</configuration>

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Java并发容器之ConcurrentLinkedQueue详解

    Java并发容器之ConcurrentLinkedQueue详解

    这篇文章主要介绍了Java并发容器之ConcurrentLinkedQueue详解,加锁队列的实现较为简单,这里就略过,我们来重点来解读一下非阻塞队列,
    从点到面, 下面我们来看下非阻塞队列经典实现类ConcurrentLinkedQueue,需要的朋友可以参考下
    2023-12-12
  • Java中检查字符串是否以特定字符结尾

    Java中检查字符串是否以特定字符结尾

    这篇文章主要介绍了Java中检查字符串是否以特定字符结尾,文章围绕主题展开字符串匹配问题,具有一定的参考价值需要的小伙伴可以参考一下
    2022-06-06
  • java Servlet 实现动态验证码图片示例

    java Servlet 实现动态验证码图片示例

    这篇文章主要介绍了java Servlet 实现动态验证码图片示例的资料,这里整理了详细的代码,有需要的小伙伴可以参考下。
    2017-02-02
  • 关于replaceFirst使用时的注意事项

    关于replaceFirst使用时的注意事项

    这篇文章主要介绍了关于replaceFirst使用时的注意事项,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-03-03
  • SpringBoot集成Mybatis-plus并实现自动生成相关文件的示例代码

    SpringBoot集成Mybatis-plus并实现自动生成相关文件的示例代码

    Mybatis-Plus是一个优秀的Mybatis增强工具,目前更新到3.1.1,本文通过示例代码给大家介绍SpringBoot集成Mybatis-plus并实现自动生成相关文件的问题,感兴趣的朋友跟随小编一起看看吧
    2021-12-12
  • 解决Java字符串JSON转换异常:cn.hutool.json.JSONException: Mismatched hr and body

    解决Java字符串JSON转换异常:cn.hutool.json.JSONException: Mismatched 

    这篇文章主要给大家介绍了关于如何解决Java字符串JSON转换异常:cn.hutool.json.JSONException: Mismatched hr and body的相关资料,文中将解决的办法通过代码介绍的非常详细,需要的朋友可以参考下
    2024-01-01
  • RequestContextHolder.getRequestAttributes()空指针问题及解决

    RequestContextHolder.getRequestAttributes()空指针问题及解决

    这篇文章主要介绍了RequestContextHolder.getRequestAttributes()空指针问题及解决,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-01-01
  • Maven依赖冲突原因以及解决方法

    Maven依赖冲突原因以及解决方法

    依赖冲突是指项目依赖的某一个 jar 包,有多个不同的版本,因而造成类包版本冲突依赖冲突很经常是类包之间的间接依赖引起的,本文将给大家介绍Maven依赖冲突原因以及解决方法,需要的朋友可以参考下
    2023-12-12
  • MyBatis中多对一和一对多数据的处理方法

    MyBatis中多对一和一对多数据的处理方法

    这篇文章主要介绍了MyBatis中多对一和一对多数据的处理,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-01-01
  • Java面试必备之ArrayList陷阱解析

    Java面试必备之ArrayList陷阱解析

    昨天小枫接到了一个公司的面试电话,其中一道面试题觉得有点意思,在这里和大家一起分享下。面试题是ArrayList如何删除指定元素。乍听很简单的问题,但是如果没有实际踩过坑很容易掉进面试官的陷阱中,我们一起来分析下吧
    2022-02-02

最新评论