This article mainly introduces the configuration of slf4j+logback in Java engineering. It is mainly for readers who already have a certain understanding of slf4j+logback, but some knowledge preparation was also made at the beginning of the article. Let's get to the topic.
Before introducing the SLF4J+logback configuration, first introduce the logback logback of the log component.
(1) The introduction and configuration of log component logback
1. Introduction to logback
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-activity. LOGBACK-CORE is the basic module of the other two modules. logback-classic is an improved version of log4j. In addition, logback-classic fully implements the SLF4J API so that you can easily replace it with other logging systems such as log4j or JDK14 Logging. The logback-access access module integrates with Servlet containers to provide the function of accessing logs through Http. Logback is the official website that combines two components with SLF4J as follows:
logback's official website: http://logback.qos.ch
SLF4J's official website: http://www.slf4j.org
The components used in this article are as follows: Please go to the official website to download!
Logback-ACCESS -.0.0.jar
logback-classic -.0.0.jar
logback-core-1.0.0.jar
SLF4J-API-1.6.0.jar
2. Reasons for logback to replace log4j:
Logback and log4j are very similar. If you are familiar with log4j, logback will be very easy to handle. Here are some advantages of logback over log4j:
1. Faster implement the kernel rewriting of the LOGBACK, and the performance increases by more than 10 times on some key execution paths. Moreover, LOGBACK not only improves performance, but also has less initialized memory loads.
2. Very full test LOGBACK has been tested for a few years, countless hours. LOGBACK's test is completely different. From the author's point of view, this is a simple and important reason to choose logback instead of log4j.
3. LOGBACK-Classic is naturally implemented with SLF4J LOGBACK-CLASSIC to achieve SLF4J. In the use of SLF4J, you can't feel logback-classic. Moreover, because logback-classic implements SLF4J very naturally, switching to log4j or other is very easy. It is OK to just provide it into another jar package, and there is no need to touch the code implemented through SLF4JAPI.
4. Very full document official website has more than 200 pages of documents.
5. Automatically reload the configuration file as a modification of the configuration file, the logback-classic can automatically reload the configuration file. The scanning process is fast and safe, it does not need to create another scanning thread. This technology fully guarantees that the application can run in the Jee environment.
6. Lilith Lilith is an observer of the LOG incident, similar to the Chainsaw of LOG4J. Lilith can also process large amounts of log data.
7. Caution mode and very friendly recovery In Caution mode, multiple FileAppender instances run under multiple JVMs, and can safely write the same log file. RollingFileAppender will have some limitations. Logback's FileAppender and its subclasses including RollingFileAppender are able to recover from I/O exceptions very friendly.
8. Configuration files can handle different situations. Developers often need to judge different logback configuration files in different environments (development, testing, production). These configuration files are only small differences, which can be implemented and to implement, so that a configuration file can adapt to multiple environments.
9. Filters (filters) Sometimes, a problem is required, and a log is needed. In LOG4J, only reducing the log level, but this will make a lot of logs and affect application performance. At LogBack, you can continue to maintain that log level and remove some special cases. For example, if the user logs in, her log will be played at the Debug level and other users can continue to play at the warn level. To achieve this function, you only need to add 4 lines of XML configuration. You can refer to MDCFILTER.
10. SIFTINGAPPENER (a very multi -functional APPENDER) it can be used to divide the log file according to any given operating parameters. For example, SiftingAppender can distinguish the user's session that follows the user's session, and then each user will have a log file.
11. Automatically compress the log RollingFileappender that has been hit. When generating new files, it will automatically compress the log file that has been played. Compression is an asynchronous process, so even for large log files, applications will not be affected in the compression process.
12. The stack tree has a package version of logback. When playing the stack tree log, it will bring the data of the bag.
13. Automatically remove the old log file by setting the Maxhistory property of TimeBasedrollingPolicy or SizeAndTimeBasedfnatp. You can control the maximum number of log files. If maxHistory 12 is set, those log files that have been over 12 months will be automatically removed.
In short, logback is better than log4j. Let our applications build logback on all of our applications!
3. Introduction to the configuration of logback
1. Logger, Appender and Layout
Logger, as a recorder of the log, associates it on the corresponding Context that is used, is mainly used to store log objects. It can also define log types and levels.
APPENDER is mainly used to specify the destination of the log output. The destination can be the console, files, remote platiards servers, MySQL, PostResql, Oracle and other databases, JMS and remote Unix Syslog Guardian processes.
Layout is responsible for the output of the event into a string, formatted log information.
2. Logger Context
Each logger is associated with a loggerContext. LoggerContext is responsible for making Logger, and it is also responsible for arranging each logger with a tree structure. All other Logger was also obtained through the static method of the org.slf4j.loggerFactory class GetLogger. The getlogger method is named by logger. Use the same name to call the loggerFactory.getLogger method. What you get is always a reference to the same logger object.
3. Inheritance of effective levels and levels
Logger can be assigned. Levels include: Trace, Debug, INFO, Warn, and Error, defined in ch.qos.logback.classic.Level class. If the logger is not assigned, then it will inherit the level from the closest ancestor of the distribution level. Root Logger's default level is debug.
4. Printing method and basic selection rules <br /> printing methods determine the level of the request. For example, if L is a logger instance, then the statement L.info("..") is a record statement with a level INFO. The level of a log 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 the logger's valid level is q. Only when p>=q, the request will be executed.
This rule is at the heart of logback. Level sorting is: trace <DEBUG <Info <warn <error
4. Logback's default configuration <br />If the configuration files logback-test.xml and logback.xml do not exist, then logback will call BasicConfigurator by default to create a minimized configuration. To minimize configuration consisting of a Consoleappender associated with a root Logger. The output mode is %d {hh: mm: ss.sss} [ %thread] %-5Level %logger {36} - %msg %n's patternlayoutendCoder. Root Logger's default level is debug.
1. The configuration file of logback
The syntax of the Logback configuration file is very flexible. Because of flexibility, DTD or XML Schema cannot be defined. Nevertheless, you can describe the basic structure of the configuration file in this way: start with <Configuration>, there are zero or more <ppender> elements, zero or more <Logger> elements, and a maximum of <ROOT> elements.
2. The steps of default configuration of logback
(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 both files do not exist, logback uses BAS ICCONFIGURATOR to automatically configure itself, which will cause the record output to the console.
3. logback.xml file
<? xml version = "1.0" encoding = "UTF-8"?> <CONFIGUTION> <!-Define the storage address of the log file. = "C:/Log"/> <!-The console output-> <appender name = "stdout"> <!-log output encoding-> <encoding> UTF-8 </encoding> <laayout> <!-Format output:%d means date,%thread indicates the thread name,%-5LEVEL: level 5 character width from the left display 5 character width%msg: log message,%n is a change symbol-> <ustern>%d {yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n </pattern> </layout> </appender> <!-- Generate every day Log files-> <ppender name = "file"> <encoding> UTF-8 </enCoding> <RollingPolicy> <!-The file name output by the log file-> <filenamepattern> $ {log_home} /myApp.log .%d {yyyy-mm-dd}. Log </fileenamepattern> <maxhistory> 30 </maxhistory> </rollingpolice> <layout> <!-Formulated output:%d represents the date,%thread represents the thread name,%d represents the thread name, %-5LEVEL: 5 characters width displayed from the left%MSG: log message,%n is a change character-> <pattern>%d {yyyy-mm-dd HH: mm: ss.sss} [%thread]% -5Level %Logger {50}- %MSG %N </Pattern> </Layout> <!-The biggest size of the log file-> <TriggeringPolice> <MaxFilesize> 10MB </maxfilesize> </TriggeringPolice> </APPEN der > <!-Show Parameters for Hibernate SQL dedicated to customization of hibernate-> <logger name = "organnate.type.descriptor.sql.basicBinder =" Trace " /> <Logger = "ORG.Hibernate. Type.descriptor.sql.basicextractor "level =" debug " /> <logger name =" org.hibernate.sql "level =" def " /> <log. Erameters "Level =" Debug " /> <logger name =" org.hibernate.engine.qury.hqlqueryplan "level =" debug " /> <!-log output level-> <root level =" info "> <ppender-ref =" Stdout " /> <ppender-Ref Ref =" File " /> < /ROOT> <!-logs to the database-> <ppender name =" db "> <! connectionSource> <!--Connection Pool--> <dataSource> <driverClass>com.mysql.jdbc.Driver</driverClass> <url>jdbc:mysql://127.0.0.1:3306/databaseName </url> <user > root </user> <password> root </password> </datasource> </connectionSource> </Appender> -> </Configuration>> </Configuration>> </Configuration>> </Configuration>> 5. Use reference Logback in program
package com.stu.system.action; import org.slf4j.Logger;import org.slf4j.LoggerFactory;public class BlogAction{ //Define a global logger, obtained through LoggerFactory Take Private Final Static Logger Logger = LoggerFactory.getLogger (blogaction .class); / ** * @param ARGS * / Public Static Void Main (String [] ARGS) {logger.info ("LogBack successful"); logger.error ("Logback success");}}}Next, let's introduce the configuration of SLF4J+LOGBACK in the Java project.
1. Maven -based SLF4J+LOGBACK POM.XML configuration
<Dependency> <Groupid> ORG.SLF4J </Groupid> <Artifactid> SLF4J-API </Artifactid> <Version> 1.7.10 </Version> </Dependency> <GROUPID> C h.qos.logback </ GROUPID> <Artifactid> LogBack-Classic </Artifactid> <Version> 1.1.2 </Version> </DEENDECY> <G.qos. LogBack </groupid> rtifactid> logback-core </ArtiFactid > <Version> 1.1.2 </version> </dependency>
2. Create a new logback.xml configuration file in the classpath directory
<?xml version="1.0" encoding="UTF-8"?><!--scan: When this property is set to true, if the configuration file changes, it will be reloaded, and the default value is true. scanPeriod: Sets the time interval to monitor whether there is a modification of the configuration file. If no time unit is given, the default unit is milliseconds. This property takes effect when scan is true. The default time interval is 1 minute. DEBUG: When this attribute is set to True, the logback internal log information will be printed to check the running status of logback in real time. The default value is false. --><configuration scan="false" scanPeriod="60 seconds" debug="false"> <!-- Define the root directory of the log--> <property name="LOG_HOME" value="/app/log" / > <!-- Define log file name--> <property name="appName" value="netty"></property> <!-- ch.qos.logback.core.ConsoleAppender Indicates console output--> < Appender name = "Stdout"> <Encoding> UTF-8 </ENCODING> <!-log output format:%d means date,%thread indicates thread name,%-5LEVEL: level 5 character width of 5 characters from left%%%%%%%5 character width%%%%%% Logger {50} means that the logger name is 50 characters, otherwise it will be divided according to the period. %msg: log message, %n is a change of lines-> <layout> <Pattern> %d {yyyy-mm-dd Hh: mm: ss.sss} [ %thread] %-5level %logger {50}- % msg%n</pattern> </layout> </appender> <!-- Scroll to record the file, first record the log to the specified file, and when a certain condition is met, record the log to other files--> <appender name = "Applogappender"> <ENCODING> UTF-8 </Encoding> <!-The name of the designated log file-> <file> $ {log_home}/$ {appName} .log </file> <! When rolling, it is determined that the behavior of RollingFileAPPENDER involves file movement and renames TimeBaseDrollingPolicy: the most commonly used rolling strategy. It formulates rolling strategies according to time, which is responsible for rolling and rolling. -> <RollingPolicy> <!-The storage location and file name of the file generated during rolling%d {yyyy-mm-dd}: Roll roll by day by day. Rolling-> <filenamepattern> $ {log_home}/$ {appName}-%d {yyyy-mm-dd}-%i.log </filenamepattern> <!-Optional node, control the reserved archive file the biggest If the quantity exceeds the quantity, delete the old file. Assuming that it is rolled every day and Maxhistory is 365, only the last 365 -day file is saved to delete the old file before. Note that the old files are deleted, and those directory created for archives will also be deleted. -> <maxhistory> 365 </maxhistory> <!-The size of the log file exceeds Maxfilesize, and the log file rolling according to the%i mentioned above pay attention to the configuration SizebasedtricgePolicy. , Must be configured with timeBasedfilenamingandtriggeringPolicy-> <TimebasedFilenamingandtriggeringPolicy> <MaxFilesize> 100MB </MaxFilesize> </TimeBasedFilenamingan DtriggeringPolicy> </RollingPolicy> <!-log output format:%d represents the date time,%thread indicates the thread name,%-5LEVEL: The level of 5 characters from the left display 5 character width%logger {50} indicates that the logger name is 50 characters, otherwise it will be divided according to the period. %msg: log message, %n is a change of lines-> <laayout> <Pattern> %d {yyyy-mm-dd hh: mm: ss.sss} [ %thread]-[ %-5Level] [ %logger { 50}: %LINE]- %msg %n </Pattern> </layout> </APPENDER> <!- Logger is mainly used to store log objects. It can also define log type and level name: , that is, the first half of the package level: the log level to be recorded, including TRACE < DEBUG < INFO < WARN < ERROR addition: The function is whether the children-logger uses the appender configured by rootLogger for output, false: It means that only the appender of the current logger is used -Ref, True: The appender-reF and rootlogger of the current logger-reF and rootlogger-reFs are effective-> <!-Hibernate logger-> <logger name = "Org.Hibernate" level = "error" /> <! <! <! -Spring Framework Logger-> <Logger name = "ORG.SpringFramework" level = "error" additivity = "false"> </logger> <logger name = "com.creditease" level = "Info" additivity = "true "> <ppender-Ref Ref =" Applogappender " /> < /Logger> <!-ROOT and Logger is the relationship between father and son. If there is no special definition, it is default. Logger, either ROOT, the key to judging is to find this logger and then judge the APENDER and Level of this logger. -> <root level = "info"> <ppender-ref = "stdout" /> <ppender-ref = "applogappender" /> < /root> < /configuration>