Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 483
m1well Avatar asked Oct 17 '22 11:10

m1well


1 Answers

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.

like image 176
glytching Avatar answered Oct 31 '22 17:10

glytching