@nextleaf
2018-11-16T20:41:44.000000Z
字数 2172
阅读 779
日志
slf4j
logback
依赖:slf4j-api
和logback-classic
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j-version}</version>
</dependency>
<!-- log4j的升级,是self4j api的实现(只能有一个实现) -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback-version}</version>
<!-- scope原是test,只能用于测试类中,这里改成compile -->
<scope>compile</scope>
</dependency>
logback.xml配置示例:
logback官方配置指导https://logback.qos.ch/manual/configuration.html
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- 格式化输出:%date表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度 %msg:日志消息,%n是换行符-->
<property name="LOG_PATTERN" value="%date{HH:mm:ss.SSS} [%thread] %-5level %logger{40} - %msg %n"/>
<!-- 定义日志存储的路径,不要配置相对路径 -->
<property name="FILE_PATH" value="D:/logs/ssmpagehelper/demo.%d{yyyy-MM-dd}.%i.log"/>
<!-- 控制台输出日志 -->
<appender name="consolelog" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<!-- 按照上面配置的LOG_PATTERN来打印日志 -->
<pattern>${LOG_PATTERN}</pattern>
</encoder>
</appender>
<!--每天生成一个日志文件,保存15天的日志文件。rollingFile是用来切分文件的 -->
<appender name="rollingFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<!-- rollover daily -->
<fileNamePattern>${FILE_PATH}</fileNamePattern>
<!-- 每个文件最多应该是10MB,保留15天的历史,但最多20GB。 -->
<maxFileSize>10MB</maxFileSize>
<maxHistory>15</maxHistory>
<totalSizeCap>1GB</totalSizeCap>
</rollingPolicy>
<encoder>
<pattern>${LOG_PATTERN}</pattern>
</encoder>
<!--暂不使用过滤器-->
</appender>
<!--logger级别的优先级要高于或等于root logger级别的优先级才不会打印两次-->
<logger name="test.mylogtest.MyLoggerTest" level="INFO" additivity="false">
<appender-ref ref="consolelog"/>
</logger>
<!--additivity标志不适用于根记录器-->
<root level="DEBUG">
<appender-ref ref="consolelog"/>
<appender-ref ref="rollingFile"/>
</root>
</configuration>
<!--logback官方配置指导https://logback.qos.ch/manual/configuration.html-->
使用示例:
package test.mylogtest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MyLoggerTest {
private final Logger logger = LoggerFactory.getLogger(MyLoggerTest.class);
public static void main(String[] args) {
MyLoggerTest login=new MyLoggerTest();
login.aVoid();
}
public void aVoid() {
logger.info("Hello World");
}
}