How to give environmental variable path for file a

2019-01-10 20:42发布

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"

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?

I had tried using this:

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

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

9条回答
▲ chillily
2楼-- · 2019-01-10 20:58

To dynamically change a variable you can do something like this:

String value = System.getenv("MY_HOME");
Properties prop = new Properties("log4j.properties"); 
prop.put("MY_HOME", value); // overwrite with value from environment
PropertyConfigurator.configure(prop);
查看更多
Explosion°爆炸
3楼-- · 2019-01-10 21:00

Since you are using unix you can use a path like this.

  /home/Production/modulename/logs/message.log

path should start with /

查看更多
成全新的幸福
4楼-- · 2019-01-10 21:01

Log4j entry

#- File to log to and log format

log4j.appender.file.File=${LOG_PATH}/mylogfile.log

Java program
String log4jConfPath        = "path/log4j.properties";
File log4jFile              = new File(log4jConfPath);
if (log4jFile.exists()) {
    System.setProperty("LOG_PATH", "c:/temp/");
    PropertyConfigurator.configure(log4jFile.getAbsolutePath());
    logger.trace("test123");
}
查看更多
forever°为你锁心
5楼-- · 2019-01-10 21:02

you CAN give it environment variables. Just preppend env: before the variable name, like this:

value="${env:MY_HOME}/logs/message.log"
查看更多
Explosion°爆炸
6楼-- · 2019-01-10 21:05

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.

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

-DMY_HOME=$MY_HOME

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

查看更多
Anthone
7楼-- · 2019-01-10 21:07

Maybe... :

datestamp=yyyy-MM-dd/HH:mm:ss.SSS/zzz
layout=%d{${datestamp}} ms=%-4r [%t] %-5p %l %n%m %n%n

# infoFile 
log4j.appender.infoFile=org.apache.log4j.RollingFileAppender
log4j.appender.infoFile.File=${MY_HOME}/logs/message.log
log4j.appender.infoFile.layout=org.apache.log4j.PatternLayout
log4j.appender.infoFile.layout.ConversionPattern=${layout}
查看更多
登录 后发表回答