1. 创建Loggertest类
@RunWith(SpringRunner.class)
@SpringBootTest
public class Loggertest {
private final Logger logger = LoggerFactory.getLogger(Loggertest.class);
@Test
public void test1(){
String name = "jess";
String password = "123456";
//日志的级别;
//由低到高 trace<debug<info<warn<error
log.debug("debug...");
log.info("info...");
log.warn("warn...");
log.info("name:{},password:{}",name,password);
log.error("error...");
}
}
没有输出debug级别的信息,因为系统默认的级别为Info,比info级别大的能够输出,比info级别小的不能输出
2. lombok工具的使用
由于我们写日志类每次都要写当前类,为了方便,使用lombok提供的一个注解:@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class Loggertest {
@Test
public void test1(){
String name = "jess";
String password = "123456";
log.debug("debug...");
log.info("info...");
log.warn("warn...");
log.info("name:{},password:{}",name,password);
log.error("error...");
}
}
3. 日志的配置(logback-spring.xml)
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<!--配置控制台日志-->
<!--appender指定日志的输出目的地是控制台-->
<appender name ="consolelog" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>
%d - %msg%n
</pattern>
</layout>
</appender>
<!--appender指定info日志的输出目的地为文件-->
<!--将error和info分别记录-->
<appender name="fileInfolog" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!--即使配置info,也不会过滤掉Error级别的日志信息,因为高于info级别的会输出-->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>DENY</onMatch>
<onMismatch>ACCEPT</onMismatch>
</filter>
<encoder>
<pattern>
%msg%n
</pattern>
</encoder>
<!-- 滚动策略:按照时间滚动,每天一个日志文件-->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志存放路径-->
<fileNamePattern>C:\Users\jess\Desktop\java web\sell\日志\info.%d.log</fileNamePattern>
</rollingPolicy>
</appender>
<appender name="fileErrorlog" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 只输出error日志-->
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>
<encoder>
<pattern>
%msg%n
</pattern>
</encoder>
<!-- 滚动策略:按照时间滚动,每天一个日志文件-->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 路径-->
<fileNamePattern>C:\Users\jess\Desktop\java web\sell\日志\error.%d.log</fileNamePattern>
</rollingPolicy>
</appender>
<root level="info">
<appender-ref ref="consolelog" />
<appender-ref ref="fileInfolog" />
<appender-ref ref="fileErrorlog" />
</root>
</configuration>