Kumar Gaurav
Kumar Gaurav

Reputation: 769

How to not to show stdout from 3rd party jar and only show slf4j log

I am using a third party jar that has lots of System.out.println(). I am not interested in those messages. It also uses slf4j logs that I am interested in. So how do I filter out System.out.println() messages in my stdout. Is there a quick way? I am trying to avoid writing any script to parse the whole log and keep only the relevant one. I am using maven.

I would prefer to do logger log as stdout and system.out as file.. so that I can see relevant log while build is running in build environment.

Upvotes: 0

Views: 1270

Answers (2)

drkunibar
drkunibar

Reputation: 1337

Redirect the System.out and System.err.

But be careful: There will be an recursion if you use the Simple Logger

stdout and stderr will redirect to our own implementation of OutputStream (see code comments). Our own implementation redirect the output to slf4j

System.setOut(new PrintStream(new OutputStream() {

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    //
    // Our own implementation of write
    //
    @Override
    public void write(int b) throws IOException {
        //
        // After a line break the line will redirect to slf4j
        //
        if ((b == '\r') || (b == '\n')) {
            // Only 'real' content will redirect to slf4j
            if (buffer.size() != 0) {
                LoggerFactory.getLogger("foo").info(new String(buffer.toByteArray(), "UFT-8"));
            }
            // A new buffer is needed after a line break
            // (there is no 'clear()')
            buffer = new ByteArrayOutputStream();
        }
        buffer.write(b);
    }
}));
System.setErr(new PrintStream(new OutputStream() {

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();


    //
    // Our own implementation of write
    //
    @Override
    public void write(int b) throws IOException {
        if ((b == '\r') || (b == '\n')) {
            if (buffer.size() != 0) {
                LoggerFactory.getLogger("foo").error(new String(buffer.toByteArray(), "UFT-8"));
            }
            buffer = new ByteArrayOutputStream();
        }
        buffer.write(b);
    }
}));

Upvotes: 0

user65839
user65839

Reputation:

What I would suggest would be to redirect System.out to slf4j. That way, all logging can be configured in your logging framework in a standardized normal way.

Note that depending on the library you're using to do the redirection, if you have some loggers print to standard output, you may need to carefully configure it so that you don't end up in an infinite loop, where a printed message gets redirected to logging, which gets redirected to printing a message, and so on.

Also note that most build environments & IDEs have support for viewing the contents of a log file while it's being generated, so you don't have to print anything to standard output if you don't want to.

Upvotes: 1

Related Questions