Logback指定自定义配置文件

slf4j + Logback算是现在使用最广的日志记录方式,logback作为log4j的加强版,也是有很多新特性。logback默认读取配置文件为/src/resource/logback.xml,一般来说这样是没有问题的,但是,当需要需改配置的时候,就会比较麻烦,所以我们一般都会把配置文件放到一个固定的地方,这样每次需要改变配置的时候,直接改就可以了。

每个项目可能会有多个module,每个module有自己的配置文件,配置文件命名规则建议为logback-${module}.xml。下面的代码展示了如何读取PIF_CONF目录下的配置文件,如果该文件不存在,则使用resource目录下的配置文件,好了,来看代码:

 public static void loadLogbackConfig(String externalFileName) throws IOException, JoranException {
         //use PIF_CONF configuration file
        String dirPath = System.getenv("PIF_CONF");
        dirPath = dirPath.endsWith("/") ? dirPath : dirPath + "/";
        LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();

        File externalConfigFile = new File(dirPath + externalFileName);

        //use classpath configuration file
        if (!externalConfigFile.exists()) {
            logger.info("External config file not find. Use classpath config file.");
            Resource resource = new ClassPathResource(externalFileName);
            externalConfigFile = resource.getFile();
        }

        if (!externalConfigFile.exists()) {
            throw new FileNotFoundException(externalConfigFile.getPath());
        } 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(externalConfigFile.getPath());
                StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
            }
        }
    }

好了,代码清楚了,那么,该在哪里调用呢?可以在应用加载配置文件之前,比如WebAppInitializer中。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,933评论 18 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,954评论 6 342
  • 在项目开发过程中,我们可以通过 debug 查找问题。而在线上环境我们查找问题只能通过打印日志的方式查找问题。因此...
    Java架构阅读 3,501评论 2 41
  • feisky云计算、虚拟化与Linux技术笔记posts - 1014, comments - 298, trac...
    不排版阅读 3,917评论 0 5
  • 在应用程序中添加日志记录总的来说基于三个目的:监视代码中变量的变化情况,周期性的记录到文件中供其他应用进行统计分析...
    时待吾阅读 5,082评论 1 13