logback-core:核心模块
logback-classis:log4j的改良版本,完整地实现了slf4j API 使你可以很方便的更换其他日志系统如log4j 或者jdk4logging ,代码层面都不需要动,直接替换jar包即可
logback-access:访问模块与Servlet容器集成提供通过Http来访问日志的功能
从上面可知,一般情况下只需要导入logback-core 和 logback-classis ,再配合具体的slf4j 即可完成日志框架的搭建。
//logback 中的 Logger 类的声明
public final class Logger implements org.slf4j.Logger, LocationAwareLogger, AppenderAttachable<ILoggingEvent>, Serializable {
private static final long serialVersionUID = 5454405123156820674L; // 8745934908040027998L;
<configuration >
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%npattern>
encoder>
appender>
<root level="debug">
<appender-ref ref="STDOUT" />
root>
configuration>
配置项三大组成:Logger、 Appender 、Layout
Logger对象就是用来处理日志信息的(决定输出什么日志信息,日志级别),Appender 用来管理日志输出目标源和输出策略(日志往哪输出,日志文件如何管理)、Layout 布局器,用来指定日志内容输出格式(日志输出内容如何格式化)。
Logger属于logback-classic 中,Appender 和 Layout 属于 logback-core 中
每个Logger都要关联到 LoggerContext 中去,其中Logger 是根据命名空间来区分的,比如 com.foo 和 com.foo.Bar ,大小写敏感,而且com.foo 是 com.foo.Bar 的父节点,全部的Logger 在LoggerContext 中类似树形一样。
其中的根Logger 是 rootLogger
Logger rootLogger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
日志级别:TRACE
日志打印:推荐使用占位符 {}
//依次传入多个参数
logger.debug("The new entry is {}. It replaces {}.", entry, oldEntry);
//直接准备参数数组
Object[] paramArray = {newVal, below, above};
logger.debug("Value {} was inserted between {} and {}.", paramArray);
<configuration debug="true" scan="true" scanPeriod="30 secondds" packagingData="true">
<contextName>myAppNamecontextName>
<property name="USER_HOME" value="/home/sebastien" />
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<withJansi>truewithJansi>
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-%highlight(5level) %logger{36} - %msg%n %contextNamepattern>
encoder>
appender>
<logger name="chapters.configuration" level="INFO" />
<logger name="chapters.configuration.Foo" level="DEBUG" additivity="false">
<appender-ref ref="FILE" />
logger>
<root level="debug">
<appender-ref ref="STDOUT" />
root>
configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%-4relative [%thread] %-5level %logger{35} - %msg %npattern>
encoder>
appender>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<append>是否使用追加的方式写文件,默认为 trueappend>
<file>myApp.log 日志文件file>
<immediateFlush>产生logEvent时是否立即刷新,默认为true;在日志量很大的时候建议设置为 falseimmediateFlush>
<encoder>
<pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%npattern>
encoder>
appender>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>logFile.logfile>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<maxHistory>30maxHistory>
<totalSizeCap>3GBtotalSizeCap>
rollingPolicy>
<encoder>
<pattern>%-4relative [%thread] %-5level %logger{35} - %msg%npattern>
encoder>
appender>
<appender name="ROLLING" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>mylog.txtfile>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>mylog-%d{yyyy-MM-dd}.%i.txtfileNamePattern>
<maxFileSize>100MBmaxFileSize>
<maxHistory>60maxHistory>
<totalSizeCap>20GBtotalSizeCap>
rollingPolicy>
<encoder>
<pattern>%msg%npattern>
encoder>
appender>
<appender name="SOCKET" class="ch.qos.logback.classic.net.SocketAppender">
<remoteHost>${host}remoteHost>
<port>${port}port>
<reconnectionDelay>10000reconnectionDelay>
<includeCallerData>${includeCallerData}includeCallerData>
appender>
<appender name="SOCKET" class="ch.qos.logback.classic.net.SSLSocketAppender">
<remoteHost>${host}remoteHost>
<port>${port}port>
<reconnectionDelay>10000reconnectionDelay>
<ssl>
<trustStore>
<location>${truststore}location>
<password>${password}password>
trustStore>
ssl>
appender>
<appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender">
<smtpHost>ADDRESS-OF-YOUR-SMTP-HOSTsmtpHost>
<to>EMAIL-DESTINATIONto>
<to>ANOTHER_EMAIL_DESTINATIONto>
<from>SENDER-EMAILfrom>
<subject>TESTING: %logger{20} - %msubject>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%date %-5level %logger{35} - %message%npattern>
layout>
appender>
c{length} 、lo{length}、logger{length}、C{length}、class{length} : 打印logger的名字
d{pattern}、 date{pattern}、d{pattern, timezone}、date{pattern, timezone}:打印时间
L / line 行号
m / msg / message 日志信息
M / method 产生日志的类中的方法
n 换行符
p / le / level 日志级别
t / thread 线程号
r / relative 应用启动到日志输出的事件间隔 单位 milliseconds
ex 异常信息 ex{2} 2层深度异常 ex{full} 全部 ex 默认全部
//自定义Layout布局器
package chapters.layouts;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.LayoutBase;
public class MySampleLayout extends LayoutBase<ILoggingEvent> {
public String doLayout(ILoggingEvent event) {
StringBuffer sbuf = new StringBuffer(128);
sbuf.append(event.getTimeStamp() - event.getLoggingContextVO.getBirthTime());
sbuf.append(" ");
sbuf.append(event.getLevel());
sbuf.append(" [");
sbuf.append(event.getThreadName());
sbuf.append("] ");
sbuf.append(event.getLoggerName();
sbuf.append(" - ");
sbuf.append(event.getFormattedMessage());
sbuf.append(CoreConstants.LINE_SEP);
return sbuf.toString();
}
}
在web.xml 中添加如下配置
<servlet>
<servlet-name>ViewStatusMessagesservlet-name>
<servlet-class>ch.qos.logback.classic.ViewStatusMessagesServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>ViewStatusMessagesservlet-name>
<url-pattern>/lbClassicStatusurl-pattern>
servlet-mapping>
<configuration debug="true">
<if condition='property("HOSTNAME").contains("torino")'>
<then>
<appender name="CON" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d %-5level %logger{35} - %msg %npattern>
encoder>
appender>
<root>
<appender-ref ref="CON" />
root>
then>
if>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>${randomOutputDir}/conditional.logfile>
<encoder>
<pattern>%d %-5level %logger{35} - %msg %npattern>
encoder>
appender>
<root level="ERROR">
<appender-ref ref="FILE" />
root>
configuration>