10023---logback use and logback.xml detailed __corejava

Source: Internet
Author: User
Tags documentation parent directory time interval log4j

Https://www.cnblogs.com/warking/p/5710303.html

The use of Logback and Logback.xml detailed


I. 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 next module:
Logback-core: Basic modules for 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 replace it with other log systems such as log4j or JDK14 Logging
Logback-access: Access module and servlet container integration provide the ability to access logs via HTTP

Ii. reasons for Logback to replace log4j:
1, faster implementation: Logback's kernel rewrite, in some key execution path performance improvement of more than 10 times times. and Logback not only improves performance, but also initializes smaller memory loads.
2, very full test: Logback After several years, countless hours of testing. Logback tests are completely different levels.
3, Logback-classic very natural realization of the slf4j:logback-classic to achieve the slf4j. In the use of slf4j, you can not feel logback-classic. And because Logback-classic very naturally implements the SLF4J, switching to log4j or something else is very easy, it just needs to be provided as another jar bundle OK, and there's no need to move those code implemented through SLF4JAPI.
4, very full documentation The official website has more than 200 pages of documentation.
5, automatically reload the configuration file, when the configuration file modified, Logback-classic can automatically reload the configuration file. The scanning process is fast and secure, and it does not need to create a separate scan thread. This technology fully guarantees that the application can run very well in the JEE environment.
6, Lilith is a log event observer, and log4j chainsaw similar. And Lilith can handle a large number of log data.
7, cautious mode and very friendly recovery, in cautious mode, multiple Fileappender instances run under multiple JVMs, and can safely write the same log file. Rollingfileappender will have some restrictions. Logback's Fileappender and its subclasses, including Rollingfileappender, can be very friendly to recover from I/O exceptions.
8, the configuration file can handle different situations, developers often need to judge different logback profiles in different environments (development, testing, production). These configuration files are only a few small differences that can be implemented through, and, such that a configuration file can be adapted to multiple environments.
9, Filters (filter) Sometimes, need to diagnose a problem, need to log. In log4j, only the log level is lowered, but this can make a large number of logs, which can affect application performance. In Logback, you can continue to maintain that log level and get rid of a particular situation, such as Alice, the user logged in, her log will be at the debug level and other users can continue to play at the warn level. Only 4 lines of XML configuration are required to implement this functionality. You can refer to Mdcfilter.
10, Siftingappender (a very versatile appender): It can be used to split log files according to any given running parameters. For example, Siftingappender can distinguish between log events to follow users ' sessions, and then each user will have a log file.
11, automatic compression has been typed log:rollingfileappender in the production of new files, will automatically compress the log file has been typed. Compression is an asynchronous process, so even for large log files, the application will not be affected by the compression process.
12, the stack tree with the package version: Logback in the Stack tree log, will bring the packet data.
13. Automatically remove old log files: by setting Timebasedrollingpolicy or SIZEANDTIMEBASEDFNATP maxhistory properties, you can control the maximum number of log files that have been generated. If you set maxhistory 12, those log files for more than 12 months will be automatically removed.

Introduction to the configuration of Logback
1, Logger, Appender and layout
Logger, as the logger of the log, associates it with the corresponding context of the application, mainly for storing the log object, or for defining the log type and level.
Appender is primarily used to specify the destination of log output, which can be console, file, remote socket server, MySQL, Postresql, Oracle and other databases, JMS and remote Unix syslog daemon, and so on.
Layout is responsible for converting events into strings and formatting the output of log information.
2, Logger context
Each logger is associated with a loggercontext,loggercontext responsible for manufacturing logger, and is responsible for arranging the logger in a tree structure. All other logger are also obtained through the static method of the Org.slf4j.LoggerFactory class GetLogger. The GetLogger method takes the logger name as a parameter. Invoking the Loggerfactory.getlogger method with the same name is always a reference to the same logger object.
3, effective level and level of inheritance
Logger can be assigned a level. 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 inherits the level from the nearest ancestor with the assigned level. The default level for root logger is DEBUG.
4, printing methods and basic selection rules
The printing method determines the level at which requests are logged. For example, if L is a logger instance, then the statement l.info ("..") is a record statement of level info. The level of the record request is called enabled when it is higher than or equal to the valid level of its logger, otherwise, it is called disabled. The record request level is P, and its logger valid level is Q, and the request is executed only when p>=q.
The rule is the core of Logback. Levels are sorted as follows: TRACE < DEBUG < INFO < WARN < ERROR

Iv. default configuration for Logback
If both the profile Logback-test.xml and logback.xml do not exist, then Logback calls Basicconfigurator by default and creates a minimized configuration. The minimized configuration consists of a consoleappender associated to the root logger. The output is in%D{HH:MM:SS mode. SSS} [%thread]%-5level%logger{36}-%msg%n is formatted. The default level for root logger is DEBUG.
1, logback configuration file
The syntax for logback configuration files is very flexible. Because it is flexible, it cannot be defined with a DTD or XML schema. In spite of this, you can describe the basic structure of the configuration file: Start with <configuration>, followed by 0 or more <appender> elements, 0 or more <logger> elements, with a maximum of one <root > elements.
2, Logback the default configuration steps
(1). Try to find the file logback-test.xml under Classpath;
(2). If the file does not exist, find the file logback.xml;
(3). If two files do not exist, Logback automatically configures itself with Basicconfigurator, which results in record output to the console.

Five, Logback.xml common configuration detailed

1, root node <configuration&gt, contains the following three 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 omitted-->
</configuration>
2, sub-node <contextname&gt: Used to set the context name, each logger is associated to the logger context, 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.
For example:
<configuration scan= "true" scanperiod= "seconds" debug= "false" >
<contextName>myAppName</contextName>
<!--other configuration omitted-->
</configuration>
3, child node <property>: To define the value of the variable, it has two properties name and value, the value defined by <property> will be inserted into the logger context, you can make "${}" to use the variable.
Name: Names of variables
Value of value: variable defined by
For example:
<configuration scan= "true" scanperiod= "seconds" debug= "false" >
<property name= "App_name" value= "Myappname"/>
<contextName>${APP_Name}</contextName>
<!--other configuration omitted-->
</configuration>
4, child node <timestamp>: Get timestamp string, he has two properties key and Datepattern
Key: Identifies the name of this <timestamp>;
Datepattern: Sets the pattern for converting the current time (the time that resolves the profile) to a string, following the format of the Java.txt.SimpleDateFormat.
For example:
<configuration scan= "true" scanperiod= "seconds" debug= "false" >
<timestamp key= "Bysecond" datepattern= "YyyyMMdd ' T ' Hhmmss"/>
<contextName>${bySecond}</contextName>
<!--other configuration omitted-->
</configuration>
5, sub-node <appender&gt: The component responsible for writing the log, it has two necessary attribute name and class. Name Specifies the Appender name, class specifies the fully qualified name of the Appender
5.1, Consoleappender the log output to the console, with the following child nodes:
&LT;ENCODER&GT: Format the log. (Specific parameters will be explained later)
<target&gt: String System.out (Default) or System.err (no more difference said)
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 indicates that the >=debug level logs are exported to the console

5.2, Fileappender: Add the log to the file, has the following child nodes:
<file>: The file name written, can be a relative directory, or can be an absolute directory, if the parent directory does not exist will be created automatically, there is no default value.
<append>: If True, the log is appended to the end of the file and, if False, clears the existing file, and defaults to true.
<encoder>: Format the logged events.
<prudent>: If True, the log is securely written to the file, even if other fileappender are writing to the file, inefficient and false by default.
Example:
<configuration> 
<appender name= "FILE" class= "Ch.qos.logback.core.FileAppender" &        GT;&NBSP
<file>testfile.log</file> 
<append>true</append> 
<ENCODER>&NBSP
<pattern>%-4relative [%thread]%-5level%logger{35}-%msg%n</pattern> &NBSP
</encoder> 
</appender> 

<root level= "DEBUG" > 
<appender-ref ref= "FILE"/> 
</root> 
</configuration>
The above configuration represents &G T;=debug-level logs are exported to TestFile.log

5.3, Rollingfileappender: Scrolling record file, first log to the specified file, when a certain condition, the log to other files. Has the following child nodes:
<file&gt: The file name that is written, can be a relative directory, or it can be an absolute directory, and will be created automatically if the parent directory does not exist, and there is no default value.
<append&gt: If true, the log is appended to the end of the file, and if it is false, empty the existing file, the default is true.
<rollingpolicy&gt: When scrolling occurs, the behavior of the Rollingfileappender is determined, involving file movement and renaming. Attribute class defines a specific scrolling policy class
Class= "Ch.qos.logback.core.rolling.TimeBasedRollingPolicy": the most commonly used scrolling strategy, which sets the rolling strategy based on time, which is responsible for scrolling and rolling. Has the following child nodes:
<filenamepattern&gt: Required node, contains file name and "%d" converter, "%d" can contain a Java.text.SimpleDateFormat specified time format, such as:%d{yyyy-mm}.
If you use%d directly, the default format is YYYY-MM-DD. The Rollingfileappender file byte point is optional, by setting file, you can specify a different location for the active file and archive file, the current log is always recorded to file (active file), and the name of the active file will not change;
If file is not set, the name of the active file is changed every other time according to the value of the Filenamepattern. "/" or "\" will be used as a directory separator.
<maxhistory>:
An optional node that controls the maximum number of archived files that are retained and deletes old files in excess of the number. Suppose the settings are scrolled every month, and <maxHistory> is 6, only the files for the last 6 months are saved and the old files are deleted. Note that deleting old files is that the directories created for archiving are also deleted.

Class= "Ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy": View the size of the currently active file, and notify Rollingfileappender if the specified size is exceeded Triggers the current active file scrolling. Only one node:
<maxfilesize&gt: This is the size of the active file, and the default value is 10MB.
<prudent&gt: Fixedwindowrollingpolicy is not supported when true. Supports Timebasedrollingpolicy, but has two restrictions, 1 does not support and does not allow file compression, 2 cannot set the file property and must be left blank.

<triggeringpolicy: Tell rollingfileappender appropriate activation scrolling.
Class= "Ch.qos.logback.core.rolling.FixedWindowRollingPolicy" renames the scrolling policy of a file based on the fixed window algorithm. Has the following child nodes:
<minindex&gt: Window Index Minimum value
<maxindex&gt: Window index maximum, the window is automatically set to 12 when the user specifies a window that is too large.
<filenamepattern&gt: Must contain "%i" for example, suppose the minimum and maximum values are 1 and 2, and the naming pattern is mylog%i.log, resulting in archive mylog1.log and Mylog2.log. You can also specify file compression options, such as mylog%i.log.gz or no log%i.log.zip
For example:
<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 daily and 30 days of log files are saved.
<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 configuration above indicates that a log file is generated in the fixed window mode and a new log file is generated when the file is greater than 20MB. The window size is 1 to 3, and when 3 files are saved, the oldest log is overwritten.
&LT;ENCODER&GT: Format the logged events. Responsible for two things, one is to convert the log information into a byte array, and the second is to write the byte array to the output stream.
Patternlayoutencoder is the only useful and default encoder, with a <pattern> node that sets the input format for the log. Using the "%" plus "convert" method, if you want to output "%", you must Escape "\%" with "\".
5.4, there are Socketappender, Smtpappender, Dbappender, Syslogappender, Siftingappender, not commonly used, here is an unknown solution.
You can refer to the Official document (http://logback.qos.ch/documentation.html) and write your own appender.
6, child node <loger&gt: To set a package or a specific class of log printing level, and specify <appender>. <loger> only has a Name property, an optional level, and an optional Addtivity property.
Can contain 0 or more <appender-ref> elements, identifying this appender will be added to this Loger
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, as well as a special 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. As with <loger>, it can contain 0 or more <appender-ref> elements, identifying this appender will be added to this loger.
7, the child node <root&gt: It is also <loger> element, but it is the root loger, is all <loger> 's superior. There is only one level attribute, because name is already named "Root" and is already the most superior.
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.
Six, commonly used Loger configuration
<!--show parameters for Hibernate SQL tailored for 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"/>
Seven, Demo
1, Adding a dependency pack logback use needs to be used with slf4j, so there is a total need to add dependent packages with SLF4J-API
Logback use needs and slf4j.  So the total need to add dependent packages has Slf4j-api.jar,logback-core.jar,logback-classic.jar,logback-access.jar this is temporarily unavailable so don't add dependencies, 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" >
<!--define the storage address of the log file do not use relative paths in Logback configuration-->
<property name= "Log_home" value= "/home"/>
<!--console output-->
<appender name= "STDOUT" class= "Ch.qos.logback.core.ConsoleAppender" >
<encoder class= "Ch.qos.logback.classic.encoder.PatternLayoutEncoder" >
<!--formatted output:%d represents the date,%thread represents the thread name,%-5level: the level displays 5 character widths from the left%msg: Log messages,%n are line breaks-->
<pattern>%d{yyyy-mm-dd HH:mm:ss. SSS} [%thread]%-5level%logger{50}-%msg%n</pattern>
</encoder>
</appender>
<!--generate log files on a daily basis-->
<appender name= "FILE" class= "Ch.qos.logback.core.rolling.RollingFileAppender" >
<rollingpolicy class= "Ch.qos.logback.core.rolling.TimeBasedRollingPolicy" >
<!--the file name of the log file output-->
<FileNamePattern>${LOG_HOME}/TestWeb.log.%d{yyyy-MM-dd}.log</FileNamePattern>
<!--log file retention days-->
<MaxHistory>30</MaxHistory>
</rollingPolicy>
<encoder class= "Ch.qos.logback.classic.encoder.PatternLayoutEncoder" >
<!--formatted output:%d represents the date,%thread represents the thread name,%-5level: the level displays 5 character widths from the left%msg: Log messages,%n are line breaks-->
<pattern>%d{yyyy-mm-dd HH:mm:ss. SSS} [%thread]%-5level%logger{50}-%msg%n</pattern>
</encoder>
<!--maximum size of log file-->
<triggeringpolicy class= "Ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy" >
<MaxFileSize>10MB</MaxFileSize>
</triggeringPolicy>
</appender>

<!--log output level-->
<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 succeeded");
Logger.error ("Logback succeeded");
Logger.debug ("Logback succeeded");
}
}
4, output
  

Viii. Summary

Logback configuration, you need to configure the output source Appender, log the Loger (child nodes) and root (root node), in fact, it output log from the child node, child nodes if there is an output source directly input, if not, judge the configuration of the addtivity, whether like superior delivery, That is, whether it is passed to root, the transmission is the source of the root output, otherwise the log is not output.

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.