1

We have a Java application on Websphere where we need SystemOut.log only print loglevel SEVERE and INFO (using existing java.util.logging default ConsoleHandler), but we need a WARNING written to separate file using the FileHandler .

Created a LevelBasedFileHandler which takes log level and file to write and i can see the log file updated as needed.

But the Warning level's are written in SystemOut.log too, Need a way to stop them from appearing

logger.addHandler(new LevelBasedFileHandler("../logs/warning.log", Level.WARNING));


logger.setFilter(new LevelBasedFilter()); - Trying to see if i can filter

logger.setUseParentHandlers(false);

using the logger.setUseParentHandlers(false) is not printing any information to SystemOut.log if i remove it i see WARNING information too. Any idea i can filter the Warning Level from this?

JavaDude
  • 11
  • 1

1 Answers1

0

If you filter at the logger level that will suppress log records before they reach any of the handlers. What you should do is install filters on the existing handlers.

For example, create a filter which takes a boolean:

import java.util.logging.Filter;
import java.util.logging.Level;
import java.util.logging.LogRecord;

public class WarningFilter implements Filter {

   private final boolean complement;

    public WarningFilter(final boolean complement) {
        this.complement = complement;
    }

    @Override
    public boolean isLoggable(LogRecord r) {
        return Level.WARNING.equals(r.getLevel()) != complement;
    }
}

Next you should install your filter on each handler. For example:

    private static final Logger logger = Logger.getLogger("some.other.logger.name");
    public static void main(String[] args) throws Exception {
        boolean found = false;
        for (Handler h : Logger.getLogger("").getHandlers()) {
            h.setFilter(new WarningFilter(h instanceof ConsoleHandler));
        }

        if(!found) {
            Handler h = new ConsoleHandler();
            h.setFilter(new WarningFilter(true));
        }

        Handler h = new FileHandler();
        h.setFilter(new WarningFilter(false));
        logger.addHandler(h);

    }
jmehrens
  • 10,580
  • 1
  • 38
  • 47
  • I tried the same approach using filter, but still no luck. It's printing in the Console logs (Warning Messages). BTW i am deploying as part of Struts Application and did the same code in ServletFilter too. Any other idea's on this is deeply appreciated. – JavaDude Jan 23 '19 at 18:38
  • @JavaDude [Try printting the logger tree](https://stackoverflow.com/questions/44882648/logging-not-showing) and add that information to your question. It might be the case that you have to `setUseParentHandlers(false)` and then add a `ConsoleHandler` that filters for warning. – jmehrens Jan 23 '19 at 19:46