Log4j2.xml中动态读取配置
Posted 张志翔 ̮
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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一致, 不同点在于读取系统环境变量
官方配置如下
Prefix | Context |
---|---|
base64 | Base64 encoded data. The format is $base64:Base64_encoded_data. For example: $base64:SGVsbG8gV29ybGQhCg== yields Hello World!. |
bundle | Resource bundle. The format is $bundle:BundleName:BundleKey. The bundle name follows package naming conventions, for example: $bundle:com.domain.Messages:MyKey. |
ctx | Thread Context Map (MDC) |
date | Inserts the current date and/or time using the specified format |
env | System environment variables. The formats are $env:ENV_NAME and $env:ENV_NAME:-default_value. |
jndi | A value set in the default JNDI Context. |
jvmrunargs | A JVM input argument accessed through JMX, but not a main argument; see RuntimeMXBean.getInputArguments(). Not available on android. |
log4j | Log4j configuration properties. The expressions $log4j:configLocation and $log4j:configParentLocation respectively provide the absolute path to the log4j configuration file and its parent folder. |
main | A value set with MapLookup.setMainArguments(String[]) |
map | A value from a MapMessage |
sd | A 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. |
sys | System properties. The formats are $sys:some.property and $sys:some.property:-default_value. |
参考:
自定义lookup: Log4j2研究之lookup_夫礼者的专栏-CSDN博客
Log4j2 Lookup扩展之支持Spring环境变量解析 - 子达的个人空间 - OSCHINA - 中文开源技术交流社区
以上是关于Log4j2.xml中动态读取配置的主要内容,如果未能解决你的问题,请参考以下文章