将System.out.println重定向到Log4J,同时保留类名信息

将System.out.println重定向到Log4J,同时保留类名信息,第1张

将System.out.println重定向到Log4J,同时保留类名信息

我能想到的唯一方法是编写自己的

PrintStream
实现,该实现在调用该
println
方法时创建了堆栈跟踪,以便计算出类名。这将是非常可怕的,但它应该可以工作…概念证明示例代码

import java.io.*;class TracingPrintStream extends PrintStream {  public TracingPrintStream(PrintStream original) {    super(original);  }  // You'd want to override other methods too, of course.  @Override  public void println(String line) {    StackTraceElement[] stack = Thread.currentThread().getStackTrace();    // Element 0 is getStackTrace    // Element 1 is println    // Element 2 is the caller    StackTraceElement caller = stack[2];    super.println(caller.getClassName() + ": " + line);  }}public class Test {  public static void main(String[] args) throws Exception {    System.setOut(new TracingPrintStream(System.out));    System.out.println("Sample line");  }}

(在您的代码中,您应该使其登录到log4j而不是当然的日志……或者也可以。)



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5488924.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存