dout重定向到DailyRollingFileAppender

dout重定向到DailyRollingFileAppender

本文介绍了log4j将stdout重定向到DailyRollingFileAppender的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用log4j的java应用程序。



配置:

  log4j.rootLogger =信息,文件

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

所以所有的日志语句都被正确附加到文件中,但是我正在丢失stdout和stderr。如何将异常堆栈跟踪和sysouts重定向到日常滚动文件?

解决方案
  //我在Log4J中设置了一个ConsoleAppender格式化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


//我在启动时调用此StdOutErrLog.tieSystemOutAndErrToLog()

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){
返回新的PrintStream(realPrintStream){
public void print(final String string){
realPrintStream.print(string);
logger.info(string);
}
};
}
}


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 ?

解决方案
// 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将stdout重定向到DailyRollingFileAppender的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 19:46