Logging

Objectives

  • Use the Java logging facility
  • Discuss advantages and disadvantages of logging in Java

Logging notes

  • There is little overhead for unused logging in programs
  • The logging level can be set so less important or debugging logging can be turned off without recompiling
  • Log messages can be output in different formats such as XML or plain text
  • Multiple loggers can be used at the same time
  • Filters can be used with logging to reduce the messages being stored
  • Logging output can be easily redirected
  • The default log configuration file can be replaced
  • Logging levels (in descending order): SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST
  • Default logger properties are stored in jreHome/lib/logging.properties
  • You can change logging properties by modifying the logging.properties file
  • Different settings can be set for each logger in the logging.properties file
  • You can also create your own logger configuration file and specify it at runtime using the -Djava.util.logging.config.file=yourLogFileName option to the java command

Simple logging to console and setting logger output level

Note how setting the log level in code of the console logger only matters if the configuration file allows logging at the specified levels. The default level is INFO.

Logging to a file in addition to the console

Note how the file log has a different logging level than the console. Note also that the output to the file defaults to XML format. You can specify your own formatter or use one of the built-in formatters. The console default formatter produces a simple text output. You can have quite a bit of detail recorded in the log entries. Notice that the XML format log entries include the class and method where the log entry came from.

Eliminating logger output to the console

Changing the console logging level

Other options

  • You can use logger.log(Level level, String msg) in place of logger.level(String msg)
  • A set of Logger methods exist for giving precise location where the logging was done (see logp methods)
  • Specific log messages can be generated when entering or exiting a method
  • Specific log messages can be generated when throwing errors
  • You can also set up log rotation files using patterns for naming the files
  • Log rotation can also set size and time limits for log files