实现日志上下文监听,添加路径变量
package com.x.x.x.listener; 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 s = System.getProperty("user.dir") + "/logs/";
System.setProperty(LOG_PAHT_KEY, s);
Context context = getContext();
context.putProperty(LOG_PAHT_KEY, s);
}
@Override
public void stop() {
}
@Override
public boolean isStarted() {
return false;
}
}
在logbakc.xml文件中指定上下文监听类
在日志配置文件中引入“CustomLogContextListener”(<contextListener class="com.x.x.x.listener.CustomLogContextListener" />)类,
就可以直接通过声明的变量名称使用路径(${LOG_PATH}),LOG_PATH就是在CustomLogContextListener类中指定的变量名称
<?xml version="1.0" encoding="UTF-8" ?>
<configuration scan="true" scanPeriod="20 seconds" debug="false">
<contextListener class="com.x.x.x.listener.CustomLogContextListener" />
<property name="PROJECT_NAME" value="xxxx" />
<!-- 控制台输出日志 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX} ${PROJECT_NAME} [%thread] %-5level %logger{80}[%line] %msg%n</pattern>
</layout>
</appender> <!-- 文件输出日志 (文件大小策略进行文件输出,超过指定大小对文件备份)-->
<appender name="FILE-debug" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>DEBUG</level>
</filter>
<File>${LOG_PATH}/${PROJECT_NAME}_debug.log</File>
<rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
<FileNamePattern>${LOG_PATH}/${PROJECT_NAME}_debug.%i.log
</FileNamePattern>
<MinIndex>1</MinIndex>
<MaxIndex>10</MaxIndex>
</rollingPolicy>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>10MB</MaxFileSize>
</triggeringPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX} ${PROJECT_NAME} [%thread] %-5level %logger{80}[%line] %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT"/>
<appender-ref ref="FILE-debug" />
<appender-ref ref="FILE-error" />
</root>
</configuration>