Setting Log Levels for Logger and Handler

In this post under Java Logging, I will explain with example how to set log levels for Logger and Handler implementations.

Please not the log level of Logger and Handler should be same otherwise some messages will not be logged by the handler.

We set the log levels by calling “setLevel” method available on Logger and Handler interface.

Below is the complete code

Main Class

1  package logging;
3  import;
4  import java.util.logging.FileHandler;
5  import java.util.logging.Level;
6  import java.util.logging.Logger;
8  public class LoggingDemo10 {
9      public static void main(String[] args) throws IOException {
10         Logger logger = Logger.getLogger("logging.LoggerDemo10");
11         logger.setLevel(Level.INFO);
13         FileHandler fileHandler = null;
14         try {
15             fileHandler = new FileHandler("java.log");
16             fileHandler.setLevel(Level.INFO);
17             logger.addHandler(fileHandler);
18   "Hello my name is Sumanth");
19             logger.removeHandler(fileHandler);
20         } finally {
21             fileHandler.close();
22         }
23     }
24 }

In the above code, at line 11, I am setting the log level for Logger instance

At line 16, I am setting the log level for FileHandler instance.

So we can log message with level INFO and above.

Leave a Reply