views:

51

answers:

2

In our product we use a number of external libraries. We do our logging with log4j, and most libraries do so as well, so we get most of the messages in our appenders fine.

But there are several libraries that just use System.out and System.err. So I am looking for a way to redirect System.out and System.err to our log4j appenders for a specific jar only, the other libraries that use log4j should not be affected, and those sometimes print to System.out and System.err too, and these messages should still go there.

Is this somehow possible?

+1  A: 

Hypothesis - Never tried

  • Create custom log level. Level should be bellow Level.ALL
  • Override std print stream to your own stream. Perform both console and log output with your custom level
  • Create new category for you required package and set its logging level to your custom logging level

Helpful sample code

http://blogs.sun.com/nickstephen/entry/java_redirecting_system_out_and

and

http://stackoverflow.com/questions/1200175/log4j-redirect-stdout-to-dailyrollingfileappender/1370033#1370033

Faheem
A: 

Not sure if you can get the output stream to log4j appender but if you just want to send it to a log file, you can direct system.out to a file as below :



 File file  = new File("my.log");
 PrintStream printStream = new PrintStream(new FilleOutputStream(file));
 System.setOut(printStream);


You can do the same for System.err

I like Faheem's first link, it has solution to roll the file.

Ramp