为了实现日志自动清理,所以使用了logback来代替log4j,话不多说,下面就是实现方式,是不是超级简单?
添加依赖包
<dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.5</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> <version>1.0.11</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.0.11</version> </dependency>配置logback.xml
<?xml version="1.0" encoding="UTF-8"?> <!-- 要使配置文件自动重载,需要把 scan 属性设置为 true,默认情况下每分钟才会扫描一次,可以指定扫描间隔:scanPeriod 可用的单位是 milliseconds,seconds,minutes 和 hours --> <configuration scan="true" scanPeriod="60 seconds" debug="false"> <!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径 --> <property name="LOG_HOME" value="./logs" /> <property name="fileLayoutPattern" value="%-20(%d{yyyy-MM-dd HH:mm:ss.SSS} [%logger{50}][%thread] [%-4relative]) [%X{hostName} %X{requestId} %X{processId} %X{service.timing} ][%level] %msg%n" /> <property name="consoleLayoutPattern" value="%-20(%d{yyyy-MM-dd HH:mm:ss.SSS} [%logger{50}][%thread] [%-4relative]) [%X{hostName} %X{requestId} %X{processId} %X{service.timing} ][%level] %msg%n" /> <!-- 控制台输出 --> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <layout name="StandardFormat" class="ch.qos.logback.classic.PatternLayout"> <pattern>${consoleLayoutPattern}</pattern> </layout> </appender> <!-- 按照每天生成日志文件 --> <appender name="INFO" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>${LOG_HOME}/info.log</file> <!-- 日志过滤器,只记录warn级别日志 ,若要配置其他级别,复制appender,修改level,并在root中配置 --> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>INFO</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>${LOG_HOME}/info.%d{yyyy-MM-dd}.log </fileNamePattern> <!--日志文件保留天数 --> <MaxHistory>30</MaxHistory> </rollingPolicy> <layout> <pattern>${fileLayoutPattern}</pattern> </layout> </appender> <appender name="ERROR" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>${LOG_HOME}/error.log</file> <!-- 日志过滤器,只记录warn级别日志 ,若要配置其他级别,复制appender,修改level,并在root中配置 --> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>ERROR</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>${LOG_HOME}/error.%d{yyyy-MM-dd}.log </fileNamePattern> <!--日志文件保留天数 --> <MaxHistory>30</MaxHistory> </rollingPolicy> <layout> <pattern>${fileLayoutPattern}</pattern> </layout> </appender> <!-- 日志输出级别 --> <root level="INFO"> <appender-ref ref="STDOUT" /> <appender-ref ref="INFO" /> <appender-ref ref="ERROR" /> </root> </configuration>
java代码
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Main {
public static Logger log = LoggerFactory.getLogger(Main.class);
public static void main(String[] args) {
log.info("哦了");
log.error("额。。。。");
}
}