在Idea中點擊File
->New
->Project
->Spring Initializr
,以下圖
填寫項目信息
修改pom.xml
文件java
添加junit測試依賴
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency>
引用文字
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency>
新增
LoggerTest.java
類
import lombok.extern.slf4j.Slf4j; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest @Slf4j public class LoggerTest { //private final Logger logger = LoggerFactory.getLogger(LoggerTest.class); @Test public void test1(){ String name = "lzz"; String password = "123456"; log.debug("debug..."); log.info("name:"+name+" password:"+password); log.info("name:{},password:{}",name,password); log.error("error..."); log.warn("warn...."); } }
經過@Slf4j
註解,替換了private final Logger logger = LoggerFactory.getLogger(LoggerTest.class)
,指向了當前的類,咱們能夠直接經過log.輸出日誌。spring
新增
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"> <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>logback.info.%d{yyyy-MM-dd}.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>logback.error.%d{yyyy-MM-dd}.log</fileNamePattern> </rollingPolicy> </appender> <root level="info"> <appender-ref ref="consoleLog" /> <appender-ref ref="fileInfoLog" /> <appender-ref ref="fileErrorLog" /> </root> </configuration>
經過引用fileInfoLog和fileErrorLog實現對日誌的隔離輸出,並在項目的根路徑下輸出對應的日誌文件。app
文件輸出展現
logback.error.2017-12-21.log展現以下
logback.info.2017-12-21.log展現以下
日誌輸出級別
根據Level的級別,優先級大的優先輸出,因此日誌輸出的順序是ERROR>WARN>INFO>DEBUG>TRACE。測試
歡迎你們訪問個人博客^_^spa