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


Posted in Java/Android onAugust 30, 2021
  • 定义工具类-创建对应的日志对象
  • 定义枚举类-存储定义的日志文件名称
  • 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/Android 相关文章推荐
深入理解java.lang.String类的不可变性
Jun 27 Java/Android
新手初学Java网络编程
Jul 07 Java/Android
mybatis 获取无数据的字段不显示的问题
Jul 15 Java/Android
SpringBoot+VUE实现数据表格的实战
Aug 02 Java/Android
springboot+WebMagic+MyBatis爬虫框架的使用
Aug 07 Java/Android
Java 实现限流器处理Rest接口请求详解流程
Nov 02 Java/Android
SpringCloud Feign请求头删除修改的操作代码
Mar 20 Java/Android
MybatisPlus EntityWrapper如何自定义SQL
Mar 22 Java/Android
详细介绍Java中的CyclicBarrier
Apr 13 Java/Android
java中如何截取字符串最后一位
Jul 07 Java/Android
Java获取字符串编码格式实现思路
Sep 23 Java/Android
Java Redisson多策略注解限流
Sep 23 Java/Android
logback如何自定义日志存储
Aug 30 #Java/Android
idea以任意顺序debug多线程程序的具体用法
Aug 30 #Java/Android
Logback 使用TurboFilter实现日志级别等内容的动态修改操作
Aug 30 #Java/Android
Java SSM配置文件案例详解
Aug 30 #Java/Android
java调用Restful接口的三种方法
Aug 23 #Java/Android
JVM钩子函数的使用场景详解
Java中CyclicBarrier和CountDownLatch的用法与区别
Aug 23 #Java/Android
You might like
用PHP进行MySQL删除记录操作代码
2008/06/07 PHP
php入门之连接mysql数据库的一个类
2012/04/21 PHP
强烈声明: 不要使用(include/require)_once
2013/06/06 PHP
PHP转换IP地址到真实地址的方法详解
2013/06/09 PHP
如何使用php判断所处服务器操作系统的类型
2013/06/20 PHP
php操作MongoDB基础教程(连接、新增、修改、删除、查询)
2014/03/25 PHP
JObj预览一个JS的框架
2008/03/13 Javascript
Prototype ObjectRange对象学习
2009/07/19 Javascript
EasyUI 中 MenuButton 的使用方法
2012/07/14 Javascript
将两个div左右并列显示并实现点击标题切换内容
2013/10/22 Javascript
javascript实现动态模态绑定grid过程代码
2014/09/22 Javascript
jquery京东商城双11焦点图多图广告特效代码分享
2015/09/06 Javascript
JavaScript动态生成二维码图片
2016/04/20 Javascript
js 自带的sort() 方法全面了解
2016/08/16 Javascript
extjs简介_动力节点Java学院整理
2017/07/17 Javascript
nginx部署访问vue-cli搭建的项目的方法
2018/02/12 Javascript
在HTML文档中嵌入JavaScript的四种方法
2018/05/07 Javascript
jQuery实现获取选中复选框的值实例详解
2018/06/28 jQuery
详解react内联样式使用webpack将px转rem
2018/09/13 Javascript
javascript将非数值转换为数值
2018/09/13 Javascript
React-redux实现小案例(todolist)的过程
2019/09/29 Javascript
python操作mysql数据库
2017/03/05 Python
Python DataFrame 设置输出不显示index(索引)值的方法
2018/06/07 Python
对python中字典keys,values,items的使用详解
2019/02/03 Python
python的setattr函数实例用法
2020/12/16 Python
菲律宾票务网站:StubHub菲律宾
2018/04/21 全球购物
Carrs Silver官网:英国著名的银器品牌
2020/08/29 全球购物
夜大自我鉴定
2013/10/31 职场文书
红旗方阵解说词
2014/02/12 职场文书
竞选纪律委员演讲稿
2014/09/13 职场文书
2014年新教师工作总结
2014/11/08 职场文书
怎样写离婚协议书
2015/01/26 职场文书
2015年教师节广播稿
2015/08/19 职场文书
优秀教师主要事迹材料
2015/11/04 职场文书
MySQL时间设置注意事项的深入总结
2021/05/06 MySQL
实现GO语言对数组切片去重
2022/04/20 Golang