a way to use log4j pass values like java -DmyEnvVar=A_VALUE to my code

Posted by raticulin on Stack Overflow See other posts from Stack Overflow or by raticulin
Published on 2010-03-15T16:21:01Z Indexed on 2010/03/15 20:49 UTC
Read the original article Hit count: 195

Filed under:
|

I need to pass some value to enable certain code in may app (in this case is to optionally enable writing some stats to a file in certain conditions, but it might be anything generally).

My java app is installed as a service. So every way I have thought of has some drawbacks:

  1. Add another param to main(): cumbersome as customers already have the tool installed, and the command line would need to be changed every time.
  2. Adding java -DmyEnvVar=A_VALUE to my command line: same as above.
  3. Set an environment variable: service should at least be restarted, and even then you must take care of what user is the service running under etc.
  4. Adding the property in the config file: I prefer not to have this visible on the config file so the user does not see it, it is something for debugging etc.

So I thought maybe there is some way (or hack) to use log4j loggers to pass that value to my code. I have thought of one way already, although is very limited:

  1. Add a dummy class to my codebase com.dummy.DevOptions

    public class DevOptions { public static final Logger logger = Logger.getLogger(DevOptions.class);

  2. In my code, use it like this:

    if (DevOptions.logger.isInfoEnabled()){ //do my optional stuff } //... if (DevOptions.logger.isDebugEnabled()){ //do other stuff }

This allows me to use discriminate among various values, and I could increase the number by adding more loggers to DevOptions. But I wonder whether there is a cleaner way, possibly by configuring the loggers only in log4j.xml??

© Stack Overflow or respective owner

Related posts about java

Related posts about log4j