logback笔记1

logback官网 https://logback.qos.ch/

Logback is intended as a successor to the popular log4j project, picking up where log4j leaves off.

At present time, logback is divided into three modules, logback-core, logback-classic and logback-access.

The logback-core module lays the groundwork for the other two modules. The logback-classic module can be assimilated to a significantly improved version of log4j. Moreover, logback-classic natively implements the SLF4J API so that you can readily switch back and forth between logback and other logging frameworks such as log4j or java.util.logging (JUL).

The logback-access module integrates with Servlet containers, such as Tomcat and Jetty, to provide HTTP-access log functionality. Note that you could easily build your own module on top of logback-core.

logback手册

第一章

First Baby Step

Requirements

Logback-classic module requires the presence of slf4j-api.jar and logback-core.jar in addition to logback-classic.jar on the classpath.

The logback-*.jar files are part of the logback distribution whereas slf4j-api-1.8.0-beta1.jar ships with SLF4J, a separate project.

Let us now begin experimenting with logback.

Example 1.1: Basic template for logging (logback-examples/src/main/java/chapters/introduction/HelloWorld1.java)
package chapters.introduction;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HelloWorld1 {

  public static void main(String[] args) {

    Logger logger = LoggerFactory.getLogger("chapters.introduction.HelloWorld1");
    logger.debug("Hello world.");

  }
}

HelloWorld1 class is defined in the chapters.introduction package. It starts by importing the Logger and LoggerFactoryclasses defined in the SLF4J API, specifically within the org.slf4j package.


Note that the above example does not reference any logback classes. In most cases, as far as logging is concerned, your classes will only need to import SLF4J classes. Thus, the vast majority, if not all, of your classes will use the SLF4J API and will be oblivious to the existence of logback.


Launching the HelloWorld1 application will output a single line on the console. By virtue of logback's default configuration policy, when no default configuration file is found, logback will add a ConsoleAppender to the root logger.

20:49:07.962 [main] DEBUG chapters.introduction.HelloWorld1 - Hello world.


Logback can report information about its internal state using a built-in status system. Important events occurring during logback's lifetime can be accessed through a component called StatusManager. For the time being, let us instruct logback to print its internal state by invoking the static print() method of the StatusPrinter class.

Example: Printing Logger Status (logback-examples/src/main/java/chapters/introduction/HelloWorld2.java)
package chapters.introduction;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.util.StatusPrinter;

public class HelloWorld2 {

  public static void main(String[] args) {
    Logger logger = LoggerFactory.getLogger("chapters.introduction.HelloWorld2");
    logger.debug("Hello world.");

    // print internal state
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    StatusPrinter.print(lc);
  }
}

Note that in case of errors, logback will automatically print its internal state on the console.

Note that in the above example we have instructed logback to print its internal state by invoking theStatusPrinter.print() method. Logback's internal status information can be very useful in diagnosing logback-related problems.

Here is a list of the three required steps in order to enable logging in your application.

  1. Configure the logback environment. You can do so in several more or less sophisticated ways. More on this later.
  2. In every class where you wish to perform logging, retrieve a Logger instance by invoking theorg.slf4j.LoggerFactory class' getLogger() method, passing the current class name or the class itself as a parameter.
  3. Use this logger instance by invoking its printing methods, namely the debug(), info(), warn() and error() methods. This will produce logging output on the configured appenders.

第2章

Logger, Appenders and Layouts

Logback is built upon three main classes: LoggerAppender and Layout. These three types of components work together to enable developers to log messages according to message type and level, and to control at runtime how these messages are formatted and where they are reported.

The Logger class is part of the logback-classic module. On the other hand, the Appender and Layout interfaces are part of logback-core. As a general-purpose module, logback-core has no notion of loggers.


package org.slf4j; 
public interface Logger {

  // Printing methods: 
  public void trace(String message);
  public void debug(String message);
  public void info(String message); 
  public void warn(String message); 
  public void error(String message); 
}

Effective Level aka Level Inheritance

Loggers may be assigned levels. The set of possible levels (TRACE, DEBUG, INFO, WARN and ERROR) are defined in the ch.qos.logback.classic.Level class. Note that in logback, the Level class is final and cannot be sub-classed, as a much more flexible approach exists in the form of Marker objects.

If a given logger is not assigned a level, then it inherits one from its closest ancestor with an assigned level. More formally:指定了的就按指定的来

The effective level for a given logger L, is equal to the first non-null level in its hierarchy, starting at Litself and proceeding upwards in the hierarchy towards the root logger.

To ensure that all loggers can eventually inherit a level, the root logger always has an assigned level. By default, this level is DEBUG.


Basic Selection Rule

A log request of level p issued to a logger having an effective level q, is enabled if p >= q.

This rule is at the heart of logback. It assumes that levels are ordered as follows: TRACE < DEBUG < INFO <  WARN < ERROR.

In logback speak, an output destination is called an appender. Currently, appenders exist for the console, files, remote socket servers, to MySQL, PostgreSQL, Oracle and other databases, JMS, and remote UNIX Syslog daemons.

More than one appender can be attached to a logger.

The rules governing appender additivity are summarized below.

Appender Additivity

The output of a log statement of logger L will go to all the appenders in L and its ancestors. This is the meaning of the term "appender additivity".

However, if an ancestor of logger L, say P, has the additivity flag set to false, then L's output will be directed to all the appenders in L and its ancestors up to and including P but not the appenders in any of the ancestors of P.

Loggers have their additivity flag set to true by default.

More often than not, users wish to customize not only the output destination but also the output format. This is accomplished by associating a layout with an appender. The layout is responsible for formatting the logging request according to the user's wishes, whereas an appender takes care of sending the formatted output to its destination. The PatternLayout, part of the standard logback distribution, lets the user specify the output format according to conversion patterns similar to the C language printf function.

For example, the PatternLayout with the conversion pattern "%-4relative [%thread] %-5level %logger{32} - %msg%n" will output something akin to:

176  [main] DEBUG manual.architecture.HelloWorld2 - Hello world.

The first field is the number of milliseconds elapsed since the start of the program. The second field is the thread making the log request. The third field is the level of the log request. The fourth field is the name of the logger associated with the log request. The text after the '-' is the message of the request.

用户调用记日志的方法后执行的流程
第3章

Let us begin by discussing the initialization steps that logback follows to try to configure itself:

  1. Logback tries to find a file called logback-test.xml in the classpath.

  2. If no such file is found, logback tries to find a file called logback.groovy in the classpath.

  3. If no such file is found, it checks for the file logback.xml in the classpath..

  4. If no such file is found, service-provider loading facility (introduced in JDK 1.6) is used to resolve the implementation of com.qos.logback.classic.spi.Configurator interface by looking up the file META-INF\services\ch.qos.logback.classic.spi.Configurator in the class path. Its contents should specify the fully qualified class name of the desired Configurator implementation.

  5. If none of the above succeeds, logback configures itself automatically using the BasicConfigurator which will cause logging output to be directed to the console.

If you are using Maven and if you place the logback-test.xml under the src/test/resources folder, Maven will ensure that it won't be included in the artifact produced. Thus, you can use a different configuration file, namely logback-test.xml during testing, and another file, namely, logback.xml, in production.

Enabling output of status data, either via the debug attribute or equivalently by installing OnConsoleStatusListener, will go a long way in helping you diagnose logback issues. As such, enabling logback status data is very highly recommended and should be considered as a recourse of first resort.


If instructed to do so, logback-classic will scan for changes in its configuration file and automatically reconfigure itself when the configuration file changes. In order to instruct logback-classic to scan for changes in its configuration file and to automatically re-configure itself set the scan attribute of the  element to true, as shown next.

Example: Scanning for changes in configuration file and automatic re-configuration (logback-examples/src/main/resources/chapters/configuration/scan1.xml)

View as .groovy
 scan="true"> 
  ... 
 

By default, the configuration file will be scanned for changes once every minute. You can specify a different scanning period by setting the scanPeriod attribute of the  element. Values can be specified in units of milliseconds, seconds, minutes or hours. Here is an example:

Example: Specifying a different scanning period (logback-examples/src/main/resources/chapters/configuration/scan2.xml)

View as .groovy
 scan="true" scanPeriod="30 seconds" > 
  ...
 

 

在网络应用中停止logback-classic并释放资源的方法。

Nevertheless, the very basic structure of the configuration file can be described as,  element, containing zero or more  elements, followed by zero or more  elements, followed by at most one  element. The following diagram illustrates this basic structure.

logback笔记1_第1张图片



   name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    
    
      %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
    
  

   name="chapters.configuration" level="INFO"/>

  
  
   level="DEBUG">          
     ref="STDOUT" />
    
  


Configuring Appenders

An appender is configured with the  element, which takes two mandatory attributes name and class. Thename attribute specifies the name of the appender whereas the class attribute specifies the fully qualified name of the appender class to instantiate. The  element may contain zero or one  elements, zero or more elements and zero or more  elements. Apart from these three common elements, elements may contain any number of elements corresponding to JavaBean properties of the appender class. Seamlessly supporting any property of a given logback component is one of the major strengths of Joran as discussed in a later chapter. The following diagram illustrates the common structure. Note that support for properties is not visible.

logback笔记1_第2张图片

Logging to multiple appenders is as easy as defining the various appenders and referencing them in a logger, as the next configuration file illustrates:

Example: Multiple loggers (logback-examples/src/main/resources/chapters/configuration/multiple.xml)

View as .groovy


   name="FILE" class="ch.qos.logback.core.FileAppender">
    myApp.log

    
      %date %level [%thread] %logger{10} [%file:%line] %msg%n
    
  

   name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    
      %msg%n
    
  

   level="debug">
     ref="FILE" />
     ref="STDOUT" />
  

By default, appenders are cumulative: a logger will log to the appenders attached to itself (if any) as well as all the appenders attached to its ancestors. Thus, attaching the same appender to multiple loggers will cause logging output to be duplicated.

In case the default cumulative behavior turns out to be unsuitable for your needs, you can override it by setting the additivity flag to false.

在配置文件中定义变量

你可能感兴趣的:(日志)