Java日志-Slf4J
2015年11月10日
Slf4J的api库:slf4j-api-1.7.12.jar
log4J2的Slf4J实现库:log4j-slf4j-impl-2.4.1.jar
log4J2的功能库:log4j-api-2.4.1.jar,log4j-core-2.4.1.jar。
可以省略,但会给出报错误警告。
//Main.java
packagelee;
importorg.slf4j.Logger;
publicclass Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Logger logger =LoggerFactory.getLogger("root");
logger.error("this iserror");
logger.info("this isinfo.");
}
}
只是调用方法使用slf4j,其它操作完全与log4j2相同。
参考:http://www.slf4j.org/manual.html
http://logging.apache.org/log4j/2.x/log4j-slf4j-impl/index.html
http://my.oschina.net/kenshiro/blog/185513
参见:Java日志-Log4j2.docx
示例:
Logger logger =LoggerFactory.getLogger("root");
logger.error("this iserror");
//log4j2.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<configuration>
<appenders>
<Console name="console"target="SYSTEM_OUT">
<PatternLayout
pattern="msg=%m~File=%F~Line=%L~Method=%M~Console~%d{yyyyMMM dd HH:mm:ss,SSS}%n" />
</Console>
<File name="log"fileName="target/test.log" append="true">
<PatternLayout
pattern="%d{DEFAULT}~%levelclass:%C line:%L method:%M - %m%xEx%n" />
</File>
<RollingFilename="dailyrolling" fileName="logs/app.log"
filePattern="logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
<PatternLayout>
<Pattern>msg=%m~File=%F~Line=%L~Method=%M~Console~%d{yyyyMMM dd
HH:mm:ss,SSS}%n</Pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy/>
<SizeBasedTriggeringPolicysize="20 MB" />
</Policies>
<DefaultRolloverStrategymax="10" />
</RollingFile>
<Asyncname="asynclog">
<AppenderRefref="dailyrolling" />
</Async>
</appenders>
<loggers>
<root>
<appender-refref="console"></appender-ref>
</root>
<loggername="com.test.loggerxx" level="info"additivity="true">
<appender-refref="log"></appender-ref>
</logger>
<logger name="lee.log"additivity="false" level="all">
<appender-refref="asynclog"></appender-ref>
</logger>
</loggers>
</configuration>
//Main.java
packagelee;
importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;
publicclass Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Logger logger =LoggerFactory.getLogger("root");
logger.error("this iserror");
logger.info("this isinfo.");
Logger myLogger =LoggerFactory.getLogger("com.test.loggerxx");
myLogger.error("myLogger:this iserror");
myLogger.info("myLogger:this isinfo.");
Logger leeLogger =LoggerFactory.getLogger("lee.log");
for (int i = 0; i < 1000000; ++i){
leeLogger.error("leeLogger:thisis error");
leeLogger.info("leeLogger:thisis info.");
}
}
}