有一种从配置文件读取环境变量的替代方法。 您可以使用上下文侦听器将自定义变量放回登录上下文。
logback.xml
[%-5level] %d{HH:mm:ss.SSS} [%.6thread] %logger - %msg%n
UTF-8
${MY_HOME}/${LOG_FILE}.log
true
true
${MY_HOME}/${LOG_FILE}.%d{yyyy-MM-dd}.log
7
[%-5level] %d{HH:mm:ss.SSS} [%.6thread] %logger - %msg%n
UTF-8
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) {
}
}