Java日志组件logback使用:加载非类路径下的配置文件并设置定时更新


 

 

Java日志组件logback使用:加载非类路径下的配置文件并设置定时更新

摘自: https://blog.csdn.net/johnson_moon/article/details/78874499

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/johnson_moon/article/details/78874499

logback加载非类路径下的logback配置文件并设置定时更新

定时重新加载logback配置文件

logback.xml

<configuration  scan="true" scanPeriod="30 seconds">   ....   </configuration>
  • 1
  • 2
  • 3

配置说明: 
- 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">
  • 1
  • 2

加载非类路径下的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);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

剥离代码为一个类:

 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);     } } 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

调用

//初始化logback日志配置文件 LogbackInit.initLogback(System.getProperty("user.dir") + "/conf/logback.xml");

 

posted @ 2018-09-08 23:01  LiuYanYGZ  阅读(1419)  评论(0编辑  收藏  举报