美文网首页
log4j,log4j2,logback日志框架的使用

log4j,log4j2,logback日志框架的使用

作者: 溪水散人 | 来源:发表于2020-03-29 11:01 被阅读0次

    SpringBoot环境下使用

    目标:
    以debug,info,error三个日志级别为例,控制台能打印这三个日志级别,同时将不同的级别输出到不同的日志文件

    log4j

    • Maven依赖
     <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
                <version>2.1.3.RELEASE</version>
                <!--排除自带的日志框架-->
                <exclusions>
                    <exclusion>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-logging</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
            <!--添加log4j-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-log4j</artifactId>
                <version>1.3.8.RELEASE</version>
            </dependency>
      </dependencies>
    
    • log4j.properties
    # LOG4J配置
    #注意:DEBUG控制全局的日志级别
    log4j.rootCategory=DEBUG, console, infoFile, errorFile ,debugFile
    LOG_PATH=E:/logs/learn-log/log4j
    LOG_PATTERN=[%d{yyyy-MM-dd HH:mm:ss,SSS}]-[%p]:%m %x %n
    # 控制台输出
    log4j.appender.console = org.apache.log4j.ConsoleAppender
    log4j.appender.console.Target = System.out
    log4j.appender.console.layout = org.apache.log4j.PatternLayout
    log4j.appender.console.layout.ConversionPattern =${LOG_PATTERN}
    
    ##debug以上级别的日志会进入改文件
    #log4j.appender.debugFile = org.apache.log4j.DailyRollingFileAppender
    log4j.appender.debugFile =com.hx.learn.log.log4j.config.AppenderConfig
    log4j.appender.debugFile.Threshold = DEBUG
    log4j.appender.debugFile.File = ${LOG_PATH}/debug.log
    log4j.appender.debugFile.DatePattern = '.'yyyy-MM-dd'.log'
    log4j.appender.debugFile.Append=true
    log4j.appender.debugFile.layout = org.apache.log4j.PatternLayout
    log4j.appender.debugFile.layout.ConversionPattern =${LOG_PATTERN}
    
    ##info以上级别的日志会进入改文件
    #log4j.appender.infoFile = org.apache.log4j.DailyRollingFileAppender
    log4j.appender.infoFile =com.hx.learn.log.log4j.config.AppenderConfig
    log4j.appender.infoFile.Threshold = INFO
    log4j.appender.infoFile.File = ${LOG_PATH}/log.log
    log4j.appender.infoFile.DatePattern = '.'yyyy-MM-dd'.log'
    log4j.appender.infoFile.Append=true
    log4j.appender.infoFile.layout = org.apache.log4j.PatternLayout
    log4j.appender.infoFile.layout.ConversionPattern =${LOG_PATTERN}
    ## error以上级别的日志会进入改文件
    #log4j.appender.errorFile = org.apache.log4j.DailyRollingFileAppender
    log4j.appender.errorFile =com.hx.learn.log.log4j.config.AppenderConfig
    log4j.appender.errorFile.Threshold = ERROR
    log4j.appender.errorFile.File = ${LOG_PATH}/error.log
    log4j.appender.errorFile.DatePattern = '.'yyyy-MM-dd'.log'
    log4j.appender.errorFile.Append=true
    log4j.appender.errorFile.layout = org.apache.log4j.PatternLayout
    log4j.appender.errorFile.layout.ConversionPattern =${LOG_PATTERN}
    
    

    log4j2

    • Maven依赖
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
                <version>2.1.3.RELEASE</version>
                <!--排除自带的日志框架-->
                <exclusions>
                    <exclusion>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-logging</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
            <!--添加log4j2-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-log4j2</artifactId>
                <version>2.1.3.RELEASE</version>
            </dependency>
        </dependencies>
    
    • log4j.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <!-- status表示log4j2本身的日志信息打印级别,和下面的level,不是一个概念 -->
    <!--TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFF-->
    <Configuration status="OFF" monitorInterval="30">
        <Properties>
            <!-- 格式化输出:%date表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度 %msg:日志消息,%n是换行符-->
            <!-- %logger{36} 表示 Logger 名字最长36个字符 -->
            <property name="LOG_PATTERN" value="[%d{yyyy-MM-dd HH:mm:ss.SSS}] [%thread] %-5level %logger{36} - %msg%n" />
            <!-- 定义日志存储的路径 -->
            <Property name="LOG_FILE_PATH">E:/logs/learn-log/log4j2</Property>
            <property name="FILE_NAME" value="log4j2" />
        </Properties>
        <Appenders>
            <!--打印到控制台-->
            <Console name="ConsoleAppender" target="SYSTEM_OUT" follow="true">
                <PatternLayout pattern="${LOG_PATTERN}"/>
                <!--控制台只输出level及其以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
                <ThresholdFilter level="debug" onMatch="ACCEPT" onMismatch="DENY"/>
            </Console>
    
            <!-- 这个会打印出所有的debug及以下级别的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->
            <RollingFile name="RollingFileDebug" fileName="${LOG_FILE_PATH}/${FILE_NAME}_debug.log" filePattern="${FILE_PATH}/${FILE_NAME}-INFO-%d{yyyy-MM-dd}_%i.log.gz">
                <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
               <!-- <ThresholdFilter level="debug" onMatch="ACCEPT" onMismatch="DENY"/>-->
                <Filters>
                    <ThresholdFilter level="INFO" onMatch="DENY" onMismatch="NEUTRAL"/>
                    <ThresholdFilter level="debug" onMatch="ACCEPT" onMismatch="DENY"/>
                </Filters>
                <PatternLayout pattern="${LOG_PATTERN}"/>
                <Policies>
                    <!--interval属性用来指定多久滚动一次,默认是1 hour-->
                    <TimeBasedTriggeringPolicy interval="1"/>
                    <SizeBasedTriggeringPolicy size="10MB"/>
                </Policies>
                <!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件开始覆盖-->
                <DefaultRolloverStrategy max="15"/>
            </RollingFile>
    
            <!-- 这个会打印出所有的info及以下级别的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->
            <RollingFile name="RollingFileInfo" fileName="${LOG_FILE_PATH}/${FILE_NAME}_info.log" filePattern="${FILE_PATH}/${FILE_NAME}-INFO-%d{yyyy-MM-dd}_%i.log.gz">
                <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
                <!--<ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>-->
                <Filters>
                    <!--通过交集的方式只匹配INFO级别日志-->
                    <ThresholdFilter level="ERROR" onMatch="DENY" onMismatch="NEUTRAL"/>
                    <ThresholdFilter level="INFO" onMatch="ACCEPT" onMismatch="DENY"/>
                </Filters>
                <PatternLayout pattern="${LOG_PATTERN}"/>
                <Policies>
                    <!--interval属性用来指定多久滚动一次,默认是1 hour-->
                    <TimeBasedTriggeringPolicy interval="1"/>
                    <SizeBasedTriggeringPolicy size="10MB"/>
                </Policies>
                <!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件开始覆盖-->
                <DefaultRolloverStrategy max="15"/>
            </RollingFile>
    
            <!-- 这个会打印出所有的info及以下级别的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->
            <RollingFile name="RollingFileError" fileName="${LOG_FILE_PATH}/${FILE_NAME}_error.log" filePattern="${FILE_PATH}/${FILE_NAME}-INFO-%d{yyyy-MM-dd}_%i.log.gz">
                <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
                <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/>
                <PatternLayout pattern="${LOG_PATTERN}"/>
                <Policies>
                    <!--interval属性用来指定多久滚动一次,默认是1 hour-->
                    <TimeBasedTriggeringPolicy interval="1"/>
                    <SizeBasedTriggeringPolicy size="10MB"/>
                </Policies>
                <!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件开始覆盖-->
                <DefaultRolloverStrategy max="15"/>
            </RollingFile>
    
        </Appenders>
    
        <Loggers>
            <!-- 此level设置的日志级别,是过滤项目中输出的日志信息,和ThresholdFilter的level有所区别 -->
            <Root level="DEBUG">
                <AppenderRef ref="ConsoleAppender" />
                <AppenderRef ref="RollingFileDebug" />
                <AppenderRef ref="RollingFileInfo" />
                <AppenderRef ref="RollingFileError" />
            </Root>
        </Loggers>
    </Configuration>
    

    log4back

    • Maven依赖
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
                <version>2.1.3.RELEASE</version>
            </dependency>
        </dependencies>
    
    • logback.xml
    <configuration debug="false" scan="true" scanPeriod="10 seconds">
    
        <contextName>logback</contextName>
    
        <!--输出sql语句-->
        <!--    <logger name="com.hx.ams.admin.mapper" level="debug"/>-->
        <property name="path" value="E:/logs/learn-log/logback"/>
        <property name="maxHistory" value="30"/>
        <property name="maxFileSize" value="50MB"/>
    
        <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
            <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
                <level>debug</level>
            </filter>
            <encoder>
                <pattern>[%date] %level [%thread] %logger{36} [%file : %line] %msg%n
                </pattern>
            </encoder>
        </appender>
    
        <appender name="debug_file" class="ch.qos.logback.core.rolling.RollingFileAppender">
            <file>${path}/debug.log</file>
            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                <!-- 每天一归档 -->
                <fileNamePattern>${path}/debug.log.%d{yyyy-MM-dd}-%i.zip</fileNamePattern>
                <maxHistory>${maxHistory}</maxHistory>
                <timeBasedFileNamingAndTriggeringPolicy
                        class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                    <maxFileSize>${maxFileSize}</maxFileSize>
                </timeBasedFileNamingAndTriggeringPolicy>
            </rollingPolicy>
            <encoder>
                <pattern>[%date] %level [%thread] %logger{36} [%file : %line] %msg%n
                </pattern>
            </encoder>
            <filter class="ch.qos.logback.classic.filter.LevelFilter">
                <level>DEBUG</level>
                <onMatch>ACCEPT</onMatch>
                <onMismatch>DENY</onMismatch>
            </filter>
        </appender>
    
        <appender name="info_file" class="ch.qos.logback.core.rolling.RollingFileAppender">
            <file>${path}/info.log</file>
            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                <!-- 每天一归档 -->
                <fileNamePattern>${path}/info.log.%d{yyyy-MM-dd}-%i.zip</fileNamePattern>
                <maxHistory>${maxHistory}</maxHistory>
                <timeBasedFileNamingAndTriggeringPolicy
                        class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                    <maxFileSize>${maxFileSize}</maxFileSize>
                </timeBasedFileNamingAndTriggeringPolicy>
            </rollingPolicy>
            <encoder>
                <pattern>[%date] %level [%thread] %logger{36} [%file : %line] %msg%n
                </pattern>
            </encoder>
            <filter class="ch.qos.logback.classic.filter.LevelFilter">
                <level>INFO</level>
                <onMatch>ACCEPT</onMatch>
                <onMismatch>DENY</onMismatch>
            </filter>
        </appender>
    
        <appender name="warn_file" class="ch.qos.logback.core.rolling.RollingFileAppender">
            <file>${path}/warn.log</file>
            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                <!-- 每天一归档 -->
                <fileNamePattern>${path}/warn.log.%d{yyyy-MM-dd}-%i.zip</fileNamePattern>
                <maxHistory>${maxHistory}</maxHistory>
                <timeBasedFileNamingAndTriggeringPolicy
                        class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                    <maxFileSize>${maxFileSize}</maxFileSize>
                </timeBasedFileNamingAndTriggeringPolicy>
            </rollingPolicy>
            <encoder>
                <pattern>[%date] %level [%thread] %logger{36} [%file : %line] %msg%n
                </pattern>
            </encoder>
            <filter class="ch.qos.logback.classic.filter.LevelFilter">
                <level>WARN</level>
                <onMatch>ACCEPT</onMatch>
                <onMismatch>DENY</onMismatch>
            </filter>
        </appender>
    
    
        <appender name="error_file" class="ch.qos.logback.core.rolling.RollingFileAppender">
            <file>${path}/error.log</file>
            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                <!-- 每天一归档 -->
                <fileNamePattern>${path}/error.log.%d{yyyy-MM-dd}-%i.zip</fileNamePattern>
                <maxHistory>${maxHistory}</maxHistory>
                <timeBasedFileNamingAndTriggeringPolicy
                        class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                    <maxFileSize>${maxFileSize}</maxFileSize>
                </timeBasedFileNamingAndTriggeringPolicy>
            </rollingPolicy>
            <encoder>
                <pattern>[%date] %level [%thread] %logger{36} [%file : %line] %msg%n
                </pattern>
            </encoder>
            <filter class="ch.qos.logback.classic.filter.LevelFilter">
                <level>ERROR</level>
                <onMatch>ACCEPT</onMatch>
                <onMismatch>DENY</onMismatch>
            </filter>
        </appender>
    
        <root>
            <level value="debug"/>
            <appender-ref ref="console"/>
            <appender-ref ref="debug_file"/>
            <appender-ref ref="info_file"/>
            <appender-ref ref="warn_file"/>
            <appender-ref ref="error_file"/>
        </root>
    
    </configuration>
    
    

    相关文章

      网友评论

          本文标题:log4j,log4j2,logback日志框架的使用

          本文链接:https://www.haomeiwen.com/subject/lguyuhtx.html