• SpringBoot配置log4j


    *注 本文转载于《https://www.cnblogs.com/vitasyuan/p/8783838.html》,并亲自测试成功

    环境

                   1.Maven项目

                   2.Log4j2日志配置

                   3.Mybatis框架

    配置

    1.添加log4j相关依赖

    在pom.xml文件中添加相关依赖:

    <!--配置log4j-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-log4j2</artifactId>
            </dependency>
            <!-- 加上这个才能辨认到log4j2.yml文件 -->
            <dependency>
                <groupId>com.fasterxml.jackson.dataformat</groupId>
                <artifactId>jackson-dataformat-yaml</artifactId>
                <version>2.9.3</version>
            </dependency>

    2.去除其他log依赖

    应该去除掉其他依赖中包含的log依赖,否则会有冲突。去除依赖的代码如下:

    <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter</artifactId>
                <exclusions>
                    <exclusion>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-logging</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
            
             <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>1.3.2</version>
                <exclusions>
                    <exclusion>
                        <!--配置log4j-->
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-logging</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
    

      

    3.添加日志配置文件

    在resource文件夹下添加log4j2.yml文件,文件内容如下:

    Configuration:
      status: warn
    
      Properties: # 定义全局变量
        Property: # 缺省配置(用于开发环境)。其他环境需要在VM参数中指定,如下:
          #测试:-Dlog.level.console=warn -Dlog.level.xjj=trace
          #生产:-Dlog.level.console=warn -Dlog.level.xjj=info
          - name: log.level.console
            value: trace
          - name: log.level.xjj
            value: trace
          - name: log.path
            value: logs
          - name: project.name
            value: lifeTrackDB
    
      Appenders:
        Console:  #输出到控制台
          name: CONSOLE
          target: SYSTEM_OUT
          ThresholdFilter:
            level: ${sys:log.level.console} # “sys:”表示:如果VM参数中没指定这个变量值,则使用本文件中定义的缺省全局变量值
            onMatch: ACCEPT
            onMismatch: DENY
          PatternLayout:
            pattern: "%d{yyyy-MM-dd HH:mm:ss,SSS}:%4p %t (%F:%L) - %m%n"
    
        RollingFile: # 输出到文件,超过128MB归档
          - name: ROLLING_FILE
            ignoreExceptions: false
            fileName: ${log.path}/${project.name}.log
            filePattern: "${log.path}/$${date:yyyy-MM}/${project.name}-%d{yyyy-MM-dd}-%i.log.gz"
            PatternLayout:
              pattern: "%d{yyyy-MM-dd HH:mm:ss,SSS}:%4p %t (%F:%L) - %m%n"
            Policies:
              SizeBasedTriggeringPolicy:
                size: "128 MB"
            DefaultRolloverStrategy:
              max: 1000
    
          - name: EXCEPTION
            ignoreExceptions: false
            fileName: ${log.path}/exception.log
            filePattern: "${log.path}/$${date:yyyy-MM}/${project.name}-%d{yyyy-MM-dd}-%i.log.gz"
            PatternLayout:
              pattern: "%d{yyyy-MM-dd HH:mm:ss,SSS}:%4p %t (%F:%L) - %m%n"
            Policies:
              SizeBasedTriggeringPolicy:
                size: "128 MB"
            DefaultRolloverStrategy:
              max: 1000
    
          - name: WEB_REQUEST
            ignoreExceptions: false
            fileName: ${log.path}/web_request.log
            filePattern: "${log.path}/$${date:yyyy-MM}/${project.name}-%d{yyyy-MM-dd}-%i.log.gz"
            PatternLayout:
              pattern: "%d{yyyy-MM-dd HH:mm:ss,SSS}:%4p %t (%F:%L) - %m%n"
            Policies:
              SizeBasedTriggeringPolicy:
                size: "128 MB"
            DefaultRolloverStrategy:
              max: 1000
    
          - name: MYBATIS_SQL
            ignoreExceptions: false
            fileName: ${log.path}/mybatis_sql.log
            filePattern: "${log.path}/$${date:yyyy-MM}/${project.name}-%d{yyyy-MM-dd}-%i.log.gz"
            PatternLayout:
              pattern: "%d{yyyy-MM-dd HH:mm:ss,SSS}:%4p %t (%F:%L) - %m%n"
            Policies:
              SizeBasedTriggeringPolicy:
                size: "128 MB"
            DefaultRolloverStrategy:
              max: 1000
    
          - name: TIME_TASK
            ignoreExceptions: false
            fileName: ${log.path}/time_task.log
            filePattern: "${log.path}/$${date:yyyy-MM}/${project.name}-%d{yyyy-MM-dd}-%i.log.gz"
            PatternLayout:
              pattern: "%d{yyyy-MM-dd HH:mm:ss,SSS}:%4p %t (%F:%L) - %m%n"
            Policies:
              SizeBasedTriggeringPolicy:
                size: "128 MB"
            DefaultRolloverStrategy:
              max: 1000
    
          - name: ASYNC_TASK
            ignoreExceptions: false
            fileName: ${log.path}/async_task.log
            filePattern: "${log.path}/$${date:yyyy-MM}/${project.name}-%d{yyyy-MM-dd}-%i.log.gz"
            PatternLayout:
              pattern: "%d{yyyy-MM-dd HH:mm:ss,SSS}:%4p %t (%F:%L) - %m%n"
            Policies:
              SizeBasedTriggeringPolicy:
                size: "128 MB"
            DefaultRolloverStrategy:
              max: 1000
    
    
      Loggers:
        Root:
          level: info
          AppenderRef:
            - ref: CONSOLE
            - ref: ROLLING_FILE
        Logger:
          - name: WEB_REQUEST_LOG
            additivity: false
            level: info
            AppenderRef:
              - ref: WEB_REQUEST
    
          - name: com.lifeTrackDB.mapper # 指定Dao层项目路径,并打印sql执行日志
            additivity: false
            level: debug   # debug info track 此地为了测试,用了Debug级别
            AppenderRef:
              - ref: MYBATIS_SQL
    
          - name: TIME_TASK_LOG
            additivity: false
            level: trace
            AppenderRef:
              - ref: TIME_TASK
    
          - name: ASYNC_TASK_LOG
            additivity: false
            level: trace
            AppenderRef:
              - ref: ASYNC_TASK
    
          - name: EXCEPTION_LOG
            additivity: false
            level: trace
            AppenderRef:
              - ref: EXCEPTION

    需要注意在配置文件中Logger:标签下添加多个日志项目。其中

     - name: com.example.demo.business #打印sql执行日志
            additivity: false
            level: trace   # trace debug info
            AppenderRef:
              - ref: MYBATIS_SQL

    配置为打印mybatis执行的sql语句。

    4.重启项目

    重启项目,日志配置即可成功。

    5.目录结构

    使用日志系统

    LogsUtil.java

    package com.lifeTrackDB.Utils;
    
    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.Logger;
    
    
    public class LogsUtil {
        private static Logger logger;
        
        private LogsUtil() {}
        
        /**
         * 获取Logger对象
         * @param TypeName
         *      需要打印的Log4J对象,根据配置文件“log4j2.yml”中的Loggers.Logger.name,例如:WEB_REQUEST_LOG、TIME_TASK_LOG
         * @return Logger
         *      返回 org.apache.logging.log4j.Logger 对象
         * */
        public static Logger getLogger(String TypeName) {
            return logger=LogManager.getLogger(TypeName);
        }
        
        /**
         * 打印消息
         * @param TypePrint
         *      打印的类型:例如info,debug
         * @param msg
         *      打印的消息
         * */
        public static void printLogMsg(String TypePrint,String msg) {
            switch (TypePrint) {
                case "info":
                    logger.info(msg);
                    break;
            }
        }
    }
  • 相关阅读:
    【javascript基础】【转】各浏览器对页面外部资源加载的策略
    【javascript基础】【转】javascript模块化、模块加载器初探
    【javascript基础】js线程机制【转】
    【css】【转】那些年我们一起清除过的浮动
    IL入门之旅(三)——Dump对象
    学习TPL(一)
    弱引用应用的注意点
    IL入门之旅(二)——动态包装
    学习TPL(二)
    IL之旅(前言)
  • 原文地址:https://www.cnblogs.com/hzb462606/p/11303272.html
Copyright © 2020-2023  润新知