Logback is intended as a successor to the popular log4j project. It was designed by Ceki Gülcü, log4j's founder.
Logback 是一个日志框架。项目中运用这个框架时需要导入的核心包有:
- slf4j-api.jar
- logback-core.jar
- logback-classic.jar
最基本的使用:
import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ServerMain { private final static Logger logger = LoggerFactory.getLogger(ServerMain.class); public static void main(String[] args) { logger.info("{} application.", "Entering"); logger.info("Exiting application."); } }
logback 有由三个重要的组件组成:
- Logger
- Appender
- Layout OR Encoders
还有一个是:
- Filters
logger 日志的实例,appender 对 logger 记录的事件进行分流并流向目的地,layout 用于控制日志的输出格式。
常用的 appenders 有如下几类:
- OutputStreamAppender
- ConsoleAppender
- FileAppender
- RollFileAppender
- TimeBasedRollingPolicy
- FixedWindowRollingPolicy
下面这个配置信息就是每隔一分钟分割一次日志。这是 logback-test.xml 文件。
<?xml version="1.0" encoding="UTF-8"?> <configuration> <statusListener class="ch.qos.logback.core.status.OnConsoleStatusListener" /> <property file="config/variables.properties" /> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <!-- encoders are assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder by default --> <encoder> <pattern>%date %level [%thread] %logger{50} [%file:%line] %msg%n </pattern> </encoder> </appender> <appender name="ROLLFILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss} %level [%class:%line] - %m%n </pattern> </encoder> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>service.%d{yyyy-MM-dd-HH-mm}.log </fileNamePattern> </rollingPolicy> </appender> <root level="debug"> <appender-ref ref="STDOUT" /> <appender-ref ref="ROLLFILE" /> </root> </configuration>
修改 %d 后面中括号中的 yyyy-MM-dd-HH-mm,如果去掉 HH-mm 那么就是按照天来切分。也就是最后一位如果是 dd 就按照天,如果是 MM 就按照月,如果是 yyyy 就按照年。
参考:
Logback 官方文档 https://logback.qos.ch/manual/index.html