Log4J Redirect Stdout to Dailyrollingfileappender

log4j redirect stdout to DailyRollingFileAppender

// 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);
}
};
}
}

Log4J: Redirect Stderr message to the main log file

I found this question here, the accepted answer is the one I needed:
log4j redirect stdout to DailyRollingFileAppender

Turns out I was trying to figure out a way to fix it in XML config when in reality I should have been trying to fix in in code by redirecting stdErr with System.setErr().

catch stderr and stdout in log4j before unix redirection

To redirecting stdout and stderr to log4j, try something like this:

System.setErr( new PrintStream( new LoggingOutputStream( Logger.getRootLogger(  ), Level.ERROR ), true);

System.setOut( new PrintStream( new LoggingOutputStream( Logger.getRootLogger( ), Level.INFO ), true);

For LoggingOutputStream you can start from this example

To get log4j to print what you want to the console (and capture this back into a file/node if you want), enable a ConsoleAppender to the proper level

Redirect System.out.println to log

My suggestion would be to refactor if possible.
For a possible solution, check these similar questions

log4j redirect stdout to DailyRollingFileAppender

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



Related Topics



Leave a reply



Submit