logback+slf4j實現日誌記錄
阿新 • • 發佈:2019-02-03
SLF4J
它不是一個真正的日誌實現,是一個抽象層,執行後臺使用任意一個日誌類庫,只需要更換依賴包和配置檔案。
LogBack + slf4j
- 依賴:
<dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.12</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>1.7.12</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> <version>1.1.3</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.1.3</version> </dependency>
- logback.xml
<?xml version="1.0" encoding="UTF-8"?> <configuration> <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender"> <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> <pattern>%d{yyyy/MM/dd-HH:mm:ss.SSS} %level [%thread] %class:%line>>%msg%n</pattern> </encoder > </appender> <appender name="file" class="ch.qos.logback.core.FileAppender"> <!--<file>D:/logs/dis.log</file>--> <file>/home/work/monkey_dispatcher/tomcat/logs/dispatcher.log</file> <encoder> <pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n</pattern> </encoder> </appender> <appender name="rollingFile" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>/home/work/monkey_dispatcher/tomcat/logs/</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>%d{yyyy-MM-dd}.log</fileNamePattern> </rollingPolicy> <encoder> <pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n</pattern> </encoder> </appender> <!--<logger name="com.controller" level="INFO"></logger>--> <root level="debug"> <appender-ref ref="stdout" /> <appender-ref ref="file" /> <appender-ref ref="rollingFile" /> </root> </configuration>
- java程式碼:
import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LogbackDemo { private static Logger log = LoggerFactory.getLogger(LogbackDemo.class); public static void main(String[] args) { log.trace("trace"); log.debug("debug"); log.info("info"); log.warn("warn"); log.error("error"); } }