简体   繁体   中英

Redirect System.out.println to Log4J, while keeping class name information

I have some libraries that are calling System.out.println on me, I'd like to redirect them through log4j or commons logging. But in particular I'd like to keep the fully-qualified-classname so I know what component generated the logs.

Is there a nice, orderly way to accomplish this?


UPDATE: After accomplishing this I posted the code here:
http://www.bukisa.com/articles/487009_java-how-to-redirect-stderr-and-stdout-to-commons-logging-with-the-calling-class

The only way I can think of would be to write your own PrintStream implementation which created a stack trace when the println method was called, in order to work out the class name. It would be pretty horrible, but it should work... proof of concept sample code:

import java.io.*;

class TracingPrintStream extends PrintStream {
  public TracingPrintStream(PrintStream original) {
    super(original);
  }

  // You'd want to override other methods too, of course.
  @Override
  public void println(String line) {
    StackTraceElement[] stack = Thread.currentThread().getStackTrace();
    // Element 0 is getStackTrace
    // Element 1 is println
    // Element 2 is the caller
    StackTraceElement caller = stack[2];
    super.println(caller.getClassName() + ": " + line);
  }
}

public class Test {
  public static void main(String[] args) throws Exception {
    System.setOut(new TracingPrintStream(System.out));
    System.out.println("Sample line");
  }
}

(In your code you would make it log to log4j instead of course... or possibly as well.)

If you can modify the source code, then have a look at the Eclipse Plugin Log4E . It provides a function to convert System.out.println into logger statements (and many other cool stuff dealing with logging).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM