Logback是由log4j創始人Ceki Gülcü設計的又一個開源日誌組件。logback當前分紅三個模塊:logback-core,logback- classic和logback-access。html
Logback主要創建於Logger、Appender 和 Layout 這三個類之上。
java
Logger:日誌的記錄器,把它關聯到應用的對應的context上後,主要用於存放日誌對象,也能夠定義日誌類型、級別。Logger對象通常多定義爲靜態常量,如:mysql
package com.logs; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MyApp { final static Logger logger = LoggerFactory.getLogger("MyApp.class"); public static void main(String[] args) { logger.trace("trace"); logger.debug("debug str"); logger.info("info str"); logger.warn("warn"); logger.error("error"); } }
Appender:用於指定日誌輸出的目的地,目的地能夠是控制檯、文件、遠程套接字服務器、 MySQL、 PostreSQL、Oracle和其餘數據庫、 JMS和遠程UNIX Syslog守護進程等。spring
Layout:負責把事件轉換成字符串,格式化的日誌信息的輸出。具體的Layout通配符,能夠直接查看幫助文檔。sql
Logger能夠被分配級別。級別包括:TRACE、DEBUG、INFO、WARN和ERROR,定義於ch.qos.logback.classic.Level類。程序會打印高於或等於所設置級別的日誌,設置的日誌等級越高,打印出來的日誌就越少。若是設置級別爲INFO,則優先級高於等於INFO級別(如:INFO、 WARN、ERROR)的日誌信息將能夠被輸出,小於該級別的如DEBUG將不會被輸出。爲確保全部logger都可以最終繼承一個級別,根logger老是有級別,默認狀況下,這個級別是DEBUG。數據庫
Logback的過濾器基於三值邏輯(ternary logic),容許把它們組裝或成鏈,從而組成任意的複合過濾策略。過濾器很大程度上受到Linux的iptables啓發。這裏的所謂三值邏輯是說,過濾器的返回值只能是ACCEPT、DENY和NEUTRAL的其中一個。express
若是返回DENY,那麼記錄事件當即被拋棄,再也不通過剩餘過濾器;apache
若是返回NEUTRAL,那麼有序列表裏的下一個過濾器會接着處理記錄事件;api
若是返回ACCEPT,那麼記錄事件被當即處理,再也不通過剩餘過濾器。服務器
Logback-classic提供兩種類型的過濾器:常規過濾器和TuroboFilter過濾器。Logback總體流程:Logger 產生日誌信息;Layout修飾這條msg的顯示格式;Filter過濾顯示的內容;Appender具體的顯示,即保存這日誌信息的地方。
Java項目中通常都會應用好比struts、spring、hibernate等開源框架,而這些框架不少是應用log4j記錄日誌的,因此咱們考慮用log4j + slf4j + logback 。這樣咱們須要導入log4j-over-slf4j-1.6.4.jar(備註:此類主要用於接管以前log4j 打印的日誌 route 到slf4j 而後通logback 打印日誌) 、logback-classic-1.0.1.jar 、logback-core-1.0.1.jar 、slf4j-api-1.6.4.jar ,若是你要用到EvaluatorFilter過濾器來過濾日誌Msg中的特殊字符須要導入其依賴包 janino-2.3.2.jar。其logback.xml
<?xml version="1.0" encoding="UTF-8"?> <configuration> <!-- 控制檯輸出 --> <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%date [%thread] %-5level %logger{80} - %msg%n</pattern> </encoder> </appender> <!-- 時間滾動輸出 level爲 DEBUG 日誌 --> <appender name="file—debug" class="ch.qos.logback.core.rolling.RollingFileAppender"> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>DEBUG</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY </onMismatch> </filter> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <FileNamePattern>D:/logs/debug.%d{yyyy-MM-dd}.log</FileNamePattern> <MaxHistory>30</MaxHistory> </rollingPolicy> <encoder> <pattern>%date [%thread] %-5level %logger{80} - %msg%n</pattern> </encoder> </appender> <!-- 時間滾動輸出 level爲 ERROR 日誌 --> <appender name="file—error" class="ch.qos.logback.core.rolling.RollingFileAppender"> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>ERROR</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY </onMismatch> </filter> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <FileNamePattern>D:/logs/error.%d{yyyy-MM-dd}.log</FileNamePattern> <MaxHistory>30</MaxHistory> </rollingPolicy> <encoder> <pattern>%date [%thread] %-5level %logger{80} - %msg%n</pattern> </encoder> </appender> <!-- 特定過濾含有某字符串的日誌 --> <appender name="file-str" class="ch.qos.logback.core.rolling.RollingFileAppender"> <filter class="ch.qos.logback.core.filter.EvaluatorFilter"> <evaluator> <expression>message.contains("str")</expression> </evaluator> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <FileNamePattern>D:/logs/contains.%d{yyyy-MM-dd}.log </FileNamePattern> <MaxHistory>30</MaxHistory> </rollingPolicy> <encoder> <pattern>%date [%thread] %-5level %logger{80} - %msg%n</pattern> </encoder> </appender> <!-- 數據庫輸出 --> <appender name="db" class="ch.qos.logback.classic.db.DBAppender"> <connectionSource class="ch.qos.logback.core.db.DriverManagerConnectionSource"> <driverClass>com.mysql.jdbc.Driver</driverClass> <url>jdbc:mysql://host_name:3306/datebase_name</url> <user>username</user> <password>password</password> </connectionSource> </appender> <logger name="java.sql.Connection"> <level value="DEBUG" /> </logger> <logger name="java.sql.Statement"> <level value="DEBUG" /> </logger> <logger name="com.ibatis"> <level value="DEBUG" /> </logger> <logger name="com.ibatis.common.jdbc.SimpleDataSource"> <level value="DEBUG" /> </logger> <logger name="com.ibatis.common.jdbc.ScriptRunner"> <level value="DEBUG" /> </logger> <logger name="com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate"> <level value="DEBUG" /> </logger> <logger name="com.danga.MemCached"> <level value="INFO" /> </logger> <logger name="org.springframework.test"> <level value="DEBUG" /> </logger> <logger name="org.apache.struts2"> <level value="DEBUG" /> </logger> <root level="DEBUG"><!--根目錄日誌級別--> <appender-ref ref="stdout" /> <appender-ref ref="file—debug" /> <appender-ref ref="file—error" /> <appender-ref ref="file-str" /> <appender-ref ref="db" /> </root> </configuration>
圖片來自:http://logback.qos.ch/manual/configuration.html
查看官方API:http://logback.qos.ch/manual/configuration.html
<logger>
elementAt this point you should have at least some understanding of level inheritance and the basic selection rule. Otherwise, and unless you are an Egyptologist, logback configuration will be no more meaningful to you than are hieroglyphics.
A logger is configured using the <logger>
element. A <logger>
element takes exactly one mandatory name attribute, an optional levelattribute, and an optional additivity attribute, admitting the values true or false. The value of the level attribute admitting one of the case-insensitive string values TRACE, DEBUG, INFO, WARN, ERROR, ALL or OFF. The special case-insensitive value INHERITED, or its synonym NULL, will force the level of the logger to be inherited from higher up in the hierarchy. This comes in handy if you set the level of a logger and later decide that it should inherit its level.
Note that unlike log4j, logback-classic does not close nor remove any previously referenced appenders when configuring a given logger.
The <logger>
element may contain zero or more <appender-ref>
elements; each appender thus referenced is added to the named logger. Note that unlike log4j, logback-classic does notclose nor remove any previously referenced appenders when configuring a given logger.
<root>
elementThe <root>
element configures the root logger. It supports a single attribute, namely thelevel attribute. It does not allow any other attributes because the additivity flag does not apply to the root logger. Moreover, since the root logger is already named as "ROOT", it does not allow a name attribute either. The value of the level attribute can be one of the case-insensitive strings TRACE, DEBUG, INFO, WARN, ERROR, ALL or OFF. Note that the level of the root logger cannot be set to INHERITED or NULL.
Note that unlike log4j, logback-classic does not close nor remove any previously referenced appenders when configuring the root logger.
Similarly to the <logger>
element, the <root>
element may contain zero or more <appender-ref>
elements; each appender thus referenced is added to the root logger. Note that unlike log4j, logback-classic does not close nor remove any previously referenced appenders when configuring the root logger.
Setting the level of a logger or root logger is as simple as declaring it and setting its level, as the next example illustrates. Suppose we are no longer interested in seeing any DEBUG messages from any component belonging to the "chapters.configuration" package. The following configuration file shows how to achieve that.
package chapters.configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Foo { static final Logger logger = LoggerFactory.getLogger(Foo.class); public void doIt() { logger.debug("Did it again!"); } }
package manual.configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MyApp1 { final static Logger logger = LoggerFactory.getLogger(MyApp1.class); public static void main(String[] args) { logger.info("Entering application."); Foo foo = new Foo(); foo.doIt(); logger.info("Exiting application."); } }
Example: Setting the level of a logger (logback-examples/src/main/java/chapters/configuration/sample2.xml)
View as .groovy
<configuration debug="true"><!--這裏能夠配置日誌級別--> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern> %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n </pattern> </encoder> </appender> <logger name="chapters.configuration" level="INFO" /> <!-- turn OFF all logging (children can override) --> <root level="OFF"> <appender-ref ref="STDOUT" /> </root> </configuration>
// assume SLF4J is bound to logback in the current environment LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); // print logback's internal status StatusPrinter.print(lc);
pecifying the location of the default configuration file as a system property
You may specify the location of the default configuration file with a system property named "logback.configurationFile"
. The value of this property can be a URL, a resource on the class path or a path to a file external to the application.
java -Dlogback.configurationFile=/path/to/config.xml chapters.configuration.MyApp1
Note that the file extension must be ".xml" or ".groovy". Other extensions are ignored. Explicitly registering a status listener may help debugging issues locating the configuration file.
Logback-classic can scan for changes in its configuration file and automatically reconfigure itself when the configuration file changes.
If instructed to do so, logback-classic will scan for changes in its configuration file and automatically reconfigure itself when the configuration file changes. In order to instruct logback-classic to scan for changes in its configuration file and to automatically re-configure itself set the scan attribute of the <configuration>
element to true, as shown next.
Example: Scanning for changes in configuration file and automatic re-configuration (logback-examples/src/main/java/chapters/configuration/scan1.xml)
View as .groovy
<configuration scan="true">
...
</configuration>
By default, the configuration file will be scanned for changes once every minute. You can specify a different scanning period by setting the scanPeriod attribute of the <configuration>
element. Values can be specified in units of milliseconds, seconds, minutes or hours. Here is an example:
Example: Specifying a different scanning period (logback-examples/src/main/java/chapters/configuration/scan2.xml)
View as .groovy
<configuration scan="true" scanPeriod="30 seconds" >
...
</configuration>