LOGBACK手动加载配置文件

在项目中经常会使用到直接用main方法启动一个进程,在日志控制方面使用的logback,main方法在启动后log的配置并没有生效

解决方案

package com.example.exe.loggerconfig;

import java.io.File;
import java.io.IOException;

import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.util.StatusPrinter;
/**
 * @author create by yingjie.chen on 2018/5/17.
 * @version 2018/5/17 16:08
 */
public class LogBackConfigLoader {
    public static void load (String externalConfigFileLocation) throws IOException, JoranException{
        LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();

        File externalConfigFile = new File(externalConfigFileLocation);
        if(!externalConfigFile.exists()){
            throw new IOException("Logback External Config File Parameter does not reference a file that exists");
        }else{
            if(!externalConfigFile.isFile()){
                throw new IOException("Logback External Config File Parameter exists, but does not reference a file");
            }else{
                if(!externalConfigFile.canRead()){
                    throw new IOException("Logback External Config File exists and is a file, but cannot be read.");
                }else{
                    JoranConfigurator configurator = new JoranConfigurator();
                    configurator.setContext(lc);
                    lc.reset();
                    configurator.doConfigure(externalConfigFileLocation);
                    StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
                }
            }
        }
    }
}
public class Exe {

    private static final Logger logger = LoggerFactory.getLogger(Exe.class);

    public static void main(String[] args) throws IOException, JoranException {
        LogBackConfigLoader.load(Exe.class.getClassLoader().getResource("logback-spring.xml").getPath());
        //代码
    }
}
  • logback的配置文件


    logback
    
    
    
       
        
            %d{yyyy-MM-dd} %d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %msg%n
        
    

    
    
        ${log.path}
        
            log/logback.%d{yyyy-MM-dd}.log
        
        
            %d{yyyy-MM-dd} %d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %msg%n
        
    

    
        
        
    

    
    
    
    
        
    

    
    
        
    
    
    
        
    


你可能感兴趣的:(LOGBACK手动加载配置文件)