重定向 System.out.println
我的应用程序有许多 System.out.println() 语句。
我想从 println 捕获消息并将它们发送到标准记录器(Log4j、JUL 等)。
怎么办呢?
My application has many System.out.println() statements.
I want to catch messages from println and send them to the standard logger (Log4j, JUL etc).
How to do that ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
System 类有一个
setOut
和setErr
可用于将输出流更改为例如带有支持 < 的新PrintStream
code>File 或者,在本例中,可能是另一个使用您选择的日志子系统的流。请记住,如果您将日志库配置为输出到标准输出或错误(可能是无限递归类型),您很可能会遇到麻烦。
如果是这种情况,您可能只想用真正的日志记录调用替换您的 System.out.print 类型语句。
The System class has a
setOut
andsetErr
that can be used to change the output stream to, for example, a newPrintStream
with a backingFile
or, in this case, probably another stream which uses your logging subsystem of choice.Keep in mind you may well get yourself into trouble if you ever configure your logging library to output to standard output or error (of the infinite recursion type, possibly).
If that's the case, you may want to just go and replace your
System.out.print
-type statements with real logging calls.我曾经有过类似的需求。我需要拦截某些第三方组件的输出并对错误消息做出反应。
这个概念看起来像这样:
I had a similar need once. I needed to intercept the output of some 3rd party component and react on a error message.
The concept looks like this:
更好的解决方案是检查并更改所有 println 语句以使用正确的日志记录库。你想做的是一个大黑客。
The better solution is to go through and change all the println statements to use a proper logging library. What you're trying to do is a big hack.
以下是如何将打印捕获到 System.out,然后将内容按顺序放回原处:
Here is how to capture prints to System.out, and then put things back in order :
扩展 PrintStream 是一个糟糕的解决方案,因为您必须重写所有
print()
和println()
方法。相反,您可以捕获流:现在您可以像这样捕获它:
extending PrintStream is a bad solution as you will have to override all
print()
andprintln()
methods. Instead, you can capture the stream:Now you can capture it like this:
我应用了这个的基本思想并且效果很好。
无需更改所有 System.out.### 和 System.err.### 内容。
此视图行将启用日志记录,而无需进一步更改代码:
I applied the base idea of this and it workes fine.
No need to change all the System.out.### and System.err.### stuff.
This view lines will enable logging without further code changes: