Redirect System.out and System.err

2019-01-14 16:55发布

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?

4条回答
等我变得足够好
2楼-- · 2019-01-14 17:27

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.

查看更多
够拽才男人
3楼-- · 2019-01-14 17:32

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.

查看更多
迷人小祖宗
4楼-- · 2019-01-14 17:34

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.

查看更多
女痞
5楼-- · 2019-01-14 17:37

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.

查看更多
登录 后发表回答