logback use


1. Introduction to logback
   Logback is another open source log component designed by the founder of log4j, the official website: http://logback.qos.ch. It is currently divided into the following modules:
  logback-core: the basic module of the other two modules
  logback-classic: it is an improved version of log4j, and it fully implements the slf4j API so that you can easily change to other logging systems Such as log4j or JDK14 Logging
  logback-access: The access module integrates with the servlet container to provide the function of accessing logs through Http

2. Reasons for logback to replace log4j:
   1. Faster implementation: The core of Logback has been rewritten, and the performance has been improved by more than 10 times on some key execution paths. And logback not only has improved performance, but also has smaller initial memory loads.
  2. Very well tested: Logback has been tested for several years and countless hours. Logback's testing is on a completely different level.
  3. Logback-classic implements SLF4j very naturally: Logback-classic implements SLF4j. You don't feel logback-classic in using SLF4j. And because logback-classic implements slf4j very naturally, it is very easy to switch to log4j or other, just need to provide another jar package and it is OK, and there is no need to touch the code implemented by SLF4JAPI.
  4. Very adequate documentation The official website has more than 200 pages of documentation.
  5. Automatically reload the configuration file. When the configuration file is modified, Logback-classic can automatically reload the configuration file. The scanning process is fast and safe, and it does not need to create an additional scanning thread. This technology fully guarantees that the application can run very happily in the JEE environment.
  6. Lilith is an observer of log events, similar to the chainsaw of log4j. And lilith can also handle large amounts of log data.
  7. Prudent mode and very friendly recovery, in prudent mode, multiple FileAppender instances running under multiple JVMs can safely write the same log file. RollingFileAppender will have some limitations. Logback's FileAppender and its subclasses including RollingFileAppender are very friendly to recover from I/O exceptions.
  8. Configuration files can handle different situations, and developers often need to judge different Logback configuration files in different environments (development, testing, production). And these configuration files only have some small differences, which can be achieved by , and , so that a configuration file can adapt to multiple environments.
  9, Filters (filters) Sometimes, a problem needs to be diagnosed and a log needs to be printed. In log4j, you can only lower the log level, but this will generate a lot of logs, which will affect application performance. In Logback, you can continue to maintain that log level and get rid of some special cases, such as the user alice logged in, her log will be printed at the DEBUG level and other users can continue to hit the WARN level. To achieve this function only need to add 4 lines of XML configuration. Can refer to MDCFIlter.
  10. SiftingAppender (a very versatile Appender): It can be used to split log files according to any given run parameters. For example, SiftingAppender can distinguish log events to follow up the user's Session, and then each user will have a log file.
  11. Automatically compress the logs that have been typed out: RollingFileAppender will automatically compress the log files that have been typed out when a new file is generated. Compression is an asynchronous process, so even for large log files, the application will not suffer during the compression process.
  12. Stack tree with package version: Logback will bring the package data when it prints the stack tree log.
  13. Automatically remove old log files: By setting the maxHistory property of TimeBasedRollingPolicy or SizeAndTimeBasedFNATP, you can control the maximum number of log files that have been generated. If you set maxHistory 12, those log files older than 12 months will be automatically removed.

3. Introduction to the configuration of logback
   1. Logger, appender and layout
Logger are used as log recorders. After they are associated with the corresponding context of the application, they are mainly used to store log objects, and log types and levels can also be defined.
Appender is mainly used to specify the destination of log output, the destination can be console, file, remote socket server, MySQL, PostreSQL, Oracle and other databases, JMS and remote UNIX Syslog daemons, etc.
Layout is responsible for converting events into strings and outputting formatted log messages.
  2. logger context
Each logger is associated with a LoggerContext, which is responsible for creating loggers and arranging loggers in a tree structure. All other loggers are also obtained through the static method getLogger of the org.slf4j.LoggerFactory class. The getLogger method takes the logger name as a parameter. Calling the LoggerFactory.getLogger method with the same name will always return a reference to the same logger object.
  3. Valid levels and level inheritance
Loggers can be assigned levels. Levels include: TRACE, DEBUG, INFO, WARN and ERROR, defined in the ch.qos.logback.classic.Level class. If the logger is not assigned a level, then it will inherit the level from the nearest ancestor that has an assigned level. The root logger default level is DEBUG.
  4. Printing method and basic selection rules
The print method determines the level of logging requests. For example, if L is a logger instance, then the statement L.info("..") is a logging statement with level INFO. A logging request is said to be enabled at a level higher than or equal to the effective level of its logger, and disabled otherwise. The logging request level is p, the effective level of its logger is q, and the request will be executed only when p>=q.
This rule is the core of logback. The order of levels is: TRACE < DEBUG < INFO < WARN < ERROR

Fourth, the default configuration of logback
If the configuration files logback-test.xml and logback.xml do not exist, then logback will call BasicConfigurator by default to create a minimal configuration. The minimal configuration consists of a ConsoleAppender associated with the root logger. The output is formatted with a PatternLayoutEncoder with the pattern %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n. The root logger default level is DEBUG.
  1.
Logback configuration file The syntax of the Logback configuration file is very flexible. Because of its flexibility, it cannot be defined with a DTD or XML schema. Nonetheless, the basic structure of a configuration file can be described as follows: it begins with <configuration>, followed by zero or more <appender> elements, zero or more <logger> elements, and at most one <root> element.
  2. Steps of the default configuration of Logback
    (1). Try to find the file logback-test.xml under the classpath;
    (2). If the file does not exist, look for the file logback.xml;
    (3). If both files do not exist, logback uses BasicConfigurator to automatically configure itself, which will cause logging to be output to the console.

5. Detailed explanation of common configuration of logback.xml

 

  1. The root node <configuration> contains the following three attributes:
    scan: When this attribute is set to true, if the configuration file is changed, it will be reloaded. The default value is true.
    scanPeriod: Set the time interval for monitoring whether the configuration file is modified. If no time unit is given, the default unit is milliseconds. This property takes effect when scan is true. The default time interval is 1 minute.
    debug: When this property is set to true, the internal log information of logback will be printed out, and the running status of logback will be viewed in real time. The default value is false.
  E.g

<configuration scan="true" scanPeriod="60 seconds" debug="false"> 
      <!--其他配置省略--> 
</configuration>

2. Child node <contextName>: used to set the context name, each logger is associated with the logger context, and the default context name is default. But you can use <contextName> to set other names to distinguish records from different applications. Once set, it cannot be modified.
  E.g:

<configuration scan="true" scanPeriod="60 seconds" debug="false"> 
      <contextName>myAppName</contextName> 
      <!--其他配置省略-->
</configuration>

3. The child node <property>: used to define the variable value. It has two attributes, name and value. The value defined by <property> will be inserted into the logger context, and you can use "${}" to use the variable.
    name: the name of the variable
    value: the value of the variable definition value
  For example:

<configuration scan="true" scanPeriod="60 seconds" debug="false"> 
      <property name="APP_Name" value="myAppName" /> 
      <contextName>${APP_Name}</contextName> 
      <!--其他配置省略--> 
</configuration>    

4. Child node <timestamp>: Get the timestamp string, it has two attributes key and datePattern
    key: identify the name of this <timestamp>;
    datePattern: set the current time (the time to parse the configuration file) into a string Pattern, following the format of java.txt.SimpleDateFormat.
  E.g:

<configuration scan="true" scanPeriod="60 seconds" debug="false"> 
      <timestamp key="bySecond" datePattern="yyyyMMdd'T'HHmmss"/> 
      <contextName>${bySecond}</contextName> 
      <!-- 其他配置省略--> 
</configuration>

5. Child node <appender>: The component responsible for writing logs, it has two necessary attributes name and class. name specifies the name of the appender, class specifies the fully qualified name of the appender
    5.1, ConsoleAppender outputs the log to the console, and has the following sub-nodes:
      <encoder>: Format the log. (The specific parameters will be explained later)
      <target>: String System.out (default) or System.err (not much difference)
    For example:

<configuration> 
      <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> 
      <encoder> 
        <pattern>%-4relative [%thread] %-5level %logger{35} - %msg %n</pattern> 
      </encoder> 
      </appender> 

      <root level="DEBUG"> 
        <appender-ref ref="STDOUT" /> 
      </root> 
</configuration>

The above configuration means that all logs >=DEBUG level are output to the console

    5.2. FileAppender: Add the log to the file, with the following sub-nodes:
      <file>: The name of the file to be written, which can be a relative directory or an absolute directory. If the upper-level directory does not exist, it will be automatically created, and there is no default value.
      <append>: If true, the log is appended to the end of the file, if false, the existing file is emptied, the default is true.
      <encoder>: Formats logging events. (The specific parameters will be explained later)
      <prudent>: If it is true, the log will be safely written to the file, even if other FileAppenders are writing to this file, which is inefficient, and the default is false.
    E.g:

<configuration> 
      <appender name="FILE" class="ch.qos.logback.core.FileAppender"> 
        <file>testFile.log</file> 
        <append>true</append> 
        <encoder> 
          <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern> 
        </encoder> 
      </appender> 

      <root level="DEBUG"> 
      <appender-ref ref="FILE" /> 
      </root> 
</configuration>

The above configuration means that all logs >=DEBUG level are output to testFile.log

    5.3, RollingFileAppender: Rolling record files, first record the log to the specified file, when a certain condition is met, record the log to other files. It has the following subnodes:
      <file>: The name of the file to be written, which can be a relative directory or an absolute directory. If the upper-level directory does not exist, it will be automatically created, and there is no default value.
      <append>: If true, the log is appended to the end of the file, if false, the existing file is emptied, the default is true.
      <rollingPolicy>: Determines the behavior of RollingFileAppender when rolling occurs, involving file movement and renaming. The attribute class defines the specific rolling policy class
      class=”ch.qos.logback.core.rolling.TimeBasedRollingPolicy”: The most commonly used rolling policy, it formulates the rolling policy according to the time, which is responsible for both rolling and starting rolling. It has the following sub-nodes:
        <fileNamePattern>: necessary node, including the file name and "%d" converter, "%d" can contain a time format specified by java.text.SimpleDateFormat, such as: %d{yyyy-MM}.
If you use %d directly, the default format is yyyy-MM-dd. The file byte point of RollingFileAppender is optional. By setting file, you can specify different locations for active files and archived files. The current log is always recorded to the file specified by file (active file), and the name of the active file will not change;
if If file is not set, the name of the active file will be changed every so often according to the value of fileNamePattern. "/" or "\" are used as directory separators.
        <maxHistory>:
An optional node that controls the maximum number of archived files to keep, before deleting old files. Assuming that the setting is rolled every month, and <maxHistory> is 6, only the files of the last 6 months are saved, and the old files before are deleted. Note that when deleting old files, those directories created for archiving are also deleted.

      class=”ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy”: View the size of the current active file, if it exceeds the specified size, it will tell RollingFileAppender to trigger the rolling of the current active file. There is only one node:
        <maxFileSize>: This is the size of the active file, the default is 10MB.
        <prudent>: When true, FixedWindowRollingPolicy is not supported. TimeBasedRollingPolicy is supported, but there are two restrictions, 1 does not support and does not allow file compression, 2 cannot set the file attribute and must be left blank.

      <triggeringPolicy>: Tells the RollingFileAppender to properly activate scrolling.
      class=”ch.qos.logback.core.rolling.FixedWindowRollingPolicy” Rolling policy to rename files according to the fixed window algorithm. It has the following sub-nodes:
        <minIndex>: the minimum value of the window index
        <maxIndex>: the maximum value of the window index, when the window specified by the user is too large, the window will be automatically set to 12.
        <fileNamePattern>: must contain "%i" For example, assuming the minimum and maximum values ​​are 1 and 2, respectively, and the naming pattern is mylog%i.log, the archive files mylog1.log and mylog2.log will be generated. File compression options can also be specified, e.g. mylog%i.log.gz or no log%i.log.zip
      e.g.:

<configuration> 
          <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> 
            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> 
              <fileNamePattern>logFile.%d{yyyy-MM-dd}.log</fileNamePattern> 
              <maxHistory>30</maxHistory> 
            </rollingPolicy> 
            <encoder> 
              <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern> 
            </encoder> 
          </appender> 

          <root level="DEBUG"> 
            <appender-ref ref="FILE" /> 
          </root> 
</configuration>

The above configuration means that a log file is generated every day and the log file is saved for 30 days.

<configuration> 
          <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> 
            <file>test.log</file> 

            <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> 
              <fileNamePattern>tests.%i.log.zip</fileNamePattern> 
              <minIndex>1</minIndex> 
              <maxIndex>3</maxIndex> 
            </rollingPolicy> 

            <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> 
              <maxFileSize>5MB</maxFileSize> 
            </triggeringPolicy> 
            <encoder> 
              <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern> 
            </encoder> 
          </appender> 

          <root level="DEBUG"> 
            <appender-ref ref="FILE" /> 
          </root> 
</configuration>

The above configuration indicates that the log file is generated according to the fixed window mode. When the file is larger than 20MB, a new log file is generated. The window size is 1 to 3, and when 3 archives are saved, the oldest log will be overwritten.
      <encoder>: Formats logging events. Responsible for two things, one is to convert the log information into a byte array, and the other is to write the byte array to the output stream.
PatternLayoutEncoder is the only useful and default encoder that has a <pattern> node that sets the input format of the log. Use "%" plus "converter" method, if you want to output "%", you must use "\" to escape "\%".
    5.4, ​​there are also SocketAppender, SMTPAppender, DBAppender, SyslogAppender, SiftingAppender, which are not commonly used and will not be explained in detail here.
You can refer to the official documentation ( http://logback.qos.ch/documentation.html ), and you can also write your own Appender.
  6. Subnode <loger>: used to set the log printing level of a package or a specific class, and specify <appender>. <loger> has only a name attribute, an optional level and an optional addtivity attribute.
Can contain zero or more <appender-ref> elements, identifying the appender will be added to the logger
    name: Used to specify a package or a specific class constrained by this logger.
    level: used to set the print level, case-insensitive: TRACE, DEBUG, INFO, WARN, ERROR, ALL and OFF, and a special value INHERITED or the synonym NULL, which represents the level of forcing the execution of the superior. If this property is not set, the current logger will inherit the level of the superior.
addtivity: Whether to pass printing information to the superior loger. Default is true. Like <loger>, can contain zero or more <appender-ref> elements, identifying the appender to which this logger will be added.
  7. Child node <root>: It is also a <loger> element, but it is the root loger and is the superior of all <loger>. There is only one level attribute, because the name has been named "root" and is already the top level.
    level: used to set the print level, case-insensitive: TRACE, DEBUG, INFO, WARN, ERROR, ALL and OFF, cannot be set to INHERITED or the synonym NULL. Default is DEBUG.
Six, commonly used loger configuration


<!-- show parameters for hibernate sql 专为 Hibernate 定制 -->
<logger name="org.hibernate.type.descriptor.sql.BasicBinder" level="TRACE" />
<logger name="org.hibernate.type.descriptor.sql.BasicExtractor" level="DEBUG" />
<logger name="org.hibernate.SQL" level="DEBUG" />
<logger name="org.hibernate.engine.QueryParameters" level="DEBUG" />
<logger name="org.hibernate.engine.query.HQLQueryPlan" level="DEBUG" />

<!--myibatis log configure-->
<logger name="com.apache.ibatis" level="TRACE"/>
<logger name="java.sql.Connection" level="DEBUG"/>
<logger name="java.sql.Statement" level="DEBUG"/>
<logger name="java.sql.PreparedStatement" level="DEBUG"/>

7. Demo
  1. Add dependency packages Logback needs to be used together with slf4j, so the total packages that need to be added are slf4j-api.
Logback needs to be used together with slf4j, so the total packages that need to be added are slf4j-api.jar, logback -core.jar, logback-classic.jar, logback-access.jar are temporarily unavailable so no dependencies are added, maven configuration

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <logback.version>1.1.7</logback.version>
    <slf4j.version>1.7.21</slf4j.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-core</artifactId>
      <version>${logback.version}</version>
    </dependency>
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>${logback.version}</version>
      </dependency>
  </dependencies>

2. logback.xml configuration

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
    <!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径 -->
    <property name="LOG_HOME" value="/home" />
    <!-- 控制台输出 -->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符 -->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} -
                %msg%n</pattern>
        </encoder>
    </appender>
    <!-- 按照每天生成日志文件 -->
    <appender name="FILE"
        class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--日志文件输出的文件名 -->
            <FileNamePattern>${LOG_HOME}/TestWeb.log.%d{yyyy-MM-dd}.log</FileNamePattern>
            <!--日志文件保留天数 -->
            <MaxHistory>30</MaxHistory>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符 -->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} -
                %msg%n</pattern>
        </encoder>
        <!--日志文件最大的大小 -->
        <triggeringPolicy
            class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <MaxFileSize>10MB</MaxFileSize>
        </triggeringPolicy>
    </appender>

    <!-- 日志输出级别 -->
    <root level="INFO">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>

3. java code

 /**
  * Hello world!
  */
  public class App {

  private final static Logger logger = LoggerFactory.getLogger(App.class);

    public static void main(String[] args) {
      logger.info("logback 成功了");
      logger.error("logback 成功了");
      logger.debug("logback 成功了");
    }
  }

4. Output
  

8. Summary

For the configuration of logback, you need to configure the output source appender, the loger (child node) and root (root node) of the log. In fact, its output log starts from the child node. If the child node has an output source, input directly, if not, judge Whether the configured addtivity is passed like the superior, that is, whether it is passed to the root, the pass uses the output source of the root, otherwise the log is not output.

Reprinted from: http://www.cnblogs.com/warking/p/5710303.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325935024&siteId=291194637