Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the logging level when using System.Logger?

Tags:

java

logging

I'm trying to use System.getLogger, but I can't figure out how to set the log level so that debug messages come out. Here is my simple problem repro:

class LogTest {
    static {
        System.setProperty("java.util.logging.SimpleFormatter.format", "%1$tF: %5$s%n");
        System.setProperty("java.util.logging.ConsoleHandler.level", "FINEST");
    }
    public static void main(String[] args) {
        System.getLogger(LogTest.class.getName())
            .log(System.Logger.Level.INFO, "info");
        System.getLogger(LogTest.class.getName())
            .log(System.Logger.Level.DEBUG, "debug");
    }
}

The formatting change works, so it appears that System.Logger is using java.util.logging, but the logging level change doesn't seem to be working.

like image 434
Benjamin Reed Avatar asked Mar 03 '26 04:03

Benjamin Reed


1 Answers

For the java.util.logging implementation of System.Logger (a.k.a. the default unless you didn't include the module or are using something else like Log4j in which case I have no experience) you can set java.util.logger.ConsoleHandler.level and .level to FINE in logging.properties or use LogManager or just manually set them:

...

.level= FINE

...

java.util.logging.ConsoleHandler.level = FINE

...

or

static {
    Logger root = Logger.getLogger("");
    root.setLevel(Level.FINER);
    root.getHandlers()[0].setLevel(Level.FINER);
}

Note that this exposes debug calls from every user of the java.util.logging API including stuff like javax.swing and Runtime.exit(). If you don't want those, you can use java.util.logging's Filter to only log if it's a logger that you want.

// Put this where it's publicly visible
public class CustomFilter extends Filter {
    @Override
    public void isLoggable(LogRecord record) {
        switch (record.getLoggerName()) {
        case DESIRED_LOGGER_1.getName():
        case DESIRED_LOGGED_2.getName():
            return true;
        }
        return false;
    }
}

logging.properties:

...

# Replace "CustomFilter" with the actual value of CustomFilter.class.getName()
java.util.logging.ConsoleHandler.filter=CustomFilter

...

Another way to add a filter:

static {
    // Just attaching it to the root logger doesn't work for some reason
    Logger.getLogger("").getHandlers()[0].setFilter(record -> {
        switch (record.getLoggerName()) {
        case DESIRED_LOGGER_1.getName():
        case DESIRED_LOGGED_2.getName():
            return true;
        }
        return false;
    });
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!