如何在logback自动加载logback.xml之前定义logback变量/属性? [英] how to define logback variables/properties before logback auto-load logback.xml?

查看:166
本文介绍了如何在logback自动加载logback.xml之前定义logback变量/属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我公司有一个环境管理工具,使您可以用Java编程地从环境中查找属性.我想利用此工具配置登录.例如,假设我有一个logback.xml,如下所示(尤其是文件附加器部分):

My company has an environment management tool that enables you to look up properties from the environment programmatically in Java. I want to leverage this tool to configure logback. For example, suppose I have a logback.xml as follows (the file appender section in particular):

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!-- console appender -->
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd/HH:mm:ss.SSS} [%thread] %-5level %logger{20}: %msg%n</pattern>
        </encoder>
    </appender>

    <!-- file appender -->
    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>${LOG_FILE:-/default/log/file/path</file>
        <encoder>
            <pattern>%d{yyyy-MM-dd/HH:mm:ss.SSS} [%thread] %-5level %logger{20}: %msg%n</pattern>
        </encoder>
    </appender>

    <root level="DEBUG">
        <appender-ref ref="CONSOLE" />
        <appender-ref ref="FILE" />
    </root>
</configuration>

因此,在这种情况下,我想从环境(或操作系统,如果可以的话)中查找 LOG_FILE 属性,并在logback加载logback.xml之前将其传递给logback.它会知道 LOG_FILE 的值.那么,我该如何实现呢?顺便说一句,我知道如何以编程方式定义文件追加器,但这不是我想要的.

So, in this case, I want to look up the LOG_FILE property from the environment (or OS, if you will), and pass it to logback before logback loads the logback.xml so that it will know the value of LOG_FILE. So, how can I achieve that? BTW, I know how to define a file appender programmatically, but that's not what I want here.

非常感谢您.

推荐答案

经过一番摸索之后,我决定采用以下解决方案.

After quite a bit of scratching my head, I am settling with the following solution.

首先,将logback.xml放在类路径之外,以便logback不会自动加载任何内容.

First, put logback.xml outside classpath so that logback will not automatically load anything.

第二,将环境中的设置添加到系统属性中,以便在解析logback.xml时可以通过logback查找它们.

Second, add the settings from the environment to system properties so that logback can look them up when parsing logback.xml.

第三,以编程方式在应用程序代码中配置登录.(官方的logback文档具有一个不错的示例.)

Third, programmatically configure logback in the application code. (The official logback documentation has one nice example of that. )

完成.

这篇关于如何在logback自动加载logback.xml之前定义logback变量/属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆