基于springBoot下搭建日志框架
1. 日志框架的选择:(这两个框架,springBoot已经整合,无需引入jar包)
2. 在resources目录下配置logback-spring.xml
<?xml version="1.0" encoding="UTF-8" ?> <configuration> <!--控制台的日志输出的配置--> <appender name="consoleLog" class="ch.qos.logback.core.ConsoleAppender"> <!-- 输出日志的格式设置--> <layout class="ch.qos.logback.classic.PatternLayout"> <pattern> %d - %msg%n </pattern> </layout> </appender> <!--输出除警告级别外的日志到本地文件下,并且实现每日生成一个日志文件--> <appender name="fileInfoLog" class="ch.qos.logback.core.rolling.RollingFileAppender"> <!-- 日志级别过滤器--> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <!-- 以下三行表示当匹配到error级别的日志时拒绝写入日志,其余级别允许写入--> <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>F:\sellLog\info.%d.log</fileNamePattern> </rollingPolicy> </appender> <!--只输出警告级别的日志到本地文件下,并且实现每日生成一个日志文件--> <appender name="fileErrorLog" class="ch.qos.logback.core.rolling.RollingFileAppender"> <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>F:\sellLog\error.%d.log</fileNamePattern> </rollingPolicy> </appender> <root level="info"> <appender-ref ref="consoleLog" /> <appender-ref ref="fileInfoLog" /> <appender-ref ref="fileErrorLog" /> </root> </configuration>
3. 在springBoot启动类添加日志相应的对象(本例使用了junit测试,与在启动类配置一样)
package com.yzy.sell; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith (SpringRunner.class) @SpringBootTest public class SellApplicationTests { private final Logger log= LoggerFactory.getLogger(SellApplicationTests.class); @Test public void test1() { String name = "yzy"; String password = "123456"; log.debug("debug..."); log.info("name: " + name + " ,password: " + password); log.info("name: {}, password: {}", name, password); log.error("error..."); log.warn("warn..."); } }