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
Bypass Generatedvalue in Hibernate (Merge Data Not in Db)
Try with Resources VS Try-Catch
Java Jar File: Use Resource Errors: Uri Is Not Hierarchical
Why Isn't There a Java.Lang.Array Class? If a Java Array Is an Object, Shouldn't It Extend Object
How to Pass a Primitive Data Type by Reference
Valid Characters in a Java Class Name
Alert Handling in Selenium Webdriver (Selenium 2) with Java
Java Calendar, Date, and Time Management for a Multi-Timezone Application
Why to Use Swingutilities.Invokelater in Main Method
Method Overloading and Choosing the Most Specific Type
How to Replace the Awt Eventqueue with Own Implementation
Scanner Nosuchelementexception
How to Write an Rss Feed with Java
Java Type Inference: Reference Is Ambiguous in Java 8, But Not Java 7
How to Get the Name of the Calling Class in Java
Does Java Evaluate Remaining Conditions After Boolean Result Is Known
How to Set an Image as a Background for Frame in Swing Gui of Java