简体   繁体   English

使用log4j2将System.out写入文件

[英]write System.out to file with log4j2

Is it possible to write the System.out (OutputStream) directly to a log file like in the "old" log4j? 是否可以将System.out(OutputStream)直接写入日志文件,如“旧”log4j?

I only find solutions for log4j, not log4j2 我只找到log4j的解决方案,而不是log4j2

thanks for any help! 谢谢你的帮助!

It is quite easy using log4j2-iostreams module. 使用log4j2-iostreams模块非常容易。 Let's say we want to send all messages from System.out to a logger with name system.out with log level INFO : 假设我们要将所有消息从System.out发送到名为system.out并且日志级别为INFO的记录器:

System.setOut(
        IoBuilder.forLogger(LogManager.getLogger("system.out"))
                .setLevel(Level.INFO)
                .buildPrintStream()
);
System.out.println("Lorem ipsum");

with the following log4j2.properties 使用以下log4j2.properties

appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d [%p] %c - %m%n

rootLogger.level = info
rootLogger.appenderRef.stdout.ref = STDOUT

we should see the following output in the console: 我们应该在控制台中看到以下输出:

2017-10-28 12:38:22,623 [INFO] system.out - Lorem ipsum

The upcoming 2.1 release contains a new log4j-iostreams module which can do this and more. 即将发布的2.1版本包含一个新的log4j-iostreams模块,可以执行此操作以及更多功能。 Should be out soon. 应该很快出来。

If you're in a hurry you can check out the latest source from master and build the 2.1 snapshot. 如果您赶时间,可以查看master中的最新源代码并构建2.1快照。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM