java日志之slf4j与logback简单使用
最近在开发遇到日志是使用slf4j与logback.xml的配置,所以就记录下来了。
1、导入这几个jar包:
Logback 分为三个模块:logback-core,logback-classic,logback-access
logback-core 是核心;
logback-classic 改善了 log4j,且自身实现了 SLF4J API,所以即使用 Logback 你仍然可以使用其他的日志实现,如原始的 Log4J,java.util.logging 等;
logback-access 让你方便的访问日志信息,如通过 http 的方式。
slf4j-api.jar
在工程src目录(也就是classpath路径下)下建立logback.xml
1.logback首先会试着查找logback.groovy文件;
2.当没有找到时,继续试着查找logback-test.xml文件;
3.当没有找到时,继续试着查找logback.xml文件;
4.如果仍然没有找到,则使用默认配置(打印到控制台)。
2、logback.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!-- For assistance related to logback-translator or configuration -->
<!-- files in general, please contact the logback user mailing list -->
<!-- at http://www.qos.ch/mailman/listinfo/logback-user -->
<!-- -->
<!-- For professional support please see -->
<!-- http://www.qos.ch/shop/products/professionalSupport -->
<!-- -->
<configuration scan="true" scanPeriod="30 seconds">
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%p] [%d] [%t] [%c{1}:%L] - [%m]%n</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>
</appender>
<appender name="ERROR" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>../log/%d{yyyy-MM-dd/HH}/error.log.%i</FileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>20MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<encoder>
<pattern>[%-5level] [%d] [%thread] [%logger{0}:%L] - [%m]%n</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>
</appender>
<root level="INFO">
<appender-ref ref="stdout" />
<appender-ref ref="MAIN" />
<appender-ref ref="ERROR" />
</root>
<appender name="CollectorDemoApp" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>../log/%d{yyyy-MM-dd/HH}/CollectorDemoApp.log.%i</FileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>20MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<encoder>
<pattern>[%-5level] [%d] [%thread] [%logger{0}:%L] - [%m]%n</pattern>
</encoder>
</appender>
<logger name="cn.com.CollectorDemoApp" level="info" >
<appender-ref ref="CollectorDemoApp" />
</logger>
</configuration>
3、java类中使用
private static final Logger logger = LoggerFactory.getLogger(CollectorDemoApp.class);