官方文档:http://logback.qos.ch/manual/index.html logback will try to configure itself using the files logback-test.xml or logback.xml if found on the class path 日志输出级别(level): TRACE < DEBUG < INFO < WARN < ERROR.
配置文件格式: 一、<configuration> 根元素为<configuration> ,包含0或多个<appender>,0或多个<logger>,至多一个<root><configuration>
element, followed by zero or more<appender>
elements, followed by zero or more<logger>
elements, followed by at most one<root>
element
<configurationdebug="true">to print status data
<configurationscan="true"scanPeriod="30 seconds"> 每隔30秒自动扫描配置文件,文件有修改,则加载,未配置scanPeriod,则默认1分钟
二、<logger>
<logger>用于日志输出名称(name)、定义日志的输出级别(level)、输出目的地(appender-ref)、是否继承父<logger>()。
多个logger间中存在继承关系(由name可以看出来),继承关系中根logger用<root>表示
name 决定logger的继承关系:
祖先logger:logger B 以logger A的name+“.”开头,则A 是B的祖先logger
父logger:logger A是logger B的祖先且A与B之间不存在其它的logger.
如果一个<looger>无父<logger>的,则它的父<logger>是<root>.
如:"java" 是"java.util" 父,也是"java.util.Vector"祖先
继承关系对日志输出级别的影响:
子<logger>未定义level,则自动继承父<logger>的level
子<loger>已定义level,则父<logger>的level对子<loger>无效,子<logger>的level可以大于父<logger>
root | DEBUG | DEBUG |
X | INFO | INFO |
X.Y | none | INFO |
X.Y.Z | ERROR | ERROR |
root | ERROR | ERROR |
X | INFO | INFO |
X.Y | DEBUG | DEBUG |
X.Y.Z | WARN | WARN |
继承关系对日志输出目的地的影响:
子logger日志输出目的地:该logger定义的输出目的地Appender,和该logger的祖先中定义的Appender中
root | A1 | not applicable | A1 | Since the root logger stands at the top of the logger hierarchy, the additivity flag does not apply to it. |
x | A-x1, A-x2 | true | A1, A-x1, A-x2 | Appenders of "x" and of root. |
x.y | none | true | A1, A-x1, A-x2 | Appenders of "x" and of root. |
x.y.z | A-xyz1 | true | A1, A-x1, A-x2, A-xyz1 | Appenders of "x.y.z", "x" and of root. |
security | A-sec | false | A-sec | No appender accumulation since the additivity flag is set to false . Only appender A-sec will be used. |
security.access | none | true | A-sec |
Only appenders of "security" because the additivity flag in "security" is set to
|
logger格式:
<logger name="logger name,可以写包路径(‘.’决定继承关系)" level="TRACE|DEBUG|INFO|WARN|ERROR|OFF|默认继承父Logger日志输出级别" additivity="true/false(默认为true,日志输出目的地:除了该logger定义的输出目的地Appender,还将日志输出到该logger的祖先中定义的Appender中),false:不向祖先中定义的Appender输出"> <appender-ref ref="输出目的地 (AppenderName)" /> </logger> <root level="TRACE|DEBUG|INFO|WARN|ERROR| OFF|默认为DEBUG"> <appender-ref ref="输出目的地 (AppenderName)" /> </root>
三、Appender
ConsoleAppender:
<configuration> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <!-- encoders are assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder by default --> <encoder> <pattern>%-4relative [%thread] %-5level %logger{35} - %msg %n</pattern> </encoder> </appender> <root level="DEBUG"> <appender-ref ref="STDOUT" /> </root> </configuration>
FileAppender:
<configuration> <appender name="FILE" class="ch.qos.logback.core.FileAppender"> <file>testFile.log</file> <append>true</append> <!-- encoders are assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder by default --> <encoder> <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern> </encoder> </appender> <root level="DEBUG"> <appender-ref ref="FILE" /> </root> </configuration>
<configuration> <!-- Insert the current time formatted as "yyyyMMdd'T'HHmmss" under the key "bySecond" into the logger context. This value will be available to all subsequent configuration elements. --> <timestamp key="bySecond" datePattern="yyyyMMdd'T'HHmmss"/> <appender name="FILE" class="ch.qos.logback.core.FileAppender"> <!-- use the previously created timestamp to create a uniquely named log file --> <file>log-${bySecond}.txt</file> <encoder> <pattern>%logger{35} - %msg%n</pattern> </encoder> </appender> <root level="DEBUG"> <appender-ref ref="FILE" /> </root> </configuration>
<configuration> <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>logFile.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- daily rollover --> <fileNamePattern>logFile.%d{yyyy-MM-dd}.log</fileNamePattern> <!-- keep 30 days' worth of history --> <maxHistory>30</maxHistory> </rollingPolicy> <encoder> <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern> </encoder> </appender> <root level="DEBUG"> <appender-ref ref="FILE" /> </root> </configuration>
输出到数据库:
支持的数据库:
DB2 | untested | untested | unknown | NO |
H2 | 1.2.132 | - | unknown | YES |
HSQL | 1.8.0.7 | - | NO | YES |
Microsoft SQL Server | 2005 | 2.0.1008.2 (sqljdbc.jar) | YES | YES |
MySQL | 5.0.22 | 5.0.8 (mysql-connector.jar) | YES | YES |
PostgreSQL | 8.x | 8.4-701.jdbc4 | NO | YES |
Oracle | 10g | 10.2.0.1 (ojdbc14.jar) | YES | YES |
SQLLite | 3.7.4 | - | unknown | YES |
Sybase SQLAnywhere | 10.0.1 | - | unknown | YES |
建表脚本在源码中的路径:
src\main\java\ch\qos\logback\access\db\script
表格式:
he logging_event table contains the following fields:
timestamp | big int |
The timestamp that was valid at the logging event's creation. |
formatted_message | text |
The message that has been added to the logging event, after formatting with
|
logger_name | varchar |
The name of the logger used to issue the logging request. |
level_string | varchar |
The level of the logging event. |
reference_flag | smallint |
This field is used by logback to identify logging events that have an exception or Its value is computed by |
caller_filename | varchar |
The name of the file where the logging request was issued. |
caller_class | varchar |
The class where the logging request was issued. |
caller_method | varchar |
The name of the method where the logging request was issued. |
caller_line | char |
The line number where the logging request was issued. |
event_id | int |
The database id of the logging event. |
The logging_event_property is used to store the keys and values contained in the MDC
or the Context
. It contains these fields:
event_id | int |
The database id of the logging event. |
mapped_key | varchar |
The key of the MDC property |
mapped_value | text |
The value of the MDC property |
The logging_event_exception table contains the following fields:
event_id | int |
The database id of the logging event. |
i | smallint |
The index of the line in the full stack trace. |
trace_line | varchar |
The corresponding line |
<configuration> <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> <root level="DEBUG" > <appender-ref ref="DB" /> </root> </configuration>
<configuration debug="true"> <appender name="DB" class="ch.qos.logback.classic.db.DBAppender"> <connectionSource class="ch.qos.logback.core.db.JNDIConnectionSource"> <!-- please note the "java:comp/env/" prefix --> <jndiLocation>java:comp/env/jdbc/logging</jndiLocation> </connectionSource> </appender> <root level="INFO"> <appender-ref ref="DB" /> </root> </configuration>
<configuration> <appender name="DB" class="ch.qos.logback.classic.db.DBAppender"> <connectionSource class="ch.qos.logback.core.db.DataSourceConnectionSource"> <dataSource class="com.mchange.v2.c3p0.ComboPooledDataSource"> <driverClass>com.mysql.jdbc.Driver</driverClass> <jdbcUrl>jdbc:mysql://${serverName}:${port}/${dbName}</jdbcUrl> <user>${user}</user> <password>${password}</password> </dataSource> </connectionSource> </appender> <root level="DEBUG"> <appender-ref ref="DB" /> </root> </configuration>
四、变量定义
方式一:
<configuration> <property name="USER_HOME" value="/home/sebastien" /> <appender name="FILE" class="ch.qos.logback.core.FileAppender"> <file>${USER_HOME}/myApp.log</file> <encoder> <pattern>%msg%n</pattern> </encoder> </appender> <root level="debug"> <appender-ref ref="FILE" /> </root> </configuration>
方式二:
<configuration>
<property resource="resource1.properties" />
<!--resource1.properties 需要在类路径中/resource1.properties-->
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>${USER_HOME}/myApp.log</file>
<encoder>
<pattern>%msg%n</pattern>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="FILE" />
</root>
</configuration>
方式三: 通过脚本或程序设置变量值 1.在启动shell 中设置环境变量:export USER_HOME=变量值 2.在java logback初始化之前 设置 System.setProperty("USER_HOME",变量值); <configuration> <appender name="FILE" class="ch.qos.logback.core.FileAppender"> <file>${USER_HOME}/myApp.log</file> <encoder> <pattern>%msg%n</pattern> </encoder> </appender> <root level="debug"> <appender-ref ref="FILE" /> </root> </configuration>
五、PatternLayout
c{length} lo{length} logger{length} |
Outputs the name of the logger at the origin of the logging event.
This conversion word takes an integer as its first and only option. The converter's abbreviation algorithm will shorten the logger name, usually without significant loss of meaning. Setting the value of length option to zero constitutes an exception. It will cause the conversion word to return the sub-string right to the rightmost dot character in the logger name. The next table provides examples of the abbreviation algorithm in action.
Please note that the rightmost segment in a logger name is never abbreviated, even if its length is longer than the length option. Other segments may be shortened to at most a single character but are never removed. |
|||||||||||||||||||||
C{length} class{length} |
Outputs the fully-qualified class name of the caller issuing the logging request. Just like the %logger conversion word above, this conversion takes an integer as an option to shorten the class name. Zero carries special meaning and will cause the simple class name to be printed without the package name prefix. By default the class name is printed in full. Generating the caller class information is not particularly fast. Thus, its use should be avoided unless execution speed is not an issue. |
|||||||||||||||||||||
contextName cn |
Outputs the name of the logger context to which the logger at the origin of the event was attached to. | |||||||||||||||||||||
d{pattern} date{pattern} d{pattern, timezone} date{pattern, timezone} |
Used to output the date of the logging event. The date conversion word admits a pattern string as a parameter. The pattern syntax is compatible with the format accepted by You can specify the string "ISO8601" for the ISO8601 date format. Note that the %date conversion word defaults to the ISO 8601 date format in the absence of a pattern parameter. Here are some sample parameter values. They assume that the actual date is Friday 20th of October, 2006 and that the author has returned to working on this document just after lunch.
The second parameter specifies a timezone. For example, the '%date{HH:mm:ss.SSS, Australia/Perth} would print the time in the time zone of Perth, Australia, the world's most isolated city. Note that in the absence of the timezone parameter, the default timezone of the host Java platform is used. If the specified timezone identifier is unknown or misspelled, the GMT timezone is assumed as dictated by the TimeZone.getTimeZone(String) method specification. COMMON ERROR Given that the comma ',' character is interpreted as the parameter separator, the pattern |
|||||||||||||||||||||
F / file |
Outputs the file name of the Java source file where the logging request was issued. Generating the file information is not particularly fast. Thus, its use should be avoided unless execution speed is not an issue. |
|||||||||||||||||||||
caller{depth}caller{depth, evaluator-1, ... evaluator-n} |
Outputs location information of the caller which generated the logging event. The location information depends on the JVM implementation but usually consists of the fully qualified name of the calling method followed by the caller's source, the file name and line number between parentheses. A integer can be added to the caller conversion specifier's options to configure the depth of the information to be displayed. For example, %caller{2} would display the following excerpt: 0 [main] DEBUG - logging statement Caller+0 at mainPackage.sub.sample.Bar.sampleMethodName(Bar.java:22) Caller+1 at mainPackage.sub.sample.Bar.createLoggingRequest(Bar.java:17) And %caller{3} would display this other excerpt: 16 [main] DEBUG - logging statement Caller+0 at mainPackage.sub.sample.Bar.sampleMethodName(Bar.java:22) Caller+1 at mainPackage.sub.sample.Bar.createLoggingRequest(Bar.java:17) Caller+2 at mainPackage.ConfigTester.main(ConfigTester.java:38) This conversion word can also use evaluators to test logging events against a given criterion before computing caller data. For example, using %caller{3, CALLER_DISPLAY_EVAL} will display three lines of stacktrace, only if the evaluator called CALLER_DISPLAY_EVAL returns a positive answer. Evaluators are described below. |
|||||||||||||||||||||
L / line |
Outputs the line number from where the logging request was issued. Generating the line number information is not particularly fast. Thus, its use should be avoided unless execution speed is not an issue. |
|||||||||||||||||||||
m / msg / message |
Outputs the application-supplied message associated with the logging event. |
|||||||||||||||||||||
M / method |
Outputs the method name where the logging request was issued. Generating the method name is not particularly fast. Thus, its use should be avoided unless execution speed is not an issue. |
|||||||||||||||||||||
n |
Outputs the platform dependent line separator character or characters. This conversion word offers practically the same performance as using non-portable line separator strings such as "\n", or "\r\n". Thus, it is the preferred way of specifying a line separator. |
|||||||||||||||||||||
p / le / level | Outputs the level of the logging event. | |||||||||||||||||||||
r / relative | Outputs the number of milliseconds elapsed since the start of the application until the creation of the logging event. | |||||||||||||||||||||
t / thread | Outputs the name of the thread that generated the logging event. | |||||||||||||||||||||
X{key:-defaultVal} mdc{key:-defaultVal} |
Outputs the MDC (mapped diagnostic context) associated with the thread that generated the logging event. If the mdc conversion word is followed by a key between braces, as in %mdc{userid}, then the MDC value corresponding to the key 'userid' will be output. If the value is null, then the default valuespecified after the :- operator is output. If no default value is specified than the empty string is output. If no key is given, then the entire content of the MDC will be output in the format "key1=val1, key2=val2". See the chapter on MDC for more details on the subject. |
|||||||||||||||||||||
ex{depth} exception{depth} throwable{depth} ex{depth, evaluator-1, ..., evaluator-n} exception{depth, evaluator-1, ..., evaluator-n} throwable{depth, evaluator-1, ..., evaluator-n} |
Outputs the stack trace of the exception associated with the logging event, if any. By default the full stack trace will be output. The throwable conversion word can followed by one of the following options:
Here are some examples:
This conversion word can also use evaluators to test logging events against a given criterion before creating the output. For example, using %ex{full, EX_DISPLAY_EVAL} will display the full stack trace of the exception only if the evaluator called EX_DISPLAY_EVAL returns a negative answer. Evaluators are described further down in this document. |
|||||||||||||||||||||
xEx{depth} xException{depth} xThrowable{depth} xEx{depth, evaluator-1, ..., evaluator-n} xException{depth, evaluator-1, ..., evaluator-n} xThrowable{depth, evaluator-1, ..., evaluator-n} |
Same as the %throwable conversion word above with the addition of class packaging information. If you do not specify %xThrowable or another throwable-related conversion word in the conversion pattern, At the end of each stack frame of the exception, a string consisting of the jar file containing the relevant class followed by the "Implementation-Version" as found in that jar's manifest will be added. This innovative technique was originally suggested by James Strachan. If the information is uncertain, then the class packaging data will be preceded by a tilde, i.e. the '~' character. Here is an example: java.lang.NullPointerException at com.xyz.Wombat(Wombat.java:57) ~[wombat-1.3.jar:1.3] at com.xyz.Wombat(Wombat.java:76) ~[wombat-1.3.jar:1.3] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.5.0_06] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) ~[na:1.5.0_06] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) ~[na:1.5.0_06] at java.lang.reflect.Method.invoke(Method.java:585) ~[na:1.5.0_06] at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:59) [junit-4.4.jar:na] at org.junit.internal.runners.MethodRoadie.runTestMethod(MethodRoadie.java:98) [junit-4.4.jar:na] ...etc Logback goes to great lengths to ensure that the class packaging information it displays is correct, even in arbitrarily complex class loader hierarchies. However, when it is unable to guarantee the absolute correctness of the information, then it will prefix the data with a tilde, i.e. the '~' character. Thus, it is theoretically possible for the printed class packaging information to differ from the real class packaging information. So, in the above example, given that packaging data for the Wombat class is preceded by a tilde, it is possible that the correct packaging data is in reality [wombat.jar:1.7]. Feedback from users indicates that Netbeans chokes on packaging information. If you are a Netbeans user, then you should disable packaging information in stack traces by adding "%ex" at the end of of your conversion pattern. For example, "%d %logger - %m%n" should be rewritten as "%d %logger - %m%n%ex" |
|||||||||||||||||||||
nopex nopexception |
Although it pretends to handle stack trace data, this conversion word does not output any data, thus, effectively ignoring exceptions. The %nopex conversion word allows the user to override |
|||||||||||||||||||||
marker |
Outputs the marker associated with the logger request. In case the marker contains children markers, the converter displays the parent as well as childrens' names according to the format shown below. parentName [ child1, child2 ] |
|||||||||||||||||||||
property{key} |
Outputs the value associated with a property named key. The the relevant docs on how to define ion entitled define variables and variable scopes. If key is not a property of the logger context, then keywill be looked up in the System properties. There is no default value for key. If it is omitted, the returned value will be "Property_HAS_NO_KEY", expliciting the error condition. |
|||||||||||||||||||||
replace(p){r, t} |
Replaces occurrences of 'r', a regex, with its replacement 't' in the string produces by the sub-pattern 'p'. For example, "%replace(%msg){'\s', ''}" will remove all spaces contained in the event message. The pattern 'p' can be arbitrarily complex and in particular can contain multiple conversion keywords. For instance, "%replace(%logger %msg){'\.', '/'}" will replace all dots in the logger or the message of the event with a forward slash. |
|||||||||||||||||||||
rEx{depth} rootException{depth} rEx{depth, evaluator-1, ..., evaluator-n} rootException{depth, evaluator-1, ..., evaluator-n} |
Outputs the stack trace of the exception associated with the logging event, if any. The root cause will be output first instead of the standard "root cause last". Here is a sample output (edited for space): java.lang.NullPointerException at com.xyz.Wombat(Wombat.java:57) ~[wombat-1.3.jar:1.3] at com.xyz.Wombat(Wombat.java:76) ~[wombat-1.3.jar:1.3] Wrapped by: org.springframework.BeanCreationException: Error creating bean with name 'wombat': at org.springframework.AbstractBeanFactory.getBean(AbstractBeanFactory.java:248) [spring-2.0.jar:2.0] at org.springframework.AbstractBeanFactory.getBean(AbstractBeanFactory.java:170) [spring-2.0.jar:2.0] at org.apache.catalina.StandardContext.listenerStart(StandardContext.java:3934) [tomcat-6.0.26.jar:6.0.26] The %rootException converter admits the same optional parameters as the %xException converter described above, including depth and evaluators. It outputs also packaging information. In short, %rootException is very similar to %xException, only the order of exception output is reversed. Tomasz Nurkiewicz, the author of %rootException converter, documents his contribution in a blog entry entitled "Logging exceptions root cause first". |
相关推荐
**Logback日志框架概述** Logback 是一个用于日志记录的开源框架,由 Ceki Gülcü(SLF4J 的创始人)开发。它是 log4j 的后继者,旨在提供更高的性能、更灵活的配置以及更好的可扩展性。Logback 主要由三部分组成...
### Logback日志配置详解 #### 一、Logback简介 Logback 是一款非常流行的 Java 日志框架,它由 Ceki Gülcü 开发并维护,作为 log4j 的一个优秀替代品出现。Logback 相对于 log4j 有着更好的性能表现,并且拥有...
《Shiro简单登录+Logback日志记录》 在现代Web开发中,权限管理和日志记录是两个不可或缺的环节。Apache Shiro是一个强大且易用的Java安全框架,提供了认证、授权、会话管理和加密等功能,而Logback作为Log4j的替代...
标题中的“将Logback日志输出到websocket”指的是利用Logback这一强大的日志框架,结合WebSocket技术,实现实时的日志传输。Logback是Java世界中广泛使用的日志记录工具,它提供了高效的日志记录功能,而WebSocket则...
本文主要介绍如何在Grails3项目中配置logback,实现日志的详细配置,包括按天生成独立的日志文件、日志格式设置以及对日志文件大小的控制。 首先,logback的配置文件是logback.groovy,需要放在项目的grails-app/...
Logback 是一个在Java开发中广泛使用的日志记录框架,由Ceki Gülcü创造,他是之前流行的log4j框架的创始人。Logback是作为log4j的替代品设计的,它提供了更高的性能和更多的特性。这个压缩包包含了Logback框架的...
(RSA+DES接口加密交互) (logback日志分级) (异常统一处理) (多数据源主主+redis集群) SpringSecurity权限控制 带图形验证码自定义认证器 SpringSecurity过滤器 登陆 + JWT + SpringSecurity权限控制
Logback 是一个流行的 Java 日志框架,由 Ceki Gülcü 创建,他是早期 Log4j 的主要开发者。Logback 提供了高效的日志记录能力,适用于各种规模的应用程序。本教程将详细介绍如何配置 logback 以实现日志记录,并...
(RSA+DES接口加密交互) (logback日志分级) (异常统一处理) (多数据源主主+redis集群) SpringSecurity权限控制 带图形验证码自定义认证器 SpringSecurity过滤器 登陆 + JWT + SpringSecurity权限控制
logback日志写logstash配置appender参考
【logback日志级别动态切换】是Java应用中常见的需求,尤其在大型分布式系统中,为了应对不同的运行环境和性能优化,需要灵活调整日志输出级别。本文将介绍一种使用Java ASM库实现的终极解决方案。 首先,理解...
logback日志的jar包和配置介绍:logback-classic-1.1.2.jar、logback-core-1.1.2.jar、slf4j-api-1.7.7.jar、logback.xml、rsframework.properties
SpringBoot中logback日志保存到mongoDB的方法 SpringBoot中logback日志保存到mongoDB的方法是指在SpringBoot项目中使用logback日志框架将日志保存到mongoDB数据库中的方法。logback是 SpringBoot默认集成的日志框架...
通过"Logback实例,log4,slf4,logback日志输出demo"的学习,你可以掌握如何配置这些工具,以满足项目需求,如指定日志的存储位置,定制日志格式,以及管理日志文件的生命周期。实践这些示例,将有助于提升你在日志...
Logback日志应用.mp4
在这个“spring-logback日志项目模块”中,我们将深入探讨Spring Boot如何与Logback集成,实现高效、灵活的日志记录。 Logback是由Ceki Gülcü创建的,它是Log4j的继承者,旨在提高性能和可配置性。在Spring Boot...
### 使用Logback日志框架记录Java应用程序运行日志 在软件开发过程中,日志记录是一项重要的功能,它有助于开发者理解程序的行为、诊断问题以及优化性能。对于Java应用程序而言,Logback是一个广泛使用的日志框架,...
SpringBoot Logback日志记录到数据库的实现方法 在本文中,我们将详细介绍SpringBoot Logback日志记录到数据库的实现方法。Logback是一个流行的日志记录框架,能够帮助开发者轻松地记录和管理应用程序中的日志信息...
通过上述内容,我们可以了解到SLF4J和Logback日志系统的使用方法以及其主要特点。对于开发人员来说,理解并熟练使用这套日志系统,能够帮助提升代码的可读性,方便调试和问题排查,同时也能提高项目的维护性。