问题描述
是否可以通过环境变量选择是否要使用logback追加器?
我有一个dockerized春季启动微服务,现在添加了ELK堆栈.
到目前为止,一切正常.
但是现在,如果我想在没有ELK堆栈的情况下启动服务,该应用程序将引发一个错误,即它不知道Logstash的主机:
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
这是我的logback.xml文件:
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>
我知道这是一个非常简单的版本,但是我是使用logback/ELK堆栈进行日志记录的新手.
所以有一种方法可以使用yaml文件中的环境变量注入一些东西. active=${LOGBACK_ACTIVE:false}
像我可以使用普罗米修斯指标那样吗?
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?
推荐答案
在您的logback.xml中,当存在命名的JVM参数时,可以使用<if>
构造启用SYSLOG
附加程序.
In your logback.xml you could use the <if>
construct to enable the SYSLOG
appender when a named JVM parameter is present.
在以下示例中,如果使用-Dsyslog
运行应用程序,则将使用SYSLOG
附加程序,否则它将被忽略,并且将使用默认附加程序CONSOLE
:
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>
这需要重复root
声明,但是由于您需要有条件地防止实例化SYSLOG追加器,我认为这可能是您唯一的选择.
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.
这篇关于如何动态(通过env变量)激活/停用logback或logback追加程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!