Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 275
Niko Avatar asked Oct 11 '14 19:10

Niko


1 Answers

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
like image 72
Anton Balaniuc Avatar answered Sep 29 '22 11:09

Anton Balaniuc