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的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<configuration  scan="true" scanPeriod="60 seconds" debug="false">
    <contextName>logback</contextName>
    <property name="log.path" value="log/logback.log" />
    <!--输出到控制台-->
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
       <!-- <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>ERROR</level>
        </filter>-->
        <encoder>
            <pattern>%d{yyyy-MM-dd} %d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <!--输出到文件-->
    <appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${log.path}</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>log/logback.%d{yyyy-MM-dd}.log</fileNamePattern>
        </rollingPolicy>
        <encoder>
            <pattern>%d{yyyy-MM-dd} %d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="warn">
        <appender-ref ref="console" />
        <appender-ref ref="file" />
    </root>

    <!-- logback为java中的包 -->
    <!--<logger name="com.dudu.controller"/>-->
    <!--logback.LogbackDemo:类的全路径 -->
    <!--<logger name="com.dudu.controller.LearnController" level="WARN" additivity="true">-->
        <!--<appender-ref ref="console"/>-->
    <!--</logger>-->

    <!-- 测试环境+开发环境. 多个使用逗号隔开. java -jar xxx.jar spring.profiles.active=prod-->
    <springProfile name="test,dev">
        <logger name="com.example" level="debug" />
    </springProfile>
    <!-- 生产环境. -->
    <springProfile name="prod">
        <logger name="com.example" level="ERROR" />
    </springProfile>

</configuration>

推荐阅读更多精彩内容