logback log4j and comparison, the former is improved, logback configuration in detail (rpm)

A, logback introduction
  Logback is another open source log4j log component by the founder of the design, the official website: http://logback.qos.ch. It is currently divided into the following modules Next:
  logback-Core: the other two modules of the basic module
  logback-classic: it is a modified version of log4j, but it is a complete implementation of the slf4j API so that you can easily replace the log into other systems logging or log4j as jdk14
  the logback-access: access module and Servlet containers provides integrated access to the log by Http

Second, the reason logback replace log4j:
  1, faster realization: Logback kernel rewrite on some key performance execution path more than 10 times. And logback not only improves performance, but also initialize memory to load even smaller.
  2, very well tested: Logback After a few years, countless hours of testing. Logback test a completely different level.
  3, Logback-classic achieve a very natural SLF4j: Logback-classic realized SLF4j. SLF4j in use, you will not feel logback-classic. And because logback-classic SLF4J achieved very natural, so log4j or switch to another very easily, need only provide the packet to another jar on OK, the code that do not need to move through SLF4JAPI achieved.
  4, very full document official website has 200 pages of documents.
  5, automatically re-load the configuration file when the configuration file is modified, Logback-classic automatically reload the configuration file. Fast and secure scanning process, it does not need to create a scan thread. The technology to ensure the application can run in JEE environment very happy inside.
  6, Lilith is an observer log events, and chainsaw log4j similar. The lilith can handle a large amount of log data.
  7, discreet and very friendly mode of recovery, in a cautious mode, multiple instances FileAppender run under multiple JVM, can write the same log file safely. RollingFileAppender be some restrictions. The FileAppender Logback and its subclasses include RollingFileAppender can be very friendly recovery from I / O exception.
  8, the configuration files can handle different situations, different developers often need to determine the profile of Logback in different environments (development, test, production). These profiles with only few minor differences, you can, and to achieve such a profile can adapt to multiple environments.
  9, Filters (filter) There are times when you need to diagnose a problem and needs to play log. In log4j, logging only the lower level, but it will play a large number of logs, will affect application performance. In Logback, you can continue to maintain the log level and get rid of some special circumstances, such as alice the user logs in, she will hit the DEBUG log level and other users can continue to play at the WARN level. To achieve this just add 4 lines of XML configuration. You can refer MDCFIlter.
  10, SiftingAppender (a very versatile Appender): it can be used to split a log file of any given operating parameters. Such as, SiftingAppender able to distinguish log events follow a user's Session, then each user will have a log file.
  11, automatic compression has been playing out of log: RollingFileAppender when a new file is automatically compressed been playing out of log files. Compression is an asynchronous process, so even for large log files during compression applications will not be affected.
  12, the tree with the stack package Version: Logback tree log stack when played, will bring the package.
  13, automatically remove old log files: by setting TimeBasedRollingPolicy or SizeAndTimeBasedFNATP of maxHistory property, you can control the maximum number of log files has been generated. If maxHistory 12, that those log files more than 12 months will be automatically removed.

Three, describes the configuration of the logback
  1, Logger, appender and layout
after logging recorder as Logger, it associates to a corresponding context applications, mainly for storage of log objects can also be defined log type, level.
Appender mainly used to specify the destination of log output destination can be a console, a file, a remote socket server, MySQL, PostreSQL, Oracle and other databases, JMS, and remote UNIX Syslog daemons. 
Layout is responsible for converting the event into a string, formatted output log information.
  2, logger context
each are associated with a logger LoggerContext, LoggerContext responsible for manufacturing logger, a tree structure is also responsible for the arrangement of each logger. All other logger also getLogger achieved by static method org.slf4j.LoggerFactory class. getLogger method name as a parameter to the logger. The same method name to call LoggerFactory.getLogger obtained always refer to the same logger object.
  3, effective level and the level of inheritance
Logger can be assigned level. Levels include: TRACE, DEBUG, INFO, WARN, and ERROR, ch.qos.logback.classic.Level defined in the class. If the logger is not assigned level, then it inherits from level has been assigned level of recent ancestors. The default is the root logger level DEBUG.
  4, the basic printing method selection rule
Print method determines the level recorded request. For example, if L is a logger instance, then the statement L.info ( "..") is a statement record level INFO. Request to record levels in higher than or equal to the effective level of its logger are called to be enabled, otherwise known as disabled. Recording request level p, that the effective level logger is q, then only if p> = time q, the request will be executed.
The rule is at the heart of logback. Level sorting is: TRACE <DEBUG <INFO <WARN <ERROR

Fourth, the default configuration of logback
If the configuration file logback-test.xml and logback.xml do not exist, then the default logback calls BasicConfigurator, create a minimal configuration. ConsoleAppender a minimal configuration by the associated root logger composition. The output mode is the% d {HH: mm: ss.SSS } [% thread]% -5level% logger {36} -% msg% n of PatternLayoutEncoder format. The default is the root logger level DEBUG.
  1, Logback configuration file
syntax Logback configuration file is very flexible. Because of the flexibility, it can not be defined with a DTD or XML schema. Nevertheless, the basic structure can be described as the configuration file: start with <configuration>, behind the zero or more <appender> element, zero or more <logger> element, up to a <root> element.
  2, Logback default configuration steps
    (1) to try to find the file in logback-test.xml CLASSPATH;.
    (2).
    (3) If neither of these files exist, logback automatically configure itself with BasicConfigurator, which will lead to record output to the console.

Five, logback.xml common configuration in detail

 

  1, the root <configuration>, comprising the following three attributes:
    Scan: When this property is set to true, if the profile change, will be reloaded, the default value is true.
    scanPeriod: Set if there are modified profiles monitoring interval, if the time unit is not given, the default milliseconds. When the scan is true, this property take effect. The default interval is 1 minute.
    debug: When this property is set to true, will print logback internal log information, real-time view logback running. The default value is false.
  For example:
    <Configuration = Scan "to true" scanPeriod = "60 seconds The" Debug = "to false"> 
      <- - other configurations will be omitted!> 
    </ Configuration>
  2, the child node <contextName>: used to set the context name, each a logger is associated to the logger context, the default context name for the default. May be used <contextName> Other names provided for recording distinguishing different applications. Once set, you can not be modified.
  For example:
    <Configuration = Scan "to true" scanPeriod = "60 seconds The" Debug = "to false"> 
      <contextName can> myAppName </ contextName can> 
      <!

  3, the child node <property>: used to define the value of a variable, it has two properties name and value, are inserted into the context of a value logger <property> defined, can be made "$ {}" to use variables.
    name: name of the variable
    value: the value of a variable defined value
  , for example:
    <Configuration Scan = "to true" scanPeriod = "60 seconds The" Debug = "to false"> 
      <Property name = "app_name" value = "myAppName" /> 
      < contextName can> $ {app_name} </ contextName can> 
      <- other configurations will be omitted ->! 
    </ configuration>
  . 4, the child node <timestamp>: Get timestamp string, and he has two key attributes The datePattern
    key: this identifier <timestamp> name;
    the datePattern: set the current time (time resolved profile) is converted to the pattern string, followed java.txt.SimpleDateFormat format.
  For example:
    <Configuration = Scan "to true" scanPeriod = "60 seconds The" Debug = " 

      <contextName can> bySecond $ {} </ contextName can> 
      <- - other configurations will be omitted!> 
    </ Configuration>
  . 5, the child node <appender>: component responsible for writing the log, it is necessary to have two attributes name and class. appender name specifies the name, class specify the fully qualified name of the appender
    5.1, ConsoleAppender log output to the console, has the following child nodes:
      <Encoder>: log format. (Specific parameters explained later)
      <target>: the System.out string (default) or System.err (difference not say)
    example:
    <Configuration> 
      <the appender name = "STDOUT" class = "ch.qos.logback .core.ConsoleAppender "> 
      <Encoder> 
        <pattern>% - 4relative [Thread%]% {35} Logger -5level% -%% n-MSG </ pattern> 
      </ Encoder> 
      </ the appender> 

      <= the root Level" the DEBUG "> 


    </ configuration>
    above-described configuration represents the> = DEBUG level logs are output to the console

    5.2, FileAppender: to add to the log file, the following sub-node:
      <File>: is written to the file name, can be a relative directory, or an absolute directory, if the parent directory does not exist will be created automatically, with no default.
      <append>: If true, the log is appended to the end of the file, if it is false, empty the existing file, the default is true.
      <encoder>: to record the event format. (Specific parameters explain later)
      <Prudent>: If true, logs are written to the file safe, even if others are doing FileAppender to this file write operations are inefficient, the default is false.
    For example:
    <Configuration> 
      <the appender name = "the FILE" class = "ch.qos.logback.core.FileAppender"> 
        <File> testFile.log </ File> 
        <the append> to true </ the append> 
        <Encoder> 
          <pattern> -4relative% [Thread%]% {35} Logger -5level% -%% n-MSG </ pattern> 
        </ Encoder> 
      </ the appender> 

      < 

      </ the root> 
    </ Configuration>
    above-described configuration represents the> = DEBUG level logs are output to testFile.log

    5.3, RollingFileAppender: rolling log file, logging to the specified file first, when a condition matches, logging to other files. The following sub-node:
      <File>: file name is written can be relative directory, or an absolute directory, if the parent directory does not exist will be created automatically, with no default.
      <append>: If true, the log is appended to the end of the file, if it is false, empty the existing file, the default is true.
      <rollingPolicy>: When scrolling occurs, determine the behavior of RollingFileAppender, move and rename files involved. Specific property defines the scrolling policy class class
      class = "ch.qos.logback.core.rolling.TimeBasedRollingPolicy": The most commonly used strategy rolling, rolling it to develop strategies based on time, responsible for both the scroll is also responsible for starting the scroll. It has the following child nodes:
        <fileNamePattern>: necessary node contains the file name and "% d" conversion specifier, "% d" may comprise a java.text.SimpleDateFormat specified time format, such as:% d {yyyy-MM} .
If the direct use of% d, the default format is yyyy-MM-dd. RollingFileAppender the file byte point dispensable, by setting the file, you can specify a different location for active files and archive files, always record the current log file to the specified file (active document), the name of the active file does not change;
if not set file, the file name of the event will be based on the value fileNamePattern change every once in a while. "/" Or "\" will be treated as a directory separator.
        <maxHistory>:
Optional node, control the maximum number of reserved archive, delete old files exceeds the number. Assuming that the scrolling of each month, and <maxHistory> 6, only the last 6 months save files, old files before deleting. Note that deleting old files, those directories created for the archive will be deleted.

      class = "ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy": see the size of the current active file, if more than the specified size will inform RollingFileAppender trigger currently active document scrolling. Only one node:
        <maxFileSize>: This is the size of the active file, the default value is 10MB.
        <prudent>: When is true, it does not support FixedWindowRollingPolicy. Support TimeBasedRollingPolicy, but there are two restrictions, one does not support file compression is not allowed, 2 not set the file attributes, must be left blank.

      <triggeringPolicy>: RollingFileAppender inform appropriate activated scrolling.
      class = "ch.qos.logback.core.rolling.FixedWindowRollingPolicy" according to a fixed window algorithm rename the scroll policy file. Has the following child nodes:
        <minIndex>: window index Min
        <maxIndex>: maximum window index, when the user designates the window is too large, automatically the window is set to 12.
        <fileNamePattern>: must contain "% i" For example, assume that minimum and maximum values are 1 and 2, designated mode mylog% i.log, and will have the archive mylog1.log mylog2.log. You can also specify the file compression options, e.g., mylog% i.log.gz or not log% i.log.zip
      example:
        <Configuration> 
          <the appender name = "the FILE" class = "ch.qos.logback.core.rolling. the RollingFileAppender "> 
            <rollingPolicy class =" ch.qos.logback.core.rolling.TimeBasedRollingPolicy "> 
              <fileNamePattern> the logFile.% D-YYYY {} .log the MM-dd </ fileNamePattern> 
              <maxHistory> 30 </ maxHistory> 
            < / rollingPolicy> 
            <Encoder> 
              <pattern>% - 4relative [Thread%]% {35} Logger -5level% -%% n-MSG </ pattern> 
            </ Encoder> 



            <REF-REF = the appender "the FILE" /> 
          </ the root> 
        </ Configuration>
        above configuration representation generator daily log file, the log file for 30 days.
        <Configuration> 
          <the appender name = "the FILE" class = "ch.qos.logback.core.rolling.RollingFileAppender"> 
            <File> the 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. 

            </ triggeringPolicy> 
            <Encoder> 
              <pattern>% - 4relative [Thread%]% {35} Logger -5level% -%% n-MSG </ pattern> 
            </ Encoder> 
          </ the appender> 

          <= the root Level "the DEBUG"> 
            <REF-REF = the appender "the fILE" /> 
          </ the root> 
        </ configuration>
        above configuration log file is generated showing a fixed window mode, when the file is greater than 20MB, generates a new log file. The window size is 1-3, after saving three archive will overwrite the oldest log.
      <encoder>: to record the event format. Responsible for two things, one is to convert the log information into a byte array, the second is the array of bytes written to the output stream.
PatternLayoutEncoder is the only useful and default Encoder, a <pattern> node, to set the input format of the log. Use "%" plus "conversion specifier" mode, if the output of "%", must be used "\" to "\%" escape.
    5.
We can refer to the official documentation (http://logback.qos.ch/documentation.html), you can also write your own Appender.
  6, the child node <loger>: to set the logging level to print one specific packet or a certain class, and designated <appender>. <loger> only a name attribute, an optional level addtivity and an optional attribute.
It may comprise zero or more <appender-ref> element, the identification will be added to the appender Loger
    name: for a certain packet or a specific constraint Loger one specified by this class.
    level: the level used to set the print, case insensitive: TRACE, DEBUG, INFO, WARN , ERROR, ALL and OFF, there is a Japanese popular value INHERITED synonyms or NULL, on behalf of the higher level of enforcement. If this property is not set, then the current level loger will inherit superiors.
addtivity: whether to pass information to their superiors print loger. The default is true. With <loger> like can contain zero or more <appender-ref> element, the identification will be added to the appender loger.
  7, the child node <root>: It is also <loger> element, but it is the root Loger, all <loger> superior. Only one level property, because name has been named "root", and is already the most superior.
    level: the level used to set the print, case insensitive: TRACE, DEBUG, INFO, WARN , ERROR, ALL and OFF, or can not be set INHERITED synonymous NULL. The default is DEBUG.
Six, common configuration loger
<!-- 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 = "the TRACE" />
<name = Logger "the java.sql.Connection" Level = "the DEBUG" />
<name = Logger "the java.sql.Statement" Level = "the DEBUG" />
<name = Logger "java.sql.PreparedStatement" Level = "the DEBUG" />
seven, Demo
  . 1, add dependencies logback designed for use with and used slf4j, so the total you need to add the dependent packages have API-slf4j
logback need and use slf4j used together, so you need to add a total of dependent packages have slf4j-api.jar, logback-core.jar, logback-classic.jar, logback-access.jar this temporary it is not less than a dependency added, maven configuration
  <Properties>
    <project.build.sourceEncoding>. 8 UTF-</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 "to false">
<-! Storage address defined in LogBack log files do not use a relative path configuration ->
<Property name = "LOG_HOME" value = "/ Home" />
<-! console output ->
<the appender name = "STDOUT" class = "ch.qos.logback.core.ConsoleAppender">
< class = Encoder "ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<- output format:!% d represents the date,% thread indicates that the thread name,% - 5level: level 5 show left character width% msg : log messages,% n newline ->
<pattern>% {D the mM-dd-YYYY HH: mm: ss.SSS} [Thread%]% {50} Logger -5level% -%% n-MSG </ pattern>
</ Encoder>
</ the appender>
<-! log files are generated per day according to the ->
<the appender name = "the fILE"class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<! - File name of the log file output ->
<FileNamePattern>} $ {LOG_HOME the MM-YYYY-/TestWeb.log.%d {dd} .log </ FileNamePattern>
<! - the number of days to keep log files - >
<MaxHistory> 30 </ MaxHistory>
</ rollingPolicy>
<Encoder class = "ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<- output format:!% d represents the date,% thread indicates that the thread name, % -5level: level 5 show left character width% msg: log messages,% n newline ->
<pattern>% {D the mM-dd-YYYY HH: mm: ss.SSS} [Thread%]% {50}% Logger -5level -% n-MSG% </ pattern>
</ Encoder>
<-! maximum size of the log file ->
<triggeringPolicy class = "ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<the MaxFileSize> 10MB </ the MaxFileSize>
</ triggeringPolicy>
</ the appender>

<! - log output level ->
<= the root Level "the INFO">
<REF-REF = the appender "STDOUT" />
</ the root>
</ Configuration>

  3, java codes
  / **
  * the Hello World!
  * /
  Public class the App {

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

    static void main public (String [] args) {
      logger.info ( "the logback successfully");
      logger.error ( "the logback successfully");
      logger.debug ( "the logback successfully");
    }
  }
  4, the output
  

Eight, summary

logback configuration, the appender need to configure the output source, play log Loger (child nodes) and the root (root), in fact, it is the beginning of the log output from a child node, the child node if the output is directly input source, if not, is determined configuration addtivity, if higher image transfer, i.e., whether transmitted to root, root pass output source is used, the log output or not.

Transfer: https: //blog.csdn.net/zbajie001/article/details/79596109

Guess you like

Origin www.cnblogs.com/muxi0407/p/11812787.html