按环境配置Logback.xml

时间:2019-02-27 11:17:40

标签: spring-boot configuration environment-variables logback graylog

我有一个类似于下面的logback配置,如您所见,我有一个将所有日志附加到独立日志服务的追加器。

<appender name="digitalGelfAppender" 
 class="de.siegmar.logbackgelf.GelfUdpAppender">
    <graylogHost>testserver.loggingservice.com</graylogHost>
    <graylogPort>1234</graylogPort>
    <useCompression>true</useCompression>
    <layout class="de.siegmar.logbackgelf.GelfLayout">
        <originHost>originHost</originHost>
        <includeRawMessage>false</includeRawMessage>
        <includeMarker>true</includeMarker>
        <includeMdcData>true</includeMdcData>
        <includeCallerData>false</includeCallerData>
        <includeRootCauseData>false</includeRootCauseData>
        <includeLevelName>false</includeLevelName>
        <shortPatternLayout class="ch.qos.logback.classic.PatternLayout">
            <pattern>${log.pattern}</pattern>
        </shortPatternLayout>
        <fullPatternLayout class="ch.qos.logback.classic.PatternLayout">
            <pattern>${log.pattern}</pattern>
        </fullPatternLayout>
        <staticField>application:DAP</staticField>
        <staticField>environment:UAT</staticField>
    </layout>
</appender>

<root level="#logback.loglevel#">
    <appender-ref ref="CONSOLE"/>
    <appender-ref ref="digitalGelfAppender"/>
</root>

我的问题是我需要改变

<graylogHost>testserver.loggingservice.com</graylogHost>
<graylogPort>1234</graylogPort>

根据环境值。因此,这就像生产服务器上的波纹管一样。

<graylogHost>prodserver.loggingservice.com</graylogHost>
<graylogPort>prodPort</graylogPort>

如何按环境将环境值传递到logback.xml文件? 我试图添加这些变量并将其像xml中的属性一样使用。它根本不起作用。

<property name="GRAYLOG_SERVER" value="${graylog-hostname}" />
<property name="GRAYLOG_SERVER_PORT" value="{graylog-port}" />

用法

<graylogHost>${GRAYLOG_SERVER}</graylogHost>
<graylogPort>${GRAYLOG_SERVER_PORT}</graylogPort>

enter image description here

2 个答案:

答案 0 :(得分:0)

嗨,我通过实现从环境的System参数检索数据的侦听器解决了我的问题;

@Controller
public class LoggerContextListener extends ContextAwareBase implements 
LoggerContextListener, LifeCycle {


@Override
public void start() {   
                Map<String, String> property = System.getenv();
                Context context = getContext();
                context.putProperty("GRAYLOG_SERVER", property.get("graylog-hostname"));
                context.putProperty("GRAYLOG_SERVER_PORT", property.get("graylog-port"));
}

之后,我将该侦听器作为contextListener添加到lockback.xml

<contextListener class="com.anadolusigorta.dap.config.DapLoggerContextListener"/> 

然后问题解决了!现在,我的xml可以使用从侦听器设置的这些参数;

<graylogHost>${GRAYLOG_SERVER}</graylogHost>
<graylogPort>${GRAYLOG_SERVER_PORT}</graylogPort>

答案 1 :(得分:0)

您不需要创建侦听器。只需使用以下环境变量即可。

 <graylogHost>${graylog-hostname}</graylogHost>
 <graylogPort>${graylog-port}</graylogPort>