logback 的日志路径一般都是写死在配置文件中的,在某些场景中,有可能需要动态获取到日志存储路径在配置
实现思路:在 logback.xml 中,我们可以通过获取 property 属性来获取动态信息,那么怎么把我们的日志路径放到 property 中就是一个重点了
创建监听器,在初始化 logback 初始化过程中,将我们需要的日志路径设置到上下文中
import cn.mrcode.Ioc;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.LoggerContextListener;
import ch.qos.logback.core.Context;
import ch.qos.logback.core.spi.ContextAwareBase;
import ch.qos.logback.core.spi.LifeCycle;
public class CustomLogContextListener extends ContextAwareBase implements LoggerContextListener, LifeCycle {
/**
* 存储日志路径标识
*/
public static final String LOG_PAHT_KEY = "LOG_PATH";
@Override
public boolean isResetResistant() {
return false;
}
@Override
public void onStart(LoggerContext loggerContext) {
}
@Override
public void onReset(LoggerContext loggerContext) {
}
@Override
public void onStop(LoggerContext loggerContext) {
}
@Override
public void onLevelChange(Logger logger, Level level) {
}
@Override
public void start() {
String path = System.getProperty("user.dir") + "/logs";
System.setProperty(LOG_PAHT_KEY, path);
Context context = getContext();
context.putProperty(LOG_PAHT_KEY, path);
}
@Override
public void stop() {
}
@Override
public boolean isStarted() {
return false;
}
}
classpath 下的 logback.xml 配置
<?xml version="1.0" encoding="UTF-8" ?>
<configuration scan="true" scanPeriod="20 seconds" debug="true">
<contextListener class="这里是刚刚创建的监听器类路径.CustomLogContextListener"/>
<property name="COMMON_PATTERN"
value="%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{80}[%line] %msg%n"/>
<!-- 控制台输出 -->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<!-- 日志输出编码 -->
<encoder>
<pattern>${COMMON_PATTERN}</pattern>
<charset>utf8</charset>yu
</encoder>
</appender>
<!-- 文件输出日志 (文件大小策略进行文件输出,超过指定大小对文件备份)-->
<appender name="FILE-ALL" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 直接通过 property 的方式获取日志路径 -->
<File>${LOG_PATH}/log.log</File>
<rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
<FileNamePattern>
${LOG_PATH}/log-%d{yyyy-MM-dd}.%i.log
</FileNamePattern>
<!--只保留最近 n天的日志-->
<maxHistory>7</maxHistory>
</rollingPolicy>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>200MB</MaxFileSize>
</triggeringPolicy>
<encoder>
<pattern>${COMMON_PATTERN}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="FILE-ALL"/>
</root>
</configuration>