Springboot整合log4j2打印System.out日志
记一次开发踩坑,springboot整合log4j2的过程中,try catch 捕获异常后,Exception.printStackTrace()方法却没有将错误日志打印到日志文件中,通过阅读源码发现,printStackTrace使用的是System.err进行日志打印,所以采用下面的办法进行处理,自定义PrintStream
1、继承PrintStream父类,并重写print这一类方法,使用log输出。
public class Log4j2ErrPrintStream extends PrintStream {
private Logger log = LoggerFactory.getLogger("SystemErr");
private static PrintStream instance = new Log4j2ErrPrintStream(System.err);
private Log4j2ErrPrintStream(OutputStream out) {
super(out);
}
public static void redirectSystemErr() {
System.setErr(instance);
}
public void print(boolean b) {
println(b);
}
public void print(char c) {
println(c);
}
public void print(char[] s) {
println(s);
}
public void print(double d) {
println(d);
}
public void print(float f) {
println(f);
}
public void print(int i) {
println(i);
}
public void print(long l) {
println(l);
}
public void print(Object obj) {
println(obj);
}
public void print(String s) {
println(s);
}
public void println(boolean x) {
log.error(String.valueOf(x));
}
public void println(char x) {
log.error(String.valueOf(x));
}
public void println(char[] x) {
log.error(x == null ? null : new String(x));
}
public void println(double x) {
log.error(String.valueOf(x));
}
public void println(float x) {
log.error(String.valueOf(x));
}
public void println(int x) {
log.error(String.valueOf(x));
}
public void println(long x) {
log.error(String.valueOf(x));
}
public void println(Object x) {
log.error(String.valueOf(x));
}
public void println(String x) {
log.error(x);
}
}
2、自定义SpringApplicationBuilder启动类
public class MyBuilder{
public MyBuilder(Class<?> sources, String[] args) {
//使用log4j2来打印system输出
Log4j2OutPrintStream.redirectSystemOut();
new SpringApplicationBuilder(sources).run(args);
}
}
3、使用自定义的启动类启动服务
@SpringBootApplication
public class TestServer {
public static void main( String[] args ) {
new MyBuilder(TestServer .class, args);
}
}
各位大神走过路过有什么好的建议,欢迎在下方评论交流