如何在 log4j 的配置文件中为文件附加程序提供环境变量路径

2022-01-15 00:00:00 environment-variables java log4j

我有一个 log4j.xml 配置文件.和一个 RollingFileAppender 我需要提供用于存储日志的文件路径.问题是我的代码将作为可运行的 jar 部署在 Unix 机器上.所以如果我传递这样的参数:

I have a log4j.xml config file. and a RollingFileAppender to which I need to provide file path for storing logs. The problem is my code will be deployed on Unix machine as a runnable jar. So if I pass parameter something like this:

value=logs/messages.log"

它在我的 HOME 目录中创建名为 logs 的文件夹,并将所有消息写入此目录中的文件.

it creates folder named logs inside my HOME directory and writes all the messages to file inside this directory.

我将环境变量设置为某个值.我想使用该变量的路径并在该路径下写入消息.我怎样才能实现它?

I have a environmental variable set to some value. I want to use path of that variable and write messages under that path. How can I achieve it?

我试过用这个:

value="${MY_HOME}/logs/message.log"

但这不起作用.任何人都可以提出解决这个问题的方法吗?

but this does not work. Can anyone suggest a solution for this problem?

推荐答案

解析其配置文件时,表达式${MY_HOME}会被展开为系统属性的值 命名为 MY_HOME,而不是系统 环境变量.两者是有区别的.

When parsing its configuration file, the expression ${MY_HOME} will be expanded to the value of the system property named MY_HOME, not the system environment variable. There's a difference between the two.

要以简洁的方式实现这一点,您必须在 JVM 调用行中添加类似这样的内容:

To achieve this in a clean way, you'll have to add something like this to the JVM invocation line:

-DMY_HOME=$MY_HOME

这将定义 Java 系统属性 MY_HOME 以包含环境变量 MY_HOME 的值.

That would define the Java system property MY_HOME to contain the value of the environment variable MY_HOME.

相关文章