Home > Software engineering >  Log4j Logging OutputStream chaining
Log4j Logging OutputStream chaining

Time:03-19

I have a legacy Java App, It uses Log4j as logging tool. The app is lacking metrics so I want to find a way to smartly retrieve some java class based metrics.

The issue is I want to intercept all log4j logging before they are served.

The idea is inspired by the chaining of the System.out looking like this

TeeOutputStream myOut=new TeeOutputStream(System.out, mySpecificOut);
PrintStream ps = new PrintStream(myOut, true); //true - auto-flush after println
System.setOut(ps);

So is there a way to chain the Log4j output stream and fully control it on java because I need to do some logic before login.

Thanks

CodePudding user response:

Yes it is, you can define your own Stream using

LoggingOutputStream extends OutputStream {

and chain in order to intercept the logs

System.setOut(new PrintStream(new LoggingOutputStream(

Have a look at this nice example based on innoq/log4j LoggingOutputStream.

  • Related