spring代码异常捕获到logback logging.config=logback-spring.xml文件中不能输出异常e.printStackTrace...
生活随笔
收集整理的這篇文章主要介紹了
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://stackoverflow.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();}@Overridepublic void write(byte[] b) throws IOException {doWrite(new String(b));}@Overridepublic void write(byte[] b, int off, int len) throws IOException {doWrite(new String(b, off, len));}@Overridepublic 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 readysbBuffer.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 }?
初始化時調用:
// 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();
轉載于:https://www.cnblogs.com/bigben0123/p/8295508.html
總結
以上是生活随笔為你收集整理的spring代码异常捕获到logback logging.config=logback-spring.xml文件中不能输出异常e.printStackTrace...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: BZOJ2631: tree
- 下一篇: 缺少动态连接库.so--cannot o