logback简单实现对日志的保存和处理,且保存有效时间,7天,
配置文件
<?xml version="1.0" encoding="UTF-8"?> <configuration> <springProperty scope="context" name="loglevel" source="log.level"/> <springProperty scope="context" name="maxHistory" source="log.maxHistory"/> <springProperty scope="context" name="maxSize" source="log.maxSize"/> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss}[%level][%thread][%logger]-%msg%n</pattern> <charset>UTF-8</charset> </encoder> </appender> <!-- Perf4J logger Appender --> <appender name="DailyAndSizeRollAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 相对路径文件名--> <file>logs/data_sync.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- rollover daily --> <fileNamePattern>logs/data_sync.%i.%d{yyyy-MM-dd}.log.zip</fileNamePattern> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <!-- or whenever the file size reaches 200MB --> <maxFileSize>${maxSize}</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> <maxHistory>${maxHistory}</maxHistory> </rollingPolicy> <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss}[%level][%thread][%logger]-%msg%n</pattern> <charset>UTF-8</charset> </encoder> </appender> <root level="${loglevel}"> <appender-ref ref="STDOUT"/> <appender-ref ref="DailyAndSizeRollAppender"/> </root> </configuration>
日志依赖
<!--日志--> <!-- logback+slf4j --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.5</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> <version>1.2.3</version> <type>jar</type> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.3</version> <type>jar</type> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
spring配置文件添加信息:
log: level: INFO #日志保存时间(天) maxHistory: 7 #每个日志文件的大小 maxSize: 10MB
测试用例
包名一定要对,太多logger的包了
import org.slf4j.Logger; import org.slf4j.LoggerFactory;
只需要使用对象打印即可在配置文件看到创建的文件
try { logger.info("--------开始执行表KEY_ENTITY_INFO-------------"); keyEntityInfoService.dealEntityInfo(); } catch (Exception e) { logger.error("--------出现异常KEY_ENTITY_INFO-------------" + e.getMessage()); }