Log4J2 属性替换 - 默认 [英] Log4J2 property substitution - default

查看:39
本文介绍了Log4J2 属性替换 - 默认的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道是否有任何方法可以为 LOG4J 中的属性替换提供默认值?

I just wonder if there is any way to provide default value for property substitution in LOG4J?

我想在 java 系统属性中传递文件路径,然后将它与${env:mySystemProperty}"一起使用.但是如果开发者忘记设置这个属性怎么办?然后我想在 log4j2.xml 中定义一些有意义的默认值.

I want to pass file path in java system property and then use it with "${env:mySystemProperty}". But what if developer forgets to set this property? Then I would like to have some meaningful default value defined in log4j2.xml.

知道如何实现此功能吗?

Any idea how to achieve this functionality?

env 替换对我不起作用:

The env substitution does not work for me:

standalone.conf

standalone.conf

-DoauthLoginLogPath=/path/oauth2.log

log4j2.xml

<Appender type="File" name="File" fileName="${env:oauthLoginLogPath}" immediateFlush="true">
<Appender type="File" name="File" fileName="${sys:oauthLoginLogPath}" immediateFlush="true">

我可以在 wildfly 控制台中看到该属性,我重新启动了服务器,但无法完成.

I can see in wildfly console the property, I restarted server but I cannot get it done.

推荐答案

默认属性映射

查看 http://logging.apache.org/log4j/2.x/manual/configuration.html#PropertySubstitution您可以在配置文件中指定默认属性映射.采用这种形式:

Looking at http://logging.apache.org/log4j/2.x/manual/configuration.html#PropertySubstitution you can specify a default property map in the configuration file. That takes this form:

<Configuration status="debug">
  <Properties>
    <Property name="oauthLoginLogPath">default/location/of/oauth2.log</Property>
  </Properties>
  ...
  <Appenders>
    <Appender type="File" name="File" fileName="${sys:oauthLoginLogPath}">
    ....
</Configuration

然后,如果您使用系统属性 -DoauthLoginLogPath=/path/oauth2.log 启动您的应用程序,则将首先在系统属性中查找 File appender fileName 值,但如果失败,它将回退到 log4j2.xml 配置文件顶部的 Properties 部分中定义的属性.

Then, if you start your app with system property -DoauthLoginLogPath=/path/oauth2.log, the File appender fileName value will first be looked up in system properties, but if that fails, it will fall back to the property defined in the Properties section at the top of the log4j2.xml configuration file.

内联

第二种方法是内联提供默认值:

A second way is to provide the default value inline:

<Appender type="File" name="File" fileName="${sys:oauthLoginLogPath:-default/location/of/oauth2.log}">

通常所有 Log4j2 查找都遵循此模式:${type:key:-defaultValue}.

Generally all Log4j2 lookups follow this pattern: ${type:key:-defaultValue}.

环境与系统

顺便说一下,env 前缀是用于环境变量(如 Windows 上的 %PATH%),与 sys 无关,后者是 Java 系统属性.另见 http://logging.apache.org/log4j/2.x/manual/lookups.html

By the way, the env prefix is for environment variables (like %PATH% on Windows), and is not related to sys, which is Java system properties. See also http://logging.apache.org/log4j/2.x/manual/lookups.html

这篇关于Log4J2 属性替换 - 默认的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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