1.简介
LogBack是一个日志框架,它与Log4j可以说是同出一源,都出自Ceki Gülcü之手。(log4j的原型是早前由Ceki Gülcü贡献给Apache基金会的)
1.1 LogBack,Slf4j,Log4j之间的关系
Slf4j是The Simple Logging Facade for Java的简称,是一个简单日志门面抽象框架,它本身只提供了日志Facade API和一个简单的日志类实现,一般常配合Log4j,LogBack,java.util.logging使用。Slf4j作为应用层的Log接入时,程序可以根据实际应用场景动态调整底层的日志实现框架(Log4j/LogBack/JdkLog...);
LogBack和Log4j都是开源日记工具库,LogBack是Log4j的改良版本,比Log4j拥有更多的特性,同时也带来很大性能提升。详细数据可参照下面地址:Reasons to prefer logback over log4j
LogBack官方建议配合Slf4j使用,这样可以灵活地替换底层日志框架。
(note: 为了优化log4j,以及更大性能的提升,Apache基金会已经着手开发了log4j 2.0, 其中也借鉴和吸收了logback的一些先进特性,目前log4j2还处于beta阶段)
1.2 LogBack的结构
LogBack被分为3个组件,logback-core, logback-classic 和 logback-access.
其中logback-core提供了LogBack的核心功能,是另外两个组件的基础。
logback-classic则实现了Slf4j的API,所以当想配合Slf4j使用时,需要将logback-classic加入classpath.
logback-access是为了集成Servlet环境而准备的,可提供HTTP-access的日志接口;
2. Slf4j+Logback的快速实践
2.1 资源准备
现在常用的是将slf4j+Logback进行配套使用,所以需要将slf4j-api.jar, logback-core.jar, log-classic.jar加入classpath.
之后编写logback.xml配置文件,同样该文件要加入classpath中,这样LogBack启动的时候会自动扫描到并加载。
(note: 若LogBack无法检索到相关的配置文件,则会启用默认配置,将日志按照默认格式输出于控制台)
2.2 logback.xml配置
LogBack的配置大概包括3部分,Appender,Logger,Root的配置。
下面通过一个配置文件的示例来快速了解logback的配置:
<?xml version="1.0" encoding="UTF-8"?> <configuration debug="true" scan="true" scanPeriod="30 seconds"> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <!-- encoders are by default assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder --> <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss} [%level] - %m%n</pattern> <!-- 常用的Pattern变量,大家可打开该pattern进行输出观察 --> <!-- <pattern> %d{yyyy-MM-dd HH:mm:ss} [%level] - %msg%n Logger: %logger Class: %class File: %file Caller: %caller Line: %line Message: %m Method: %M Relative: %relative Thread: %thread Exception: %ex xException: %xEx nopException: %nopex rException: %rEx Marker: %marker %n </pattern> --> </encoder> </appender> <!-- 按日期区分的滚动日志 --> <appender name="ERROR-OUT" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>logs/error.log</file> <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss} [%class:%line] - %m%n</pattern> </encoder> <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"> <!-- daily rollover --> <fileNamePattern>error.%d{yyyy-MM-dd}.log.zip</fileNamePattern> <!-- keep 30 days' worth of history --> <maxHistory>30</maxHistory> </rollingPolicy> </appender> <!-- 按文件大小区分的滚动日志 --> <appender name="INFO-OUT" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>logs/info.log</file> <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss} [%class:%line] - %m%n</pattern> </encoder> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>INFO</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> <fileNamePattern>info.%i.log</fileNamePattern> <minIndex>1</minIndex> <maxIndex>3</maxIndex> </rollingPolicy> <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> <maxFileSize>5MB</maxFileSize> </triggeringPolicy> </appender> <!-- 按日期和大小区分的滚动日志 --> <appender name="DEBUG-OUT" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>logs/debug.log</file> <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss} [%class:%line] - %m%n</pattern> </encoder> <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"> <!-- rollover daily --> <fileNamePattern>debug-%d{yyyy-MM-dd}.%i.log</fileNamePattern> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <!-- or whenever the file size reaches 100MB --> <maxFileSize>100MB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> </rollingPolicy> </appender> <!-- 级别阀值过滤 --> <appender name="SUM-OUT" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>logs/sum.log</file> <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss} [%class:%line] - %m%n</pattern> </encoder> <!-- deny all events with a level below INFO, that is TRACE and DEBUG --> <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> <level>INFO</level> </filter> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- rollover daily --> <fileNamePattern>debug-%d{yyyy-MM-dd}.%i.log</fileNamePattern> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <!-- or whenever the file size reaches 100MB --> <maxFileSize>100MB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> </rollingPolicy> </appender> <root level="debug"> <appender-ref ref="STDOUT" /> <appender-ref ref="ERROR-OUT" /> <appender-ref ref="INFO-OUT" /> <appender-ref ref="DEBUG-OUT" /> <appender-ref ref="SUM-OUT" /> </root> </configuration>
另一个更简单的:
<?xml version="1.0" encoding="UTF-8"?> <configuration debug="true" scan="false" scanPeriod="30 seconds"> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <!-- encoders are by default assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder --> <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss} [%level] - %m%n</pattern> </encoder> </appender> <!-- 按日期区分的滚动日志 --> <appender name="APP" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>logs/app.log</file> <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss} [%class:%line] - %m%n</pattern> </encoder> <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> <level>INFO</level> </filter> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- daily rollover --> <fileNamePattern>app.%d{yyyy-MM-dd}.log</fileNamePattern> <!-- keep 30 days' worth of history --> <maxHistory>30</maxHistory> </rollingPolicy> </appender> <!-- 按日期和大小区分的滚动日志 --> <appender name="DEBUG-OUT" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>logs/debug.log</file> <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss} [%class:%line] - %m%n</pattern> </encoder> <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"> <!-- rollover daily --> <fileNamePattern>debug-%d{yyyy-MM-dd}.%i.log</fileNamePattern> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <!-- or whenever the file size reaches 100MB --> <maxFileSize>30MB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> </rollingPolicy> </appender> <root level="debug"> <appender-ref ref="STDOUT" /> <appender-ref ref="APP" /> <appender-ref ref="DEBUG-OUT" /> </root> </configuration>
2.3 示例
public class Slf4jTest { private static Logger Log = LoggerFactory.getLogger(Slf4jTest.class); @Test public void testLogBack(){ Log.debug("Test the MessageFormat for {} to {} endTo {}", 1,2,3); Log.info("Test the MessageFormat for {} to {} endTo {}", 1,2,3); Log.error("Test the MessageFormat for {} to {} endTo {}", 1,2,3); try{ throw new IllegalStateException("try to throw an Exception"); }catch(Exception e){ Log.error(e.getMessage(),e); } } }
输出:
2013-12-30 21:37:18 [DEBUG] - Test the MessageFormat for 1 to 2 endTo 3 2013-12-30 21:37:18 [INFO] - Test the MessageFormat for 1 to 2 endTo 3 2013-12-30 21:37:18 [ERROR] - Test the MessageFormat for 1 to 2 endTo 3 2013-12-30 21:37:18 [ERROR] - try to throw an Exception java.lang.IllegalStateException: try to throw an Exception at logs.Slf4jTest.testLogBack(Slf4jTest.java:19) ~[bin/:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.6.0_18] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) ~[na:1.6.0_18] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) ~[na:1.6.0_18] at java.lang.reflect.Method.invoke(Method.java:597) ~[na:1.6.0_18] at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47) [junit.jar:na] at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit.jar:na] at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44) [junit.jar:na] at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) [junit.jar:na] at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271) [junit.jar:na] at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70) [junit.jar:na] at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) [junit.jar:na] at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) [junit.jar:na] at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) [junit.jar:na] at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) [junit.jar:na] at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) [junit.jar:na] at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) [junit.jar:na] at org.junit.runners.ParentRunner.run(ParentRunner.java:309) [junit.jar:na] at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) [.cp/:na] at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) [.cp/:na] at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) [.cp/:na] at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) [.cp/:na] at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) [.cp/:na] at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) [.cp/:na]
简易教程基本到这里就差不多了,希望大家都能很快上手。
附带上示例中所用到的类库:slf4j+logback运行类库下载
想了解更多的信息,可访问下面地址: