Introduction to log Component Logback and how to configure it

Source: Internet
Author: User

First, the introduction of Logback

Logback is another open source log component designed by the founder of Log4j. The Logback is currently divided into three modules: Logback-core,logback-classic and logback-access. The Logback-core is the base module for the other two modules. Logback-classic is an improved version of log4j. In addition logback-classic full implementation of the SLF4J API allows you to easily change to other log systems such as log4j or JDK14 Logging. The Logback-access Access module integrates with the servlet container to provide the ability to access the log via HTTP. Logback is the official website to be combined with the SLF4J with two components as follows:

Logback's official website: http://logback.qos.ch

SLF4J's official website: http://www.slf4j.org

This article uses the following components: please go to the official website to download!

Logback-access-1.0.0.jar

Logback-classic-1.0.0.jar

Logback-core-1.0.0.jar

Slf4j-api-1.6.0.jar

Ii. reasons for Logback to replace log4j:

Logback and log4j are very similar, if you are familiar with log4j, then Logback will soon be handy. Some of the advantages of logback with respect to log4j are listed below:

1. Faster implementation The kernel of Logback has been rewritten to improve performance by more than 10 times times on some key execution paths. and Logback not only improves performance, but also initializes the memory load smaller.

2. Very full testing Logback after a few years, countless hours of testing. Logback tests are completely different levels. In the author's view, it is simple and important to choose Logback rather than log4j.

3, Logback-classic very natural to achieve the SLF4J Logback-classic implements the SLF4J. In the use of slf4j, you can not feel the logback-classic. And because Logback-classic is very natural to achieve the SLF4J, so switch to log4j or other, very easy, only need to provide another jar package is OK, there is no need to move through the SLF4JAPI implementation of the code.

4. The very full documentation official website has more than 200 pages of documentation.

5, automatically reload the configuration file when the configuration file has been modified, Logback-classic can automatically reload the configuration file. The scanning process is fast and secure, and it does not require another scan thread to be created. This technique ensures that the application can run very happily in the JEE environment.

6, Lilith Lilith is the observer for the log event, similar to the chainsaw of log4j. Lilith can also handle large numbers of log data.

7. Cautious mode and very friendly recovery in discreet 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. Profiles can handle different situations developers often need to judge different logback profiles in different environments (development, testing, production). And these profiles are only a few very small differences, can be achieved through, and to achieve, such a configuration file can be adapted to multiple environments.

9, Filters (filter) There are times when a problem needs to be diagnosed and a log must be played. In log4j, only the log level is lowered, but this can make a large number of logs that can affect application performance. In Logback, you can continue to keep that log level and get rid of some special case, such as Alice, who logged in, her log will hit the debug level and other users can continue to hit the warn level. To implement this feature, add only 4 lines of XML configuration. You can refer to Mdcfilter.

10, Siftingappender (a very versatile appender) it can be used to split the log file according to any given run parameter. For example, Siftingappender can distinguish log events from the user's session, and then each user will have a log file.

11. Automatically compress the log that has been hit Rollingfileappender automatically compresses the log files that have been made when a new file is generated. Compression is an asynchronous process, so even for large log files, the application is not affected by the compression process.

12. Stack tree with package version Logback the stack tree log, the packet's data is taken.

13. Automatic removal of 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 that are more than 12 months old will be automatically removed.

In short, logback than log4j too excellent, let our application all set up logback on it!

Introduction to the configuration of Logback

1, Logger, Appender and layout

Logger, which is used as a logger for logging, is associated with the corresponding context of the application, primarily for storing log objects, and for defining log types and levels.

The Appender is primarily used to specify the destination of the log output, which can be a 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 to a loggercontext,loggercontext responsible for manufacturing logger, and is responsible for arranging the logger in a tree structure. All other logger are also obtained by GetLogger the static method of the Org.slf4j.LoggerFactory class. The GetLogger method is called a parameter with the logger name. Calling the Loggerfactory.getlogger method with the same name will always get a reference to the same logger object.

3. Inheritance of effective levels and levels

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, it inherits from the nearest ancestor with the assigned level. Root logger The default level is DEBUG.

4. Printing methods and basic selection rules

The Print method determines the level at which requests are recorded. For example, if L is an logger instance, then the statement l.info ("..") is a record statement with a level of info. The level of logging requests is known to be enabled when it is higher or equal to the valid level of its logger, otherwise, it is called disabled. The record request level is P, and its logger has a valid level of Q, and the request is only executed when p>=q.

This rule is the core of Logback. Levels sorted By: TRACE < DEBUG < INFO < WARN < ERROR

Iv. default configuration for Logback

If none of the profiles Logback-test.xml and Logback.xml exist, then Logback calls Basicconfigurator by default, creating a minimized configuration. The minimized configuration consists of a consoleappender that is associated to the root logger. The output mode is%D{HH:MM:SS. SSS} [%thread]%-5level%logger{36}-%msg%n Patternlayoutencoder is formatted. Root logger The default level is DEBUG.

1. Logback configuration file

The syntax of the Logback configuration file is very flexible. Because it is flexible, it cannot be defined with a DTD or XML schema. However, the basic structure of the configuration file can be described in this way: Beginning with <configuration>, followed by 0 or more <appender> elements, 0 or more <logger> elements, with up to 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 none of the two files exist, Logback automatically configures itself with Bas Icconfigurator, which results in a record output to the console.

3. logback.xml file

<?xml version= "1.0" encoding= "UTF-8"?><configuration> <!--define the storage address of the log file do not use relative paths in Logback configuration---& Lt;property name= "Log_home" value= "C:/log"/> <!--console output--<appender name= "STDOUT" class= "Ch.qos. Logback.core.ConsoleAppender "> <!--log Output codec--<Encoding>UTF-8</Encoding> &lt ; Layout class= "Ch.qos.logback.classic.PatternLayout" > <!--formatted output:%d for the date,%thread for the thread name,%-5level: Level shows 5 from left Character width%msg: Log message,%n is a newline character---<pattern>%d{yyyy-mm-dd HH:mm:ss. SSS} [%thread]%-5level%logger{50}-%msg%n </pattern> </layout> </appender&       Gt           <!--generate log files per day--<appender name= "file" class= "Ch.qos.logback.core.rolling.RollingFileAppender" > <Encoding>UTF-8</Encoding> <rollingpolicy class= "Ch.qos.logback.core.rolling.TimeBasedRolli           Ngpolicy "> <!--log file output file name-- <FileNamePattern>${LOG_HOME}/myApp.log.%d{yyyy-MM-dd}.log</FileNamePattern> <maxhistory>3              0</maxhistory> </rollingPolicy> <layout class= "Ch.qos.logback.classic.PatternLayout" > <!--formatted output:%d represents the date,%thread represents the thread name,%-5level: the level shows 5 character widths from the left%msg: Log messages,%n is newline---<pattern>%d{yyy Y-mm-dd HH:mm:ss. SSS} [%thread]%-5level%logger{50}-%msg%n </pattern> </layout> <!--log file Max Size-<triggeringpolicy class= "Ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy" > <maxfile Size>10mb</maxfilesize> </triggeringPolicy> </appender> <!--show parameters for Hiber      Nate SQL specifically designed 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.hib Ernate.SQL "level=" Debug "/> <logger name=" org.hibernate.engine.QueryParameters "level=" Debug "/> <logger N Ame= "Org.hibernate.engine.query.HQLQueryPlan" level= "DEBUG"/> <!--log output level-<root level= "INFO" &           Gt <appender-ref ref= "STDOUT"/> <appender-ref ref= "FILE"/> </root> <!--log asynchronous to         Database--<appender name= "DB" class= "Ch.qos.logback.classic.db.DBAppender" > <!--Log Asynchronous to database--            <connectionsource class= "Ch.qos.logback.core.db.DriverManagerConnectionSource" > <!--Connection Pool-- <datasource class= "Com.mchange.v2.c3p0.ComboPooledDataSource" > <driverclass>com.mysql.jdbc . Driver</driverclass> <url>jdbc:mysql://127.0.0.1:3306/databaseName</url> <u ser>root</user> <password>root</password> </dataSource> </con NectionsoUrce> </appender>--></configuration> 
Copy Code



V. Reference Logback in the program

Package com.stu.system.action; Import Org.slf4j.logger;import Org.slf4j.loggerfactory;public class blogaction{     //define a global logger, obtained by loggerfactory     private final static Logger Logger = Loggerfactory.getlogger (blogaction.class);      /**     * @param args     *    /public static void main (string[] args) {        logger.info ("Logback succeeded");        Logger.error ("Logback succeeded");}    }

Introduction to log Component Logback and how to configure it

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.