开发者

slf4j/log4j: disabling console output when console is inappropriate

I'm starting a JVM programmatically with ProcessBuilder. For clarity let's call the JVM that uses ProcessBuilder JVM A and the one it starts JVM B. JVM B uses slf4j/log4j for logging.

The issue here is that the class I execute in JVM B is one that I sometimes run in a debugger, where it's helpful to have console output.

If I run JVM B with ProcessBuilder, however, then I don't want console output, because that requires JVM A to read the process's output or JVM B hangs.

Is there a way to control slf4j or log4j from within JVM B so that if my main class in JVM deems it's inappropriate to use a console for logging, it doesn开发者_StackOverflow't try to do so? (e.g. it disables console-based appenders) I would rather not have to maintain separate log4j.configuration files, although I'll do that if I need to do so.

e.g. in my main class

static {
   if (shouldntUseConsole())
   {
      ?????
   }
}

I can figure out how to implement shouldntUseConsole(), but I don't know what to put for ?????.


First of all, slf4j is an API with an implementation behind it, which here is log4j so it is the implementation you need to configure, not slf4j.

The usual way to have different logging behaviors is to have different configuration files. For log4j you can either have different file sets for A and B, with two different log4j.properties files, or you can have one configuration set the "log4j.configuration" system property to the name of another configuration file.

See "Default initialization procedure" section in http://logging.apache.org/log4j/1.2/manual.html for details.


You could use two log4j files with the property configurator object. Your code would look something like this :

   import org.apache.log4j.PropertyConfigurator;

if(shouldntUseConsole())
 {
   PropertyConfigurator.configure("NotConsoleLog4J.props");
 }


 else
    { 
      PropertyConfigurator.configure("ConsoleLog4J.props");
    }

Here is the appropriate javadoc: http://logging.apache.org/log4j/1.2/apidocs/index.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜