import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private static final Logger logger = LoggerFactory.getLogger(MyClass.class);
使用logger即可。
--
http://logback.qos.ch/manual/introduction.html
The logback-*.jar files are part of the logback distribution whereas slf4j-api-1.7.5.jar ships with SLF4J, a separate project.
logback是SLF4J的原生实现。
没有logback.xml也能直接运行,默认格式:
15:57:12.727 [main] DEBUG HelloWorld1 - Hello world.
--
http://logback.qos.ch/manual/architecture.html
core components: Logger , Appender , Layout. 跟log4j类似。
Parameterized logging
logger.debug("The entry is {}.", entry);
logger.debug("The new entry is {}. It replaces {}.", entry, oldEntry);
logger.debug("Value {} was inserted between {} and {}.", paramArray);
--
http://logback.qos.ch/manual/configuration.html
http://logback.qos.ch/translator/可以把log4j.properties转换为logback.xml。
配置文件搜索顺序 in the classpath:
logback.groovy , logback-test.xml , logback.xml
If neither file is found, logback configures itself automatically using the BasicConfigurator which will cause logging output to be directed to the console.
In the absence of warnings or errors, if you still wish to inspect logback's internal status, then you can instruct logback to print status data by invoking the print() of the StatusPrinter class.
// assume SLF4J is bound to logback in the current environment
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
// print logback's internal status
StatusPrinter.print(lc);
<configuration debug="true">也能达到上面的效果。
Specifying the location of the default configuration file as a system property
java -Dlogback.configurationFile=/path/to/config.xml chapters.configuration.MyApp1
Note that the file extension must be ".xml" or ".groovy". Other extensions are ignored.
Automatically reloading configuration file upon modification
<configuration scan="true">
By default, the configuration file will be scanned for changes once every minute. <configuration scan="true" scanPeriod="30 seconds" >. If no unit of time is specified, then the unit of time is assumed to be milliseconds.
可以在运行时修改日志输出级别,便于调试。
Variable substitution
Earlier versions of this document used the term "property substitution" instead of the term "variable".
<file>${USER_HOME}/myApp.log</file> , ways to set it:
java -DUSER_HOME="/home/sebastien" MyApp2
<property name="USER_HOME" value="/home/sebastien" /> in logback.xml
<property file="src/main/java/chapters/configuration/variables1.properties" /> in logback.xml
Conditional processing of configuration files
logback supports conditional processing of configuration files with the help of <if>, <then> and <else> elements so that a single configuration file can adequately target several environments.
File inclusion
<include file="src/main/java/chapters/configuration/includedConfig.xml"/> in logback.xml
--记录http请求日志
http://logback.qos.ch/access.html
--打开输出缓存
http://logback.qos.ch/manual/encoders.html
As a sub-class of LayoutWrappingEncoder, PatternLayoutEncoder admits the immediateFlush property. The default value for immediateFlush is 'true'. Immediate flushing of the output stream ensures that logging events are immediately written to disk and will not be lost in case your application exits without properly closing appenders. On the other hand, setting this property to 'false' is likely to quintuple (your mileage may vary) logging throughput. As mentioned previously, if immediateFlush is set to 'false' and if appenders are not closed properly when your application exits, then logging events not yet written to disk may be lost.
example:
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>foo.log</file>
<encoder>
<pattern>%d %-5level [%thread] %logger{0}: %msg%n</pattern>
<!-- this quadruples logging throughput -->
<immediateFlush>false</immediateFlush>
</encoder>
</appender>
"grep immediateFlush -r logback-core/",在logback-core/src/main/java/ch/qos/logback/core/encoder/LayoutWrappingEncoder.java
ch.qos.logback.core.encoder.LayoutWrappingEncoder.init(OutputStream os) <- ch.qos.logback.core.OutputStreamAppender.encoderInit() <- ch.qos.logback.core.OutputStreamAppender.setOutputStream(OutputStream outputStream) <- ch.qos.logback.core.FileAppender.openFile(String file_name) <- ch.qos.logback.core.recovery.ResilientFileOutputStream.ResilientFileOutputStream(File file, boolean append) <- java.io.BufferedOutputStream.BufferedOutputStream(OutputStream out)
默认的输出缓存大小是8KB,无法配置。
--退出程序的时候flush缓存
ch.qos.logback.classic.LoggerContext.stop()可以flush缓存,放到ServletContextListener.contextDestroyed或者ShutdownHook里关闭即可。
ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();
// Check for logback implementation of slf4j
if (loggerFactory instanceof LoggerContext) {
LoggerContext context = (LoggerContext) loggerFactory;
context.stop();
}
ref: Re: Do I need to flush events when shutting down using logback? - Author: David Roussel - stackoverflow.com--
从log4j自动转换到logback的格式有问题,<pattern>%d{DATE} [%t] %p %c{2} - %m%n</pattern>会导致错误:
17:38:13,721 |-WARN in ch.qos.logback.classic.pattern.DateConverter@dd1152a - Could not instantiate SimpleDateFormat with pattern DATE java.lang.IllegalArgumentException: Illegal pattern character 'A'
at java.lang.IllegalArgumentException: Illegal pattern character 'A'
at at java.text.SimpleDateFormat.compile(SimpleDateFormat.java:845)
at at java.text.SimpleDateFormat.initialize(SimpleDateFormat.java:659)
at at java.text.SimpleDateFormat.<init>(SimpleDateFormat.java:585)
at at java.text.SimpleDateFormat.<init>(SimpleDateFormat.java:560)
at at ch.qos.logback.core.util.CachingDateFormatter.<init>(CachingDateFormatter.java:34)
at at ch.qos.logback.classic.pattern.DateConverter.start(DateConverter.java:42)
先使用 %d %-5level [%thread] %logger: %msg%n ,具体可以看下面的链接。--详细的格式说明
http://logback.qos.ch/manual/layouts.html
--输出到控制台的例子
Pre[-]
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true" scan="true" scanPeriod="30 seconds">
<appender name="CONSOLE"
class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d %-5level [%thread] %logger: %msg%n</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>TRACE</level>
</filter>
</appender>
<logger name="EchoAsyncServlet" level="TRACE" />
<root level="TRACE">
<appender-ref ref="CONSOLE" />
</root>
</configuration>
No comments:
Post a Comment