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运行类库下载

想了解更多的信息,可访问下面地址:

http://logback.qos.ch

http://www.slf4j.org

Logback LogBack的更多相关文章

  1. 【转】logback logback.xml常用配置详解(二)<appender>

    原创文章,转载请指明出处:http://aub.iteye.com/blog/1101260, 尊重他人即尊重自己 详细整理了logback常用配置, 不是官网手册的翻译版,而是使用总结,旨在更快更透 ...

  2. 【转】logback logback.xml常用配置详解(一)<configuration> and <logger>

    原创文章,转载请指明出处:http://aub.iteye.com/blog/1101260, 尊重他人即尊重自己 详细整理了logback常用配置, 不是官网手册的翻译版,而是使用总结,旨在更快更透 ...

  3. logback logback.xml常用配置详解(三)

    logback logback.xml常用配置详解 <filter> <filter>: 过滤器,执行一个过滤器会有返回个枚举值,即DENY,NEUTRAL,ACCEPT其中之 ...

  4. logback logback.xml 常用配置详解

    一:根节点<configuration>包含的属性: scan: 当此属性设置为true时,配置文件如果发生改变,将会被重新加载,默认值为true. scanPeriod: 设置监测配置文 ...

  5. logback logback.xml常用配置详解(一)<configuration> and <logger>

    logback logback.xml常用配置详解(一)<configuration> and <logger> 博客分类: Log java loglogback  原创文章 ...

  6. logback logback.xml 常用配置详解(转)

    本文转自:http://my.oschina.net/looly/blog/298675 推荐参考:http://blog.csdn.net/haidage/article/details/67945 ...

  7. [转] logback logback.xml常用配置详解(一)<configuration> and <logger>

    转载文章:原文出处:http://aub.iteye.com/blog/1101260 详细整理了logback常用配置, 不是官网手册的翻译版,而是使用总结,旨在更快更透彻的理解其配置 根节点< ...

  8. logback logback.xml常用配置详解 <filter>

    <filter>: 过滤器,执行一个过滤器会有返回个枚举值,即DENY,NEUTRAL,ACCEPT其中之一.返回DENY,日志将立即被抛弃不再经过其他过滤器:返回NEUTRAL,有序列表 ...

  9. 【转】logback logback.xml常用配置详解(三) <filter>

    原创文章,转载请指明出处:http://aub.iteye.com/blog/1110008, 尊重他人即尊重自己 详细整理了logback常用配置, 不是官网手册的翻译版,而是使用总结,旨在更快更透 ...

  10. logback logback.xml常用配置详解(三) <filter>

    <filter>: 过滤器,执行一个过滤器会有返回个枚举值,即DENY,NEUTRAL,ACCEPT其中之一.返回DENY,日志将立即被抛弃不再经过其他过滤器:返回NEUTRAL,有序列表 ...

随机推荐

  1. 网络流 最大流HDU 3549

    //////////在这幅图中我们首先要增广1->2->4->6,这时可以获得一个容量为2的流,但是如果不建立4->2反向弧的话,则无法进一步增广,最终答案为2,显然是不对的, ...

  2. Tomcat安装

    第一步,下载: 直接上下载地址:http://tomcat.apache.org/download-70.cgi 直接下载如下选中即可: 第二步,安装: 然后解压(这里我是放在下载里),再进入bin目 ...

  3. github图片

    github:https://github.com/BigShow1949/BigShow1949

  4. 58. Android一些开发习惯总结

    作者:漫步 链接:https://www.zhihu.com/question/27227425/answer/35973793 来源:知乎 著作权归作者所有.商业转载请联系作者获得授权,非商业转载请 ...

  5. oninput等表单事件

    oninput等表单事件 过去我们常使用keydown和keyup辅助表单元素的处理,这要求处理时,表单元素必须处于激活(聚焦)状态.oninput事件可以实时监听文本框的输入变化.   现代浏览器支 ...

  6. Cache Helper类

    using System; using System.Collections.Generic; using System.Web; using System.Collections; using Sy ...

  7. 系统补丁更新导致MVC3.0.0升级到3.0.1的问题解决

    在更新了系统补丁之后,会不知觉的将MVC3.0.0升级到MVC3.0.1的问题,解决的思路如下: 1.全部MVC引用使用NuGet进行包的管理. 2.单独把MVC库抽离出来,然后放在单独的项目文件夹, ...

  8. 如何查询Oracle中所有用户信息

    1.查看所有用户: select * from dba_users; select * from all_users; select * from user_users; 2.查看用户或角色系统权限( ...

  9. Nginx Parsing HTTP Package、header/post/files/args Sourcecode Analysis

    catalog . Nginx源码结构 . HTTP Request Header解析流程 . HTTP Request Body解析流程 1. Nginx源码结构 . core:Nginx的核心源代 ...

  10. 嵌入式环境下通过 UDP 链接来调试 QT 程序

    据说有为嵌入式提供的 QT Debug 手段,但是目前还没发现,所以想到了这个笨办法.有更好思路的可以推荐. 该思路是基于 QDebug() .因为 QT 提供了重写 QT msg 处理方法的接口 q ...