16

I have some legacy code (or rather some code we don't control but we have to use) that writes a lot of statements to system.out/err.

At the same time, we are using a framework that uses a custom logging system wrapped around log4j (again, unfortunately we don't control this).

So I'm trying to redirect the out and err stream to a custom PrintStream that will use the logging system. I was reading about the System.setLog() and System.setErr() methods but the problem is that I would need to write my own PrintStream class that wraps around the logging system in use. That would be a huge headache.

Is there a simple way to achieve this?

Stephan
  • 41,764
  • 65
  • 238
  • 329
Giovanni Botta
  • 9,626
  • 5
  • 51
  • 94

4 Answers4

14

Just to add to Rick's and Mikhail's solutions, which are really the only option in this scenario, I wanted to give an example of how creating a custom OutputStream can potentially lead to not so easy to detect/fix problems. Here's some code:

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import org.apache.log4j.Logger;

public class RecursiveLogging {
  /**
   * log4j.properties file:
   * 
   * log4j.rootLogger=DEBUG, A1
   * log4j.appender.A1=org.apache.log4j.ConsoleAppender
   * log4j.appender.A1.layout=org.apache.log4j.PatternLayout
   * log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
   * 
   */
  public static void main(String[] args) {
    // Logger.getLogger(RecursiveLogging.class).info("This initializes log4j!");
    System.setOut(new PrintStream(new CustomOutputStream()));
    System.out.println("This message causes a stack overflow exception!");
  }
}

class CustomOutputStream extends OutputStream {
  @Override
  public final void write(int b) throws IOException {
    // the correct way of doing this would be using a buffer
    // to store characters until a newline is encountered,
    // this implementation is for illustration only
    Logger.getLogger(CustomOutputStream.class).info((char) b);
  }
}

This example shows the pitfalls of using a custom output stream. For simplicity the write() function uses a log4j logger, but this can be replaced with any custom logging facility (such as the one in my scenario). The main function creates a PrintStream that wraps a CustomOutputStream and set the output stream to point to it. Then it executes a System.out.println() statement. This statement is redirected to the CustomOutputStream which redirects it to a logger. Unfortunately, since the logger is lazy initialized, it will acquire a copy of the console output stream (as per the log4j configuration file which defines a ConsoleAppender) too late, i.e., the output stream will point to the CustomOutputStream we just created causing a redirection loop and thus a StackOverflowError at runtime.

Now, with log4j this is easy to fix: we just need to initialize the log4j framework before we call System.setOut(), e.g., by uncommenting the first line of the main function. Luckily for me, the custom logging facility I have to deal with is just a wrapper around log4j and I know it will get initialized before it's too late. However, in the case of a totally custom logging facility that uses System.out/err under the cover, unless the source code is accessible, it's impossible to tell if and where direct calls to System.out/err are performed instead of calls to a PrintStream reference acquired during initialization. The only work around I can think of for this particular case would be to retrieve the function call stack and detect redirection loops, since the write() functions should not be recursive.

Giovanni Botta
  • 9,626
  • 5
  • 51
  • 94
6

You should not need to wrap around the custom logging system you are using. When the application initializes, just create a LoggingOutputStream and set that stream on the System.setOut() and System.setErr() methods with the logging level that you desire for each. From that point forward, any System.out statements encountered in the application should go directly to the log.

mightyrick
  • 910
  • 4
  • 6
  • What's LoggingOutputStream? How's that gonna help me use the (quite crappy) custom logging system I'm dealing with? – Giovanni Botta Feb 06 '13 at 14:58
  • The LoggingOutputStream would be a stream class that you write and set on the System.setOut() and System.setErr() methods. How it helps you use your logging system is that it allows for the sending of all System.out() to log without having to rewrite your application or the existing logging facilities. – mightyrick Feb 06 '13 at 15:50
  • Oh, ok so it's the same thing Mikhail suggested. Thanks! – Giovanni Botta Feb 06 '13 at 15:51
  • So the only problem now is a chicken and egg type of problem: what if some unknown part of the external logging facility uses a direct call to System.out/err? In this case the call will be redirected recursively causing stack overflow. As I said, the logging library I am working with uses a wrapper around log4j (hot mess!), so as long as log4j is initialized *before* I redirect out/err I should be fine. Is there a way to catch such infinite recursion problem (well I know I could look at the call stack...)? – Giovanni Botta Feb 08 '13 at 21:20
  • I'm not sure how an infinite loop could possibly happen. Even if the external logging facility uses System.out, it will just go straight to the log. Are you getting a stack overflow error? Or are you just wondering if it is possible? – mightyrick Feb 10 '13 at 16:45
  • You can absolutely make it happen, even with log4j. For example, if you design your custom OutputStream to write to a log4j logger and call System.setOut() *before* you call Logger.getLogger(), then the logger will try be created using the System.out stream which is now the custom one, causing an infinite redirection loop. – Giovanni Botta Feb 11 '13 at 16:10
6

Take a look at the constructors provided by PrintStream. You can pass the logging framework OutputStream directly to PrintStream, then set the System.out and System.err to use the PrintStream.

Edit: Here's a simple test case:

public class StreamTest
{
    public static class MyOutputStream extends FilterOutputStream
    {
        public MyOutputStream(OutputStream out)
        {
            super(out);
        }

        @Override
        public void write(byte[] b, int off, int len) throws IOException
        {
            byte[] text = "MyOutputStream called: ".getBytes();         
            super.write(text, 0, text.length);
            super.write(b, off, len);
        }
    }

    @Test   
    public void test()
    {       
        //Any OutputStream-implementation will do for PrintStream, probably
        //you'll want to use the one from the logging framework
        PrintStream outStream = new PrintStream(new MyOutputStream(System.out), true);  //Direct to MyOutputStream, autoflush
        System.setOut(outStream); 

        System.out.println("");
        System.out.print("TEST");
        System.out.println("Another test");
    }
}

The output is:

MyOutputStream called: 
MyOutputStream called: TESTMyOutputStream called: Another testMyOutputStream called: 

The second line has an "empty" call (MyOutputStream called: -output and then nothing after it), because println will first pass the Another test -string to the write-method, and then calls it again with a line feed.

esaj
  • 15,875
  • 5
  • 38
  • 52
  • Too bad the framework doesn't use an OutputStream but some custom class that under the cover uses log4j. It's pretty much a mess I'm trying to work around. – Giovanni Botta Feb 06 '13 at 14:52
3

Just write your own OutputStream and then wrap it into standard PrintStream. OutputStream has only 1 method that must be implemented and another that is worth to be overridden for performance reasons.

The only trick is to slice stream of bytes into separate log messages, e.g. by '\n', but this is not too hard to implement too.

Mikhail Vladimirov
  • 13,572
  • 1
  • 38
  • 40
  • Yeah that's what I was thinking about doing. Which one is the other method worth overriding? – Giovanni Botta Feb 06 '13 at 14:52
  • Method `write (int)` must be overridden, `write (byte [], int, int)` worth to be. – Mikhail Vladimirov Feb 06 '13 at 14:55
  • Actually it's a little more complicated than that. Say my application has two threads using my legacy code. I want to be able to log System.out from each thread to a different OutputStream, but this doesn't seem to be easily workable (http://stackoverflow.com/questions/10015182/in-a-multithreaded-java-program-does-each-thread-have-its-own-copy-of-system-ou). Ideas? – Giovanni Botta Feb 06 '13 at 16:23
  • It is easy enough. Just use `Thread.currentThread()` in your OutputStream implementation to know what thread it is. – Mikhail Vladimirov Feb 06 '13 at 17:47
  • Yeah, that means using a singleton stream and having a map from thread to logger. The only problem is the lifetime of the objects stored: when the thread is done, it should be removed from the map so that all the resources associated to the logger can be freed. – Giovanni Botta Feb 06 '13 at 18:27