75

I have a java app that uses log4j.

Config:

log4j.rootLogger=info, file

log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.File=${user.home}/logs/app.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d [%t] %c %p %m%n

So all the log statements are correctly appended to the file, but i am losing stdout and stderr. How do i redirect exception stack traces and sysouts to the daily rolled file ?

letronje
  • 9,002
  • 9
  • 45
  • 53

10 Answers10

110
// I set up a ConsoleAppender in Log4J to format Stdout/Stderr
log4j.rootLogger=DEBUG, CONSOLE
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=[%t] %-5p %c - %m%n


// And I call this StdOutErrLog.tieSystemOutAndErrToLog() on startup

public class StdOutErrLog {

    private static final Logger logger = Logger.getLogger(StdOutErrLog.class);

    public static void tieSystemOutAndErrToLog() {
        System.setOut(createLoggingProxy(System.out));
        System.setErr(createLoggingProxy(System.err));
    }

    public static PrintStream createLoggingProxy(final PrintStream realPrintStream) {
        return new PrintStream(realPrintStream) {
            public void print(final String string) {
                realPrintStream.print(string);
                logger.info(string);
            }
        };
    }
}
skaffman
  • 398,947
  • 96
  • 818
  • 769
Michael S.
  • 1,124
  • 1
  • 7
  • 3
  • 8
    this works with exceptions, but it doesn't capture all output written to stdout. For example if you called System.out.print(5); it would bypass the proxy print stream. as well, even with exceptions this will end up printing extra blank lines to stderr if you do someException.printStackTrace() – sbridges Aug 04 '11 at 00:01
  • 3
    @sbridges you can just override more of the methods if you require. For example the `printStackTrace` calls the `println(Object o)` method which you could also override to eliminate those nasty blank lines. – tysonjh Sep 17 '13 at 22:25
  • I learned much more than logging while examine your code. brilliant! Thank you. – Lalith J. Aug 13 '14 at 16:59
  • Does this work for the whole Tomcat instance or only the web app that has this class? – Dojo Sep 19 '14 at 07:37
  • If you use this method, I think you are best off implementing all the methods in PrintStream. If you want to be lazy, you can use Dario's answer that implements OutputStream. Just note the caveat with that method that I noted in the comments. – Mike Pone Dec 23 '14 at 21:30
  • Will this go to infinite loop if logback is pointing to standard out? – AlienOnEarth May 17 '16 at 15:37
13

I picked up the idea from Michael S., but like mentioned in one comment, it has some problems: it doesn't capture everything, and it prints some empty lines.

Also I wanted to separate System.out and System.err, so that System.out gets logged with log level 'INFO' and System.err gets logged with 'ERROR' (or 'WARN' if you like).

So this is my solution: First a class that extends OutputStream (it's easier to override all methods for OutputStream than for PrintStream). It logs with a specified log level and also copies everything to another OutputStream. And also it detects "empty" strings (containing whitespace only) and does not log them.

import java.io.IOException;
import java.io.OutputStream;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

public class LoggerStream extends OutputStream
{
private final Logger logger;
private final Level logLevel;
private final OutputStream outputStream;

public LoggerStream(Logger logger, Level logLevel, OutputStream outputStream)
{
    super();

    this.logger = logger;
    this.logLevel = logLevel;
    this.outputStream = outputStream;
}

@Override
public void write(byte[] b) throws IOException
{
    outputStream.write(b);
    String string = new String(b);
    if (!string.trim().isEmpty())
        logger.log(logLevel, string);
}

@Override
public void write(byte[] b, int off, int len) throws IOException
{
    outputStream.write(b, off, len);
    String string = new String(b, off, len);
    if (!string.trim().isEmpty())
        logger.log(logLevel, string);
}

@Override
public void write(int b) throws IOException
{
    outputStream.write(b);
    String string = String.valueOf((char) b);
    if (!string.trim().isEmpty())
        logger.log(logLevel, string);
}
}

And then a very simple utility class to set out and err:

import java.io.PrintStream;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

public class OutErrLogger
{
public static void setOutAndErrToLog()
{
    setOutToLog();
    setErrToLog();
}

public static void setOutToLog()
{
    System.setOut(new PrintStream(new LoggerStream(Logger.getLogger("out"), Level.INFO, System.out)));
}

public static void setErrToLog()
{
    System.setErr(new PrintStream(new LoggerStream(Logger.getLogger("err"), Level.ERROR, System.err)));
}

}
Dario Seidl
  • 4,140
  • 1
  • 39
  • 55
  • Where to add the path to the the log file ?? – Aniket Sep 19 '12 at 16:17
  • can you give me an idea about how the log4j.properties or log4j.xml file should look like to get this working ? – Aniket Sep 20 '12 at 16:06
  • @acoolguy See [Log4j XML Configuration Primer](http://wiki.apache.org/logging-log4j/Log4jXmlFormat), use a [FileAppender](http://wiki.apache.org/logging-log4j/FileAppender). – Dario Seidl Sep 22 '12 at 16:07
  • 2
    The only downside to this implementation is that if you have a stack trace printed to StdErr, it will print one line at a time like this, `2014-12-22 19:55:04,581 [main] INFO {ERR} at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefiniti‌​ons(XmlBeanDefinitionReader.java:396) 2014-12-22 19:55:04,581 [main] INFO {ERR} at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinition‌​s(XmlBeanDefinitionReader.java:334)` – Mike Pone Dec 22 '14 at 20:28
12

In Skaffman code : To remove empty lines in log4j logs, just add "println" method to PrintStream of createLoggingProxy

public static PrintStream createLoggingProxy(final PrintStream realPrintStream) {
    return new PrintStream(realPrintStream) {
        public void print(final String string) {
            logger.warn(string);
        }
        public void println(final String string) {
            logger.warn(string);
        }
    };
}
athspk
  • 6,722
  • 7
  • 37
  • 51
Fizou
  • 121
  • 1
  • 2
7

The answers above give an excellent idea to use proxy for the STDOUT/ERR logging. However provided implementation examples do not work nicely for all cases. For example, try

System.out.printf("Testing %s\n", "ABC");

The code from examples above will cut the output into separate pieces on a console and in multiple not readable Log4j entries.

The solution is to buffer the output until a trigger '\n' is found at buffer's end. Sometimes the buffer ends with '\r\n'. The class below addresses this issue. It is fully functional. Call the static method bind() to activate it.

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

// Based on
// http://stackoverflow.com/questions/1200175/log4j-redirect-stdout-to-dailyrollingfileappender
public class Log4jStdOutErrProxy {

  public static void bind() {
    bind(Logger.getLogger("STDOUT"), Logger.getLogger("STDERR"));
  }

  @SuppressWarnings("resource")
  public static void bind(Logger loggerOut, Logger loggerErr) {
    System.setOut(new PrintStream(new LoggerStream(loggerOut, Level.INFO,  System.out), true));
    System.setErr(new PrintStream(new LoggerStream(loggerErr, Level.ERROR, System.err), true));
  }

  private static class LoggerStream extends OutputStream {
    private final Logger logger;
    private final Level logLevel;
    private final OutputStream outputStream;
    private StringBuilder sbBuffer;

    public LoggerStream(Logger logger, Level logLevel, OutputStream outputStream) {
      this.logger = logger;
      this.logLevel = logLevel;
      this.outputStream = outputStream;
      sbBuffer = new StringBuilder();
    }

    @Override
    public void write(byte[] b) throws IOException {
      doWrite(new String(b));
    }

    @Override
    public void write(byte[] b, int off, int len) throws IOException {
      doWrite(new String(b, off, len));
    }

    @Override
    public void write(int b) throws IOException {
      doWrite(String.valueOf((char)b));
    }

    private void doWrite(String str) throws IOException {
      sbBuffer.append(str);
      if (sbBuffer.charAt(sbBuffer.length() - 1) == '\n') {
        // The output is ready
        sbBuffer.setLength(sbBuffer.length() - 1); // remove '\n'
        if (sbBuffer.charAt(sbBuffer.length() - 1) == '\r') {
          sbBuffer.setLength(sbBuffer.length() - 1); // remove '\r'
        }
        String buf = sbBuffer.toString();
        sbBuffer.setLength(0);
        outputStream.write(buf.getBytes());
        outputStream.write('\n');
        logger.log(logLevel, buf);
      }
    }
  } // inner class LoggerStream  

}
MarkG
  • 71
  • 1
  • 1
7

For those looking for how to do this in log4j2. There is now a component to create these streams for you.

Requires including the log4j-iostreams jar
See: https://logging.apache.org/log4j/2.x/log4j-iostreams.html

Example:

PrintStream logger = IoBuilder.forLogger("System.out").setLevel(Level.DEBUG).buildPrintStream();
PrintStream errorLogger = IoBuilder.forLogger("System.err").setLevel(Level.ERROR).buildPrintStream();
System.setOut(logger);
System.setErr(errorLogger);
nyg
  • 2,380
  • 3
  • 25
  • 40
Rowan
  • 598
  • 5
  • 7
6

If you are using an application server, servlet container or something similar, see kgiannakakis's answer.

For standalone apps see this. You can reassing stdin, stdout and stderr using java.lang.System class. Basically you create a new subclass of PrintStream and set that instance to System.out.

Something along these lines in start of your app (untested).

// PrintStream object that prints stuff to log4j logger
public class Log4jStream extends PrintStream {
      public void write(byte buf[], int off, int len) {
        try {
           // write stuff to Log4J logger
        } catch (Exception e) {
       }
    }
}

// reassign standard output to go to log4j
System.setOut(new Log4jStream());
Community
  • 1
  • 1
Juha Syrjälä
  • 33,425
  • 31
  • 131
  • 183
2

I presume you're logging stacktraces via e.printStackTrace() ? You can pass an exception object into the Log4j logging methods and those will appear in your log (see Logger.error(Object obj, Throwable t))

Note that you can change System.out and System.err to another PrintStream that redirects to Log4j. That would be a straightforward change and save you converting all your System.out.println() statements.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
2

Standard output and error streams are managed from your container. For example Tomcat uses JULI to log output and error streams.

My recommendation is to leave these as it is. Avoid using System.out.print in your application. See here for stack traces.

kgiannakakis
  • 103,016
  • 27
  • 158
  • 194
  • 2
    How about standalone java apps that do not use a container? Surely there is a way to catch stdout and log it to log4j? – Juha Syrjälä Jul 29 '09 at 13:29
  • As suggested by Brian Agnew you can redirect the stream to log4j. I however recommend against it. The solution is not to print at standard output, but use log4j instead. There isn't a single decent java library that uses standard output. If you have third party code that does this, ask them to use log4j or commons logging instead. Redirecting standard output should be the last resort. – kgiannakakis Jul 29 '09 at 13:46
  • Do not use System.out.println() for logging. Use log4j (or another logging framework) in your code, and simply have the config send the output to stdout. – matt b Jul 29 '09 at 13:52
  • 2
    oh, boys ;-) assumably, the whole point is about capturing third parties printing to System.out - e.g. if you turn on log4j.debug it'll print to System.out (see also LogLog) – Jörg Apr 05 '16 at 12:50
1

The anser of @Michael is a good Point. But extending PrintStream is not very nice, because it uses a internal method void write(String) to write all things to an OutputStream.

I prefer to use the LoggingOutputStream Class from the Log4J Contrib package.

Then i redirect the system-streams like this:

public class SysStreamsLogger {
    private static Logger sysOutLogger = Logger.getLogger("SYSOUT");
    private static Logger sysErrLogger = Logger.getLogger("SYSERR");

    public static final PrintStream sysout = System.out;
    public static final PrintStream syserr = System.err;

    public static void bindSystemStreams() {
        // Enable autoflush
        System.setOut(new PrintStream(new LoggingOutputStream(sysOutLogger, LogLevel.INFO), true));
        System.setErr(new PrintStream(new LoggingOutputStream(sysErrLogger, LogLevel.ERROR), true));
    }

    public static void unbindSystemStreams() {
        System.setOut(sysout);
        System.setErr(syserr);
    }
}
itshorty
  • 1,522
  • 3
  • 17
  • 39
  • LoggingOutputStream doesn't seem to exist anymore in the latest log4j contrib release (1.0.4) – Nicolas Mommaerts Apr 28 '13 at 11:28
  • just take it from https://svn.apache.org/viewvc/logging/log4j/trunk/contribs/JimMoore/LoggingOutputStream.java?view=co ! it's pretty stand alone. – itshorty May 16 '13 at 09:14
-2

Before using the System.setOut and System.setErr method we should reset the java.util.logging.LogManager object by using reset() method.

public static void tieSystemOutAndErrToLog() {

    try{

        // initialize logging to go to rolling log file
        LogManager logManager = LogManager.getLogManager();
        logManager.reset();

        // and output on the original stdout
        System.out.println("Hello on old stdout");
        System.setOut(createLoggingProxy(System.out));
        System.setErr(createLoggingProxy(System.err));

        //Following is to make sure whether system.out and system.err is redirecting to the stdlog.log file
        System.out.println("Hello world!");

        try {
            throw new RuntimeException("Test");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }catch(Exception e){
        logger.error("Caught exception at StdOutErrLog ",e);
        e.printStackTrace();
    }
}