将System.out.println重定向到Log4J,同时保留类名信息 [英] Redirect System.out.println to Log4J, while keeping class name information
问题描述
我有一些库在我身上调用System.out.println,我想通过log4j或commons日志记录重定向它们。但特别是我想保留完全限定的类名,所以我知道哪个组件生成了日志。
I have some libraries that are calling System.out.println on me, I'd like to redirect them through log4j or commons logging. But in particular I'd like to keep the fully-qualified-classname so I know what component generated the logs.
有没有一个很好的,有序的方法来完成这个?
Is there a nice, orderly way to accomplish this?
更新:完成此操作后,我在此处发布了代码:
http://www.bukisa.com/articles/487009_java-how-to-redirect-stderr-and-stdout-to-commons-logging-with-the-calling-class
推荐答案
我能想到的唯一方法就是编写自己的 PrintStream
在调用 println
方法时创建堆栈跟踪的实现,以便计算出类名。这将是相当可怕的,但它应该工作...概念证明示例代码:
The only way I can think of would be to write your own PrintStream
implementation which created a stack trace when the println
method was called, in order to work out the class name. It would be pretty horrible, but it should work... proof of concept sample code:
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而不是当然......或者可能也是如此。)
(In your code you would make it log to log4j instead of course... or possibly as well.)
这篇关于将System.out.println重定向到Log4J,同时保留类名信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!