简体   繁体   中英

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?

I only find solutions for log4j, not log4j2

thanks for any help!

It is quite easy using log4j2-iostreams module. Let's say we want to send all messages from System.out to a logger with name system.out with log level INFO :

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

with the following 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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