The most complete logback, including Java case and configuration instructions

Source: Internet
Author: User
Tags time interval log4j
(i) logback Java usage First, Logback introduction

Logback is another open source log component designed by the founder of Log4j. Logback is currently divided into three modules: Logback-core,logback-classic and logback-access. Logback-core is the base module for the other two modules. Logback-classic is an improved version of log4j. In addition, the Logback-classic full implementation SLF4J API allows you to easily replace it with other log systems such as log4j or JDK14 Logging. The Logback-access access module and servlet container integration provide the ability to access logs via HTTP (from Baidu Encyclopedia).


second, maven dependency

<!--logback+slf4j-->  
<dependency>  
    <groupId>org.slf4j</groupId>  
    < artifactid>slf4j-api</artifactid>  
    <version>1.6.0</version>  
    <type>jar</ type>  
    <scope>compile</scope>  
</dependency>  
<dependency>  
    <groupid >ch.qos.logback</groupId>  
    <artifactId>logback-core</artifactId>  
    <version> 0.9.28</version>  
    <type>jar</type>  
</dependency>  
<dependency>  
    <groupId>ch.qos.logback</groupId>  
    <artifactId>logback-classic</artifactId>  
    <version>0.9.28</version>  
    <type>jar</type>  
</dependency>  


If you're not using maven, download the jar bag yourself ...


three. Log Usage
We use org.slf4j.LoggerFactory, we can use the log directly.


public class TestController extends Basecontroller {  


    protected final Logger    Logger = Loggerfactory.getlogger ( Testcontroller.class);  
  
    public void Hello () {  
        logger.debug ("Debug TEST This place output debug level log");  
        Logger.info ("info test this place output info level log");  
        Logger.error ("error test this place output error level log");  
    }  
  




(b) Logback configuration detailed
One: Root node <configuration> included properties: Scan: When this property is set to True, the configuration file will be reloaded if it changes, and the default value is true. Scanperiod: Set the monitoring profile for changes in the time interval, if no time units are given, the default unit is milliseconds. This property takes effect when scan is true. The default time interval is 1 minutes. Debug: When this property is set to True, the Logback internal log information is printed and the Logback run status is viewed in real time. The default value is False.

For example:


<configuration scan= "true" scanperiod= "seconds" debug= "false" >  
      <!--other configuration omit-->  
</ Configuration>


Two: The root node <configuration> child nodes:

Set Context name:<contextname>

Each logger is associated with the logger context, and the default context name defaults. However, you can use <contextName> to set other names to distinguish between records for different applications. Once set, cannot be modified.


<!--lang:xml-->
<configuration scan= "true" scanperiod= "seconds" debug= "false" >  
      < Contextname>myappname</contextname>  
      <!--other configurations omit-->  
</configuration>



Setting variables: <property>

The label used to define the value of the variable,<property> has two attribute name and value; Name: variable's value when the variable is defined.

Values defined by <property> are inserted into the logger context. After you define a variable, you can make "${}" use the variable.

For example, use <property> to define a context name, and then use it when you <contentName> set the logger context.


<!--lang:xml-->
<configuration scan= "true" scanperiod= "seconds" debug= "false" >  
      <property Name= "App_name" value= "Myappname"/>   
      <contextName>${APP_Name}</contextName>  
      <!-- Other configuration omitted-->  
</configuration>



gets the timestamp string:<timestamp>

Two properties: Key: Identifies this <timestamp> name; Datepattern: Sets the pattern of converting the current time (the time that resolves the profile) to a string, following the format of the Java.txt.SimpleDateFormat.

For example, the time for parsing a profile is the context name:


<!--lang:xml-->
<configuration scan= "true" scanperiod= "seconds" debug= "false" >  
      < Timestamp key= "Bysecond" datepattern= "YyyyMMdd ' T ' Hhmmss"/> <contextname>${bysecond}</contextname   
      >  
      <!--other configuration omitted-->  
</configuration>


Set Loger: <loger>

Used to set the log print level for a package or a specific class, and specify <appender>. <loger> only has a Name property, an optional level, and an optional Addtivity property.

Name: Used to specify a package or a specific class that is constrained by this loger.

Level: Used to set print levels, case-insensitive: TRACE, DEBUG, Info,warn,error,all and off, and a custom value inherited or synonym null ', representing the level at which the parent is enforced. If this property is not set, the current Loger will inherit the level of the ancestor.

Addtivity: Whether to pass print information to the superior Loger. The default is true. <root>

is also a <loger> element, but it is a root loger. There is only one level attribute, which should have been named "Root". Level: Used to set print levels, case-insensitive: TRACE, DEBUG, INFO, WARN, ERROR, all, and off, cannot be set to inherited or synonym null. The default is Debug.

<loger> and <root> can contain 0 or more <appender-ref> elements, identifying this appender will be added to this loger.

For example: Logbackdemo.java class


<!--lang:java-->
package logback;  

Import Org.slf4j.Logger;  
Import org.slf4j.LoggerFactory;  

public class Logbackdemo {  
    private static Logger log = Loggerfactory.getlogger (Logbackdemo.class);  
    public static void Main (string[] args) {  
        log.trace ("======trace");  
        Log.debug ("======debug");  
        Log.info ("======info");  
        Log.warn ("======warn");  
        Log.error ("======error");  
    }  
<span style= "font-family:arial, Helvetica, Sans-serif; Background-color:rgb (255, 255, 255); >
</span>
<span style= "font-family:arial, Helvetica, Sans-serif; Background-color:rgb (255, 255, 255); >
</span>
Third, logback.xml configuration file 1th: Configure root only


<!--lang:xml-->
<configuration>   

  <appender name= "STDOUT" class= " Ch.qos.logback.core.ConsoleAppender ">   
    <!--encoder default configuration is Patternlayoutencoder-->   
    <encoder>   
      <pattern>%d{hh:mm:ss. SSS} [%thread]%-5level%logger{36}-%msg%n</pattern>   
    </encoder>   
  </appender>   

  < Root level= "INFO" >             
    <appender-ref ref= "STDOUT"/>   
  </root>     

</configuration>


Where the configuration representation of Appender is printed to the console (explained later in detail Appender), <root level= "Info" > sets the print level of root to "info" and specifies STDOUT with the name "Appender".

When executing logback. When the main method of the Logbackdemo class is used, root gives the log information of the level "info" and greater than "info" to the Appender processing, named "STDOUT", which is already configured, and "STDOUT" Appender prints the information to the console;

Print the results as follows:


13:30:38.484 [main] INFO  logback. Logbackdemo-======info  
13:30:38.500 [main] WARN  logback. Logbackdemo-======warn  


2nd: Configuration with Loger, no level specified, Appender not specified:


<!--lang:xml-->
<configuration>   

  <appender name= "STDOUT" class= " Ch.qos.logback.core.ConsoleAppender ">   
    <!--encoder default configuration is Patternlayoutencoder-->   
    <encoder>   
      <pattern>%d{hh:mm:ss. SSS} [%thread]%-5level%logger{36}-%msg%n</pattern>   
    </encoder>   
  </appender>   

  <!-- Logback to Java package-->   
  <logger name= "Logback"/> <root level=   

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

</configuration>



Where the configuration representation of Appender is printed to the console (explained later in detail Appender), <logger name= "Logback"/> will control the printing of logs for all classes under the Logback package, but does not set the print level, so inherit his superiors <root> log Level "DEBUG"; addtivity is not set, default is true, the Loger print information is passed to the superior; Appender is not set, this loger itself does not print any information. <root level= "Debug" > sets the print level of root to "debug", specifying the Appender with the name "STDOUT".

When executing logback. Logbackdemo The main method of the class, because Logbackdemo is in the package Logback, the <logger name= "Logback"/> is executed first, and the level is "debug" and greater than "debug" The log information is passed to root, which does not print itself; Root receives the information that the subordinate transmits, gives the already configured Appender processing named "STDOUT", "STDOUT" Appender to print the information to the console;

Print the results as follows:


13:19:15.406 [main] DEBUG logback. Logbackdemo-======debug  
13:19:15.406 [main] INFO  logback. Logbackdemo-======info  
13:19:15.406 [main] WARN  logback. Logbackdemo-======warn  
13:19:15.406 [main] ERROR logback. Logbackdemo-======error



3rd: Configuration with multiple loger, specifying levels, specifying Appender:


<!--lang:xml-->
<configuration>   
   <appender name= "STDOUT" class= " Ch.qos.logback.core.ConsoleAppender ">   
    <!--encoder default configuration is Patternlayoutencoder-->   
    <encoder>   
      <pattern>%d{hh:mm:ss. SSS} [%thread]%-5level%logger{36}-%msg%n</pattern>   
    </encoder>   
  </appender>   

  <!-- Logback is a package-->   
  <logger name= "Logback"/>   
  <!--logback in Java. Logbackdemo: The full path of the class-->   
  <logger name= "Logback. Logbackdemo "level=" INFO "additivity=" false ">  
    <appender-ref ref=" STDOUT "/>  
  </logger>   

  <root level= "ERROR" >             
    <appender-ref ref= "STDOUT"/>   
  </root>     
</ Configuration>

Output results:

14:05:35.937 [main] INFO  logback. Logbackdemo-======info  
14:05:35.937 [main] WARN  logback. Logbackdemo-======warn  
14:05:35.937 [main] ERROR logback. Logbackdemo-======error

Addtivity is not set and the default is true to pass this logger print information to the superior.

Appender is not set, this logger itself does not print any information.

<logger name= "Logback. Logbackdemo "level=" INFO "additivity=" false "> Control logback. Logbackdemo class log printing, printing level "INFO".
The Additivity property is False, indicating that the print information for this logger is no longer passed to the superior, and that the appender named "STDOUT" is specified.

<root level= "DEBUG" > sets the print level of root to "ERROR", specifying the Appender with the name "STDOUT".

When executing logback. Logbackdemo The main method of the class, the <logger name= "Logback is executed first. Logbackdemo "level=" "Info" additivity= "false", the level of "info" and greater than "info" log information to this logger named "STDOUT" Appender processing, Log in the console and no longer pass print information to the secondary logger's superior <logger name= "Logback"/>.

<logger name= "Logback"/> has not received any print information and, of course, will not pass any print information to its parent root.

If you will <logger name= "Logback. Logbackdemo "level=" INFO additivity= "false" > modified to <logger name= "Logback". Logbackdemo "level=" INFO additivity= "true" > what will the print result be?
Yes, the log printed two times, presumably everyone knows why, because the printing information to the superior delivery, logger itself printed once, Root received and print once:

14:09:01.531 [main] INFO  logback. Logbackdemo-======info  
14:09:01.531 [main] info  logback. Logbackdemo-======info  
14:09:01.531 [main] WARN  logback. Logbackdemo-======warn  
14:09:01.531 [main] warn  logback. Logbackdemo-======warn  
14:09:01.531 [main] ERROR logback. Logbackdemo-======error  
14:09:01.531 [main] Error logback. Logbackdemo-======error


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.