log4j2.xml中动态读取配置

log4j2支持多种方式的获取值添加进入日志中, 由此衍生出多种lookup~~

可以看下org.apache.logging.log4j.core.lookup包下的代码, 基本上就是官方文档中列的方式, 并可以深入了解框架本身是怎么进行数据获取的, 必要时可自行实现!

支持多种方式动态读取配置, 下面写几个我用过的示例:

1. bundle: ${bundle:BundleName:BundleKey}

bundle: 固定前缀, 标识读取配置文件

BundleName: 配置文件名(如application.properties)

BundleKey: 配置key

eg: ${bundle:application:log.path}

从application.properties中读取key为log.path的值

return ResourceBundle.getBundle(bundleName).getString(bundleKey)

2. sys: ${sys:some.property}或${sys:some.property:-default_value}

sys: 标识读取系统属性, 基本是通过System.getProperty()可读取的属性, jvm参数等

some.property: 属性的key

default_value: 默认值

eg: ${sys:test.log.path:-/opt/logs/}

从系统属性中读取test.log.path属性值, 未取到时默认值为/opt/logs/

3. env基本上和sys一致, 不同点在于读取系统环境变量

官方配置如下

PrefixContext
base64Base64 encoded data. The format is ${base64:Base64_encoded_data}. For example: ${base64:SGVsbG8gV29ybGQhCg==} yields Hello World!.
bundleResource bundle. The format is ${bundle:BundleName:BundleKey}. The bundle name follows package naming conventions, for example: ${bundle:com.domain.Messages:MyKey}.
ctxThread Context Map (MDC)
dateInserts the current date and/or time using the specified format
envSystem environment variables. The formats are ${env:ENV_NAME} and ${env:ENV_NAME:-default_value}.
jndiA value set in the default JNDI Context.
jvmrunargsA JVM input argument accessed through JMX, but not a main argument; see RuntimeMXBean.getInputArguments(). Not available on Android.
log4jLog4j configuration properties. The expressions ${log4j:configLocation} and ${log4j:configParentLocation} respectively provide the absolute path to the log4j configuration file and its parent folder.
mainA value set with MapLookup.setMainArguments(String[])
mapA value from a MapMessage
sdA value from a StructuredDataMessage. The key "id" will return the name of the StructuredDataId without the enterprise number. The key "type" will return the message type. Other keys will retrieve individual elements from the Map.
 
sysSystem properties. The formats are ${sys:some.property} and ${sys:some.property:-default_value}.
 

参考:

自定义lookup: Log4j2研究之lookup_夫礼者的专栏-CSDN博客

Log4j2 Lookup扩展之支持Spring环境变量解析 - 子达的个人空间 - OSCHINA - 中文开源技术交流社区

Log4j – Configuring Log4j 2

————————————————
版权声明:本文为CSDN博主「lackdaylad」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/lackdaylad/article/details/121825056

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值