How can I dynamically (by env variable) activate/deactivate logback or logback appender?

只谈情不闲聊 提交于 2020-02-25 04:22:49

问题


is there a way to choose if I want to have a logback appender or not, via environment variable?

I have a dockerized spring boot Microservice and added now the ELK stack.
That works fine so far.
But now if I want to start my service without ELK stack, the application throws an error, that it doesn't know the host of Logstash:

app | 10:09:23,537 |-ERROR in ch.qos.logback.classic.net.SyslogAppender[SYSLOG] - Could not create SyslogWriter java.net.UnknownHostException: logstash: Name or service not known
app |   at java.net.UnknownHostException: logstash: Name or service not known

Here is my logback.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <appender name="SYSLOG" class="ch.qos.logback.classic.net.SyslogAppender">
        <syslogHost>logstash</syslogHost>
        <port>5000</port>
        <facility>LOCAL1</facility>
        <suffixPattern>[%thread] %logger %msg</suffixPattern>
    </appender>

    <root level="INFO">
        <appender-ref ref="SYSLOG"/>
    </root>

</configuration>

I know this is a very simple version, but I am new in logging with logback/ELK stack.

So is there a way to inject something with an environment variable like in yaml files e.g. active=${LOGBACK_ACTIVE:false} like I can do it with my prometheus metrics?


回答1:


In your logback.xml you could use the <if> construct to enable the SYSLOG appender when a named JVM parameter is present.

In the following example if you run your application with -Dsyslog then your SYSLOG appender will be engaged otherwise it will be ignored and the default appender, CONSOLE, will be engaged:

<if condition='isDefined("syslog")'>
  <then>
    <appender name="SYSLOG" class="ch.qos.logback.classic.net.SyslogAppender">
      ...
    </appender>

    <root level="INFO">
      <appender-ref ref="SYSLOG" />
    </root>
  </then>
  <else>
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
      ...
    </appender>

    <root level="INFO">
      <appender-ref ref="CONSOLE" />
    </root>
  </else>
</if>

This requires some duplication of the root declaration but since you need to conditionally prevent the SYSLOG appender from being instantiated I think this might be your only option.



来源:https://stackoverflow.com/questions/53152471/how-can-i-dynamically-by-env-variable-activate-deactivate-logback-or-logback-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!