views:

8333

answers:

3

Is it possible to reference system environment variables (as opposed to Java system properties) in a log4j xml configuration file?

I'd like to be able to do something like:

<level value="${env.LOG_LEVEL}" />

and have it get that from the system environment variables, so I can avoid having to pass in so many things with -D parameters.

A: 

I dont think so, you can use java properties though so you should be able to use System.setProperty prior to configuring log4j... Hmm intreguing .. I might have a play with that .. I will try and knock up a sample and report back.

Scott James
+5  A: 

I tried to do that recently and couldn't get it to work. What I ended up doing is sending a variable at startup. So say you have an environment variable called $LOG_LEVEL:

<level value="${log_level}" />

and at startup...

java -Dlog_level=$LOG_LEVEL your_app
Einar
A: 

I think this is not supported, but basically you can do two things to bring in your environment variables:

  1. Use System.setProperty before Log4J gets configured

  2. Convert (your) environment variables to system properties in your launcher

The first option basically boils down to this:

for (Map<String,String>.Entry entry : System.getenv().entrySet()) {
  System.setProperty(entry.getKey(), entry.getValue());
}

... but the question is of course where to put this code. In particular if you're running within some sort of Tomcat container or similar, this might be troublesome.

The other largely depends on your environment. Basically if you have a shell script that starts your app, you can write some shell magic to set all environment variables as properties, or just the ones you need, e.g.:

java -DMY_ENV=$MY_ENV -DMY_OTHER_ENV=$MY_OTHER_ENV -cp ... com.example.Main

It's also possible to alter your server startup scripts to support this, e.g. catalina.sh or similar.

Martin Probst