还有一种从配置文件中读取环境变量的替代方法。您可以将自定义变量放入使用上下文侦听器登录上下文。
日志返回.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true" scan="true" scanPeriod="30 seconds">
<!-- THIS IS OUR CUSTOM CONTEXT LISTENER -->
<contextListener class="com.myapp.logging.listener.LoggerStartupListener"/>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%-5level] %d{HH:mm:ss.SSS} [%.6thread] %logger - %msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<appender name="FILEOUT" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${MY_HOME}/${LOG_FILE}.log</file>
<append>true</append>
<!-- Support multiple-JVM writing to the same log file -->
<prudent>true</prudent>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- Daily rollover -->
<fileNamePattern>${MY_HOME}/${LOG_FILE}.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- Keep 7 days' worth of history -->
<maxHistory>7</maxHistory>
</rollingPolicy>
<encoder>
<pattern>[%-5level] %d{HH:mm:ss.SSS} [%.6thread] %logger - %msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT"/>
<appender-ref ref="FILEOUT"/>
</root>
</configuration>
LoggerStartupListener.java
package com.myapp.logging.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 LoggerStartupListener extends ContextAwareBase implements LoggerContextListener, LifeCycle {
private static final String DEFAULT_LOG_FILE = "MYAPP";
private boolean started = false;
@Override
public void start() {
if (started) return;
String userHome = System.getProperty("user.home");
String logFile = System.getProperty("log.file"); // log.file is our custom jvm parameter to change log file name dynamicly if needed
logFile = (logFile != null && logFile.length() > 0) ? logFile : DEFAULT_LOG_FILE;
Context context = getContext();
context.putProperty("MY_HOME", userHome);
context.putProperty("LOG_FILE", logFile);
started = true;
}
@Override
public void stop() {
}
@Override
public boolean isStarted() {
return started;
}
@Override
public boolean isResetResistant() {
return true;
}
@Override
public void onStart(LoggerContext context) {
}
@Override
public void onReset(LoggerContext context) {
}
@Override
public void onStop(LoggerContext context) {
}
@Override
public void onLevelChange(Logger logger, Level level) {
}
}