zoukankan      html  css  js  c++  java
  • 【Log】logback的配置和使用(一)

    logback介绍

    Logback是由log4j创始人设计的又一个开源日志组件。logback当前分成三个模块:logback-core,logback- classic和logback-access。logback-core是其它两个模块的基础模块。logback-classic是log4j的一个 改良版本。此外logback-classic完整实现SLF4J API使你可以很方便地更换成其它日志系统如log4j或JDK14 Logging。logback-access访问模块与Servlet容器集成提供通过Http来访问日志的功能

    想要学习logback,可以参照Logback用户手册中文版.pdf。

    logback使用

    • 先新建一个maven工程

      

    • logback需要引入的jar包(slf4j-api-x.x.x.jar,logback-core-x.x.x.jar,logback-classic-1.0.0.jar,logback-access-x.x.x.jar),maven的依赖关系如下:
     1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     2     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
     3     <modelVersion>4.0.0</modelVersion>
     4     <groupId>com.test</groupId>
     5     <artifactId>test-logback</artifactId>
     6     <packaging>war</packaging>
     7     <version>0.0.1-SNAPSHOT</version>
     8     <name>test Maven Webapp</name>
     9     <url>http://maven.apache.org</url>
    10     <dependencies>
    11         <dependency>
    12             <groupId>org.slf4j</groupId>
    13             <artifactId>slf4j-api</artifactId>
    14             <version>1.7.5</version>
    15             <type>jar</type>
    16             <scope>compile</scope>
    17         </dependency>
    18 
    19         <dependency>
    20             <groupId>ch.qos.logback</groupId>
    21             <artifactId>logback-core</artifactId>
    22             <version>0.9.30</version>
    23             <type>jar</type>
    24         </dependency>
    25 
    26         <dependency>
    27             <groupId>ch.qos.logback</groupId>
    28             <artifactId>logback-classic</artifactId>
    29             <version>0.9.30</version>
    30             <type>jar</type>
    31         </dependency>
    32 
    33         <dependency>
    34             <groupId>ch.qos.logback</groupId>
    35             <artifactId>logback-access</artifactId>
    36             <version>0.9.30</version>
    37         </dependency>
    38 
    39         <dependency>
    40             <groupId>junit</groupId>
    41             <artifactId>junit</artifactId>
    42             <version>3.8.1</version>
    43             <scope>test</scope>
    44         </dependency>
    45     </dependencies>
    46     <build>
    47         <finalName>test</finalName>
    48     </build>
    49 </project>
    pom.xml
    • 测试类
     1 package com.test;
     2 
     3 import java.util.Date;
     4 
     5 import org.slf4j.Logger;
     6 import org.slf4j.LoggerFactory;
     7 
     8 
     9 public class Test {
    10     
    11     final static  Logger logger  =  LoggerFactory.getLogger(Test.class );
    12 
    13     public static void main(String[] args) throws InterruptedException {
    14         
    15         
    16         logger.debug( "现在的时间是 {}" ,  new Date().toString());
    17         
    18         logger.info( " This time is {}" ,  new Date().toString());
    19         
    20         logger.warn( " This time is {}" ,  new Date().toString());
    21         
    22         logger.error( " This time is {}" ,  new Date().toString());
    23         
    24     }
    25 
    26 }
    Test.java
    • Logback 可以通过编程式配置,或用 XML 格式的配置文件进行配置。
      Logback 采取下面的步骤进行自我配置:
      1. 尝试在 classpath 下查找文件 logback-test.xml;
      2. 如果文件不存在,则查找文件 logback.xml;
      3. 如果两个文件都不存在,logback 用 BasicConfigurator 自动对自己进行配置,这会 导致记录输出到控制台。 

      如果是maven工程直接把logback.xml放在src/main/resources里面即可。

      

     1 <?xml version="1.0" encoding="UTF-8" ?> 
     2 
     3 <!-- scan="true"    当此属性设置为true时,配置文件如果发生改变,将会被重新加载,默认值为true。 -->
     4 <!--  scanPeriod="30 seconds"   设置每30秒自动扫描,若没有指定具体单位则以milliseconds为标准(单位:milliseconds, seconds, minutes or hours)  -->
     5 <!-- debug="false"当此属性设置为true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为false。-->
     6 <configuration  scan="true" scanPeriod="30 seconds">
     7     <!-- 上下文名称  -->
     8     <contextName>test</contextName>
     9     
    10     <!-- 存放日志文件路径 -->
    11     <property name="Log_Home" value="D:/logs/test" />
    12 
    13     <!-- INFO级别 -->
    14     <appender name="FILE_INFO" class="ch.qos.logback.core.rolling.RollingFileAppender">
    15     
    16         <!-- 级别过滤器 -->
    17         <filter class="ch.qos.logback.classic.filter.LevelFilter">
    18             <!-- 设置过滤级别 -->
    19             <level>INFO</level>
    20             <!-- 用于配置符合过滤条件的操作 -->
    21             <onMatch>ACCEPT</onMatch>
    22             <!-- 用于配置不符合过滤条件的操作 -->
    23             <onMismatch>DENY</onMismatch>
    24         </filter>
    25         <Encoding>UTF-8</Encoding>
    26         <File>${Log_Home}/info/info.log</File>
    27         <!-- 根据时间来制定滚动策略 -->
    28         <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
    29             <FileNamePattern>
    30                 ${Log_Home}/info/info.%d{yyyy-MM-dd}.%i.log
    31             </FileNamePattern>
    32             <!-- 多久后自动清楚旧的日志文件,单位:月 -->
    33             <MaxHistory>1</MaxHistory>
    34             <TimeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
    35                  <!-- 默认值是 10MB,文档最大值 -->
    36                 <MaxFileSize>2MB</MaxFileSize>
    37             </TimeBasedFileNamingAndTriggeringPolicy>
    38         </rollingPolicy>
    39         
    40         <encoder>
    41             <Pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{50} - %msg%n</Pattern>
    42         </encoder>
    43     </appender>
    44     
    45     <!-- ch.qos.logback.core.ConsoleAppender 控制台输出 -->
    46     <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    47         <encoder>
    48             <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符 -->
    49             <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{50} - %msg%n</pattern>
    50         </encoder>
    51     </appender>
    52 
    53     <!-- 控制java下面包的打印,没设置等级,将继承上级root的等级 -->
    54     <logger name="com.test"/>
    55 
    56     <!-- 当前日志总级别为TRACE、DEBUG、INFO、 WARN、ERROR、ALL和 OF -->
    57     <!-- the level of the root level is set to DEBUG by default.       -->
    58     <root level="DEBUG">
    59         <appender-ref ref="STDOUT" />
    60         <appender-ref ref="FILE_INFO" />
    61     </root>
    62 </configuration>
    logback.xml
    • 运行测试类Test.java的main方法,控制台输出如下
     1 20:35:23,708 |-INFO in ch.qos.logback.classic.LoggerContext[test] - Could NOT find resource [logback.groovy]
     2 20:35:23,709 |-INFO in ch.qos.logback.classic.LoggerContext[test] - Could NOT find resource [logback-test.xml]
     3 20:35:23,709 |-INFO in ch.qos.logback.classic.LoggerContext[test] - Found resource [logback.xml] at [file:/D:/workspace/test-logback/target/classes/logback.xml]
     4 20:35:23,751 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - debug attribute not set
     5 20:35:23,753 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - Setting ReconfigureOnChangeFilter scanning period to 30 seconds
     6 20:35:23,753 |-INFO in ReconfigureOnChangeFilter{invocationCounter=0} - Will scan for changes in [[D:workspace	est-logback	argetclasseslogback.xml]] every 30 seconds. 
     7 20:35:23,753 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - Adding ReconfigureOnChangeFilter as a turbo filter
     8 20:35:23,759 |-INFO in ch.qos.logback.classic.joran.action.ContextNameAction - Setting logger context name as [test]
     9 20:35:23,760 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.rolling.RollingFileAppender]
    10 20:35:23,763 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [FILE_INFO]
    11 20:35:23,783 |-ERROR in ch.qos.logback.core.joran.spi.Interpreter@25:13 - no applicable action for [Encoding], current pattern is [[configuration][appender][Encoding]]
    12 20:35:23,819 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - No compression will be used
    13 20:35:23,820 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - Will use the pattern D:/logs/test/info/info.%d{yyyy-MM-dd}.%i.log for the active file
    14 20:35:23,822 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@5599682f - The date pattern is 'yyyy-MM-dd' from file name pattern 'D:/logs/test/info/info.%d{yyyy-MM-dd}.%i.log'.
    15 20:35:23,822 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@5599682f - Roll-over at midnight.
    16 20:35:23,824 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@5599682f - Setting initial period to Wed Jul 13 20:05:58 CST 2016
    17 20:35:23,825 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
    18 20:35:23,837 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[FILE_INFO] - Active log file name: D:/logs/test/info/info.log
    19 20:35:23,837 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[FILE_INFO] - File property is set to [D:/logs/test/info/info.log]
    20 20:35:23,838 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.ConsoleAppender]
    21 20:35:23,839 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [STDOUT]
    22 20:35:23,840 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
    23 20:35:23,841 |-INFO in ch.qos.logback.classic.joran.action.RootLoggerAction - Setting level of ROOT logger to DEBUG
    24 20:35:23,841 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [STDOUT] to Logger[ROOT]
    25 20:35:23,841 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [FILE_INFO] to Logger[ROOT]
    26 20:35:23,842 |-INFO in ch.qos.logback.classic.joran.JoranConfigurator@4a871190 - Registering current configuration as safe fallback point
    27 
    28 2016-07-13 20:35:23 [main] DEBUG com.test.Test - 现在的时间是 Wed Jul 13 20:35:23 CST 2016
    29 2016-07-13 20:35:23 [main] INFO  com.test.Test -  This time is Wed Jul 13 20:35:23 CST 2016
    30 2016-07-13 20:35:23 [main] WARN  com.test.Test -  This time is Wed Jul 13 20:35:23 CST 2016
    31 2016-07-13 20:35:23 [main] ERROR com.test.Test -  This time is Wed Jul 13 20:35:23 CST 2016
    console.txt

      外部输出的日志文件如下:

      

      info.log的内容:

      

      

  • 相关阅读:
    [分治FFT]「CTSC2018」青蕈领主
    [边分治+线段树合并]「CTSC2018」暴力写挂
    [模板]MTT
    [模板]NTT
    [矩阵求逆+二分图匹配]BZOJ 3168 [Heoi2013]钙铁锌硒维生素
    [BZOJ1925][SDOI2010]地精部落(DP)
    [BZOJ1047][HAOI2007]理想的正方形(RMQ+DP)
    [POJ3630]Phone List (Tire)
    [POJ1193][NOI1999]内存分配(链表+模拟)
    [POJ2823]Sliding Window 滑动窗口(单调队列)
  • 原文地址:https://www.cnblogs.com/h--d/p/5668152.html
Copyright © 2011-2022 走看看