如何在Logback中隨時更改日誌文件路徑?使用Logback隨時更改日誌文件路徑屬性
在我的Web應用程序中,用戶可以更改某些電子郵件附件將被保存和處理的位置。用戶可以訪問這個路徑,看看處理後是否發生了一些錯誤,所以我想在這個路徑中創建一個日誌文件。要做到這一點,我已經嘗試使用這種配置的logback:
<configuration debug="true" scan="true" scanPeriod="30 seconds">
<property scope="context" resource="com/hrgi/configuracoes/recuperadorNFe.properties" />
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%date{dd/MM/yyyy;HH:mm:ss} [%thread] %-5level %logger - %msg%n %ex{full}</pattern>
</encoder>
</appender>
<appender name="importador" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${recuperadorNFe.diretorioDeArmazenamento}/logs/importador.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${recuperadorNFe.diretorioDeArmazenamento}/logs/%d{yyyy/MM}/importador-%d{dd}.log</fileNamePattern>
</rollingPolicy>
<encoder>
<pattern>(%date{dd/MM/yyyy;HH:mm:ss} [%-5level]) -> %msg%n %nopex</pattern>
</encoder>
</appender>
<logger name="com.hrgi.nfe" level="info">
<appender-ref ref="importador" />
</logger>
<root level="info">
<appender-ref ref="console" />
</root>
</configuration>
就像你看到的,我希望爲重啓記錄儀背景這樣或許可以看出,屬性文件的內容被更改,並加載正確的價值觀。不起作用:
private void restartLogContext(){
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
loggerContext.stop();
loggerContext.start();
StatusPrinter.print(loggerContext);
}
所以我試過刪除記錄器appender並創建一個新的。至少在日誌文件中的新路徑創建,但記錄在控制檯發生的事情:
private void restartLog(){
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
Logger logbackLogger = loggerContext.getLogger("com.hrgi.nfe");
logbackLogger.detachAndStopAllAppenders();
TimeBasedRollingPolicy policy= new TimeBasedRollingPolicy();
policy.setContext(loggerContext);
policy.setFileNamePattern(modeloPopup.getConfiguracoes().getDiretorioDeArmazenamento()+"/logs/%d{yyyy/MM}/importador-%d{dd}.log");
RollingFileAppender fileAppender = new RollingFileAppender();
fileAppender.setContext(loggerContext);
fileAppender.setName("importador");
fileAppender.setFile(modeloPopup.getConfiguracoes().getDiretorioDeArmazenamento()+"/logs/importador.log");
fileAppender.setRollingPolicy(policy);
policy.setParent(fileAppender);
PatternLayoutEncoder encoder = new PatternLayoutEncoder();
encoder.setContext(loggerContext);
encoder.setPattern("(%date{dd MMM yyyy;HH:mm:ss} [%-5level]) -> %msg%n %nopex");
encoder.start();
fileAppender.setEncoder(encoder);
fileAppender.start();
logbackLogger.addAppender(fileAppender);
StatusPrinter.print(loggerContext);
}
有人能解釋我什麼,我做錯了什麼?
感謝彼得,我已經延長了TimeBasedRollingPolicy並覆蓋翻轉和isTriggeringEvent,現在我可以更改dinamically日誌文件路徑... – brevleq