Java日誌元件logback使用:載入非類路徑下的配置檔案並設定定時更新
阿新 • • 發佈:2019-02-04
logback載入非類路徑下的logback配置檔案並設定定時更新
定時重新載入logback配置檔案
logback.xml
<configuration scan="true" scanPeriod="30 seconds">
....
</configuration>
配置說明:
- scan: 設定為true,代表會在指定的時間內重新載入日誌配置檔案
- scanPeriod:當scan=true時,日誌配置檔案會在指定的單位時間內重新載入,預設是每分鐘會過載一次。
- scanPeriod的配置說明:
時間單位:milliseconds, seconds, minutes , hours
eg:
5分鐘: <configuration scan="true" scanPeriod="5 minutes">
1小時: <configuration scan="true" scanPeriod="1 hours">
載入非類路徑下的logback.xml配置檔案
主方法中呼叫如下程式碼:
//logback.xml的路徑名
File file = new File(System.getProperty("user.dir") + "/conf/logback.xml");
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
JoranConfigurator joranConfigurator = new JoranConfigurator();
joranConfigurator.setContext(loggerContext);
loggerContext.reset();
try {
joranConfigurator.doConfigure(file);
} catch (Exception e) {
System.out.println(String.format("Load logback config file error. Message: ", e.getMessage()));
}
StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext);
剝離程式碼為一個類:
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.util.StatusPrinter;
import org.slf4j.LoggerFactory;
import java.io.File;
/**
* Created by xuyh at 2017/11/20 14:32.
*/
public class LogbackInit {
/**
* 設定logback.xml配置檔案並載入
*
* @param configFilepathName 配置檔案路徑名
*/
public static void initLogback(String configFilepathName) {
File file = new File(configFilepathName);
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
JoranConfigurator joranConfigurator = new JoranConfigurator();
joranConfigurator.setContext(loggerContext);
loggerContext.reset();
try {
joranConfigurator.doConfigure(file);
} catch (Exception e) {
System.out.println(String.format("Load logback config file error. Message: ", e.getMessage()));
}
StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext);
}
}
呼叫
//初始化logback日誌配置檔案
LogbackInit.initLogback(System.getProperty("user.dir") + "/conf/logback.xml");