Saturday, July 25, 2015

Write logs to different outputs according to log level

In some cases we have to write logs to different outputs according to log level. It can be easily configured by specifying the filter of certain appenders. The most easiest way of specifying appenders is having a properties configuration file, but properties configuration files doesn’t support log level filters. Therefore it is necessary to stick with XML to specify appenders.

Log4J supports different log levels. These log levels can be used in different events as mentioned in table 1.

#
Level
Summary
1
ALL
ALL has the lowest rank and it is intended to turn on all logging.
2
DEBUG
DEBUG level is useful to developers to indentify events in an informational manner and allows to debug the application.
3
ERROR
ERROR level specifies events that must immediately investigated but which allows the application to continue its functionality.
4
FATAL
FATAL level can be used to log terrible errors that can cause application to abort its operations.
5
INFO
INFO level is useful to mention informative messages after important process has finished.
6
OFF
OFF has the highest rand and it is intended to turn off all logging.
7
TRACE
TRACE level is used to log events in a very informative manner. Basically TRACE logs are used in development and eventually remove from production deployments.
8
WARN
WARN level can be used to log potentially harmful situations.

Basically when a low priority log level is given, messages with higher priority for the given log level are also logged. In that case log level range filter (LevelRangeFilter) can be used to reject messages with priorities outside a certain range. The range can be configured by specifying the values for LevelMin, LevelMax, and AcceptOnMatch properties.

A sample of log4j XML file with log level filters created by a colleague is added below.


References:
  • "Logging Services." Log4J. Apache Software Foundation, n.d. Web.
  • "Log4j Architecture." Log4J. Apache Software Foundation, n.d. Web.