Skip to content
Advertisement

Is there a way to get java.util.logging.LogManager to report all loggers for which properties are specified or to access the properties?

In LogManager, the method getLoggerNames appears to only return loggers that have been actually instantiated already. However, logging properties can be held “in reserve” until a logger with a given name is instantiated.

Is there a way to get the full list of loggers for which we have settings, or to at least get the current properties set/map, without reading the original file from my own code?

Advertisement

Answer

JDK-8033661: readConfiguration does not cleanly reinitialize the logging system was fixed in Java version 9 which added the LogManager.updateConfiguration(Function<String,BiFunction<String,String,String>>) method. Per the documentation this method will read configuration keys and returns a function whose returned value will be applied to the resulting configuration. By supplying an identity function you can iterate the existing configuration keys instead of the actual created loggers by doing something like the following:

    Function<String, BiFunction<String,String,String>> consume 
            = new Function<String, BiFunction<String,String,String>>() {
        @Override
        public BiFunction<String, String, String> apply(final String k) {
            return new BiFunction<String, String, String>() {
                
                @Override
                public String apply(String o, String n) {
                    System.out.println(k +"="+ o);
                    return o;
                }
            };
        }
    };
    LogManager.getLogManager().updateConfiguration(consume);

For JDK 8 and older, you have to do one of the following:

  1. Read the logging.properties file yourself.
  2. Override the LogManager.readConfiguration(InputStream) to capture the bytes from the stream and create your own Properties object from the stream. The no arg readConfiguration will call this method so the given stream is the properties file as bytes.
  3. Resort to reflection (yuck!).

The easy way to read the properties file is by using the java.util.Properties class.

    final Properties props = new Properties();
    try {
        String v = System.getProperty("java.util.logging.config.file");
        if (v == null) {
           v = System.getProperty("java.home") + "/lib/logging.properties";
        }
        final File f = new File(v).getCanonicalFile();
        final InputStream in = new FileInputStream(f);
        try {
            props.load(in);
        } finally {
            in.close();
        }
    } catch (final RuntimeException permissionsOrMalformed) {
    } catch (final Exception ioe) {
    }
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement