Take the 2-minute tour ×

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:

share|improve this question

2 Answers 2

up vote 11 down vote accepted

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) {

  // You'd want to override other methods too, of course.
  public void println(String line) {
    // 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 {
    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.)

share|improve this answer
Well, it was tricky, a few pitfalls along the way, but doable. Thanks for the info. I posted the code here: bukisa.com/articles/… –  David Parks Apr 20 '11 at 4:27

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).

share|improve this answer
Nope, they're 3rd party libraries that are doing it. It's not worth changing their code, and requesting them to do it may take years. –  David Parks Apr 19 '11 at 7:10
The only thing that comes to mind when you can't modify source code is byte code manipulation but you need to intercept the class loading process and create a new class file with the System.out replaced with Logger statements, but that sounds way to intensive –  Liviu T. Apr 19 '11 at 7:18
scratch that, Jon Skeet came to the rescue :) –  Liviu T. Apr 19 '11 at 7:28

Your Answer


