This article mainly introduces the configuration of Slf4j+logback in Java Engineering, the reader is mainly slf4j+logback have a certain understanding of the students, but at the beginning of the article also did some knowledge matting, below we get to the point.
Before introducing the Slf4j+logback configuration, first introduce the log component Logback.
(i) Introduction and configuration usage of log component Logback
I. 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-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 the servlet container integration provide the ability to access logs through HTTP. Logback is to be combined with SLF4J with two components of the official website 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-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, and if you are familiar with log4j, it will soon be handy for logback. Some of the advantages of logback relative to log4j are listed below:
1, faster implementation of the logback of the kernel rewrite, in some key execution path on the 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. In the author's view, this is simply an important reason to choose Logback rather than log4j.
3, Logback-classic very natural realization of the SLF4J Logback-classic achieved 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 Logback-classic can automatically reload the configuration file when the profile is modified. 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 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. Configuration files 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, Stack tree with package version logback when the stack tree log is played, the packet data is taken.
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.
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, 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 uses Bas icconfigurator to automatically configure itself, which results in record output to the console.
3, Logback.xml documents
<?xml version= "1.0" encoding= "UTF-8"?> <configuration> <!--define the storage address of the log file do not use relative paths in Logback configuration--> T;property name= "Log_home" value= "C:/log"/> <!--console output--> <appender name= "STDOUT" class= "Ch.qos.logba" Ck.core.ConsoleAppender "> <!--log output encoding--> <Encoding>UTF-8</Encoding> <layout class= "Ch.qos.logback.classic.PatternLayout" > <!--formatted output:%d for date,%thread for thread name,%-5level: Level 5 character width from left%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> < !--generate log files daily--> <appender name= "file" class= "Ch.qos.logback.core.rolling.RollingFileAppender" > <e ncoding>utf-8</encoding> <rollingpolicy class= "Ch.qos.logback.core.rolling.TimeBasedRollingPolicy" > <!--file name--> <filenamepattern>${log_home}/myapp.log.%d{yyyy-mm-dd} for log file output.log</filenamepattern> <MaxHistory>30</MaxHistory> </rollingPolicy> <layout C lass= "Ch.qos.logback.classic.PatternLayout" > <!--formatted output:%d for date,%thread for thread name,%-5level: Level 5 character width from left%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> <!--maximum size of log file--> <triggeringpolicy class= "Ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy" > <MAXFILESIZE>10MB </MaxFileSize> </triggeringPolicy> </appender> <!--show parameters for Hibernate SQL specifically for Hib Ernate Custom--> <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" Debug "/> <logger name=" org.hibernate.engine.QueryParameters "level=" Debug "/> <loGger name= "Org.hibernate.engine.query.HQLQueryPlan" level= "DEBUG"/> <!--log output level--> <root level= "INFO "> <appender-ref ref=" STDOUT "/> <appender-ref ref=" FILE "/> </root> <!--day
Log asynchronously to the database--> <appender name= "DB" class= "Ch.qos.logback.classic.db.DBAppender" > <!--logs asynchronously to the database--> <connectionsource class= "Ch.qos.logback.core.db.DriverManagerConnectionSource" > <!--connection pool--> <d Atasource class= "Com.mchange.v2.c3p0.ComboPooledDataSource" > <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>--> &L T;/configuration>
V. Reference Logback in the program
Package com.stu.system.action;
Import Org.slf4j.Logger;
Import org.slf4j.LoggerFactory;
public class blogaction{
//defines a global logger that obtains the
private final static Logger Logger by Loggerfactory Loggerfactory.getlogger (blogaction.class);
/**
* @param args */public
static void Main (string[] args) {
logger.info ("Logback succeeded");
Logger.error ("Logback succeeded");
}
Next we'll describe the configuration of Slf4j+logback in Java Engineering.
A. Slf4j+logback pom.xml configuration based on Maven
<dependency>
<groupId>org.slf4j</groupId>
<artifactid>slf4j-api</artifactid >
<version>1.7.10</version>
</dependency>
<dependency>
<groupid >ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version >1.1.2</version>
</dependency>
<dependency>
<groupid>ch.qos.logback </groupId>
<artifactId>logback-core</artifactId>
<version>1.1.2</version >
</dependency>
New logback.xml configuration file in Classpath directory
<?xml version= "1.0" encoding= "UTF-8"?> <!--Scan: When this property is set to True, the configuration file is reloaded if it changes, and the default value is true. Scanperiod: Set the monitoring configuration file for changes in the interval, if no time unit is given, the default unit is milliseconds when scan is true, this property takes effect.
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. --> <configuration scan= "false" scanperiod= "seconds" debug= "false" > <!--define the root of the log--> <property n Ame= "Log_home" value= "/app/log"/> <!--define log file name--> <property name= "AppName" value= "Netty" ></proper Ty> <!--ch.qos.logback.core.ConsoleAppender indicates console output--> <appender name= "stdout" class= "ch.qos.logback.co" Re. Consoleappender "> <Encoding>UTF-8</Encoding> <!--log output format:%d for date time,%thread for thread name,%-5level: level from left Displaying 5 character widths%logger{50} indicates that the logger name is up to 50 characters long, otherwise it is segmented by a period. %MSG: Log message,%n is a newline character--> <layout class= "Ch.qos.logback.classic.PatternLayout" > <pattern>%d{yyyy-m M-dd HH:mm:ss. SSS} [%thread]%-5level%logger{50}-%msg%n</pattern> </layout&Gt </appender> <!--scrolling record files, logging to the specified file, logging to other files when a condition is met--> <appender name= "Applogappender class=" ch
. qos.logback.core.rolling.RollingFileAppender "> <Encoding>UTF-8</Encoding> <!--Specify the name of the log file-->
<file>${LOG_HOME}/${appName}.log</file> <!--When scrolling occurs, determines the behavior of rollingfileappender, involving file movement and renaming
Timebasedrollingpolicy: The most commonly used scrolling strategy, which sets the rolling strategy based on time, which is responsible for scrolling and rolling. --> <rollingpolicy class= "Ch.qos.logback.core.rolling.TimeBasedRollingPolicy" > < The files that are generated when scrolling Drop position and file name%d{yyyy-mm-dd}: Log scrolling by day%i: When file size exceeds maxfilesize, file scrolling according to I--> <filenamepattern>${log_h Ome}/${appname}-%d{yyyy-mm-dd}-%i.log</filenamepattern> <!--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 setting scrolls daily and the maxhistory is 365, only the last 365 days of the file are saved, and the old file is deleted.
Note that deleting old files is that the directories created for archiving are also deleted. --> <MaxHistory>365</MaxHistory> <!--The log file exceeds the size specified by MaxFileSize, according to the% mentioned aboveI log file scrolling Note This configuration Sizebasedtriggeringpolicy is not possible to scroll by file size and must be configured Timebasedfilenamingandtriggeringpolicy--> ; Timebasedfilenamingandtriggeringpolicy class= "Ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP" > <
Maxfilesize>100mb</maxfilesize> </timeBasedFileNamingAndTriggeringPolicy> </rollingPolicy> <!--log Output format:%d indicates the date time,%thread represents the thread name,%-5level: the level displays 5 character widths from the left%logger{50} indicates that the logger name is 50 characters long, otherwise it is divided by a period. %MSG: Log message,%n is a newline character--> <layout class= "Ch.qos.logback.classic.PatternLayout" > <pattern>%d{yyy Y-mm-dd HH:mm:ss.
SSS} [%thread]-[%-5level] [%logger{50}:%line]-%msg%n</pattern> </layout> </appender> <!--logger is primarily used to hold log objects or to define the log type, level name: a matching logger type prefix, which is the first half level of the package: Log levels to record, including TRACE < DEBUG < INFO < WARN < ERROR additivity: The effect is to children-logger whether to use Rootlogger configured Appender for output, false: Indicates that only the logger of the current appender-ref is used. True: Represents the Appender-ref and Rootlo of the current loggerGger appender-ref are effective--> <!--hibernate logger--> <logger "error" name= "Org.hibernate" level= t;! --Spring Framework logger--> <logger name= "org.springframework" level= "error" additivity= "false" ></ logger> <logger name= "com.creditease" level= "info" additivity= "true" > <appender-ref ref= "AppLogAppender" "/> </logger> <!--root and logger are parent-child relationships, without a special definition, the default is root, and any class will only correspond to a logger, or a defined logger, or root, and the key to judgment is
Find this logger, and then judge the Appender and level of this logger.
--> <root level= "info" > <appender-ref ref= "stdout"/> <appender-ref ref= "Applogappender"/>
</root> </configuration>