spring代码异常捕获到logback logging.config=logback-spring.xml文件中不能输出异常e.printStackTrace

在spring中使用logging.config=logback-spring.xml将日志转存到了文件中。但是代码中的捕获的异常无法用 e.printStackTrace 打印到文件中。使用如下方法打印:


main:
catch(Exception e){
log.error("xxx",e);
}

这里可以重新定向 system.out 和err的输出,到logback:
https://*.com/questions/1200175/log4j-redirect-stdout-to-dailyrollingfileappender

用于捕获运行时异常。
package com.italktv.platform.audioDist;

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

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

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) == '
') {
                // The output is ready
                sbBuffer.setLength(sbBuffer.length() - 1); // remove '
'
                if (sbBuffer.charAt(sbBuffer.length() - 1) == '
') {
                    sbBuffer.setLength(sbBuffer.length() - 1); // remove '
'
                }
                String buf = sbBuffer.toString();
                sbBuffer.setLength(0);
                outputStream.write(buf.getBytes());
                outputStream.write('
');
                logger.log(logLevel, buf);
            }
        }
    } // inner class LoggerStream  

}

初始化时调用:

// initialize logging to go to rolling log file
LogManager.resetConfiguration();

// and output on the original stdout
System.out.println("Hello on old stdout");
Log4jStdOutErrProxy.bind();