Log4j Logging Framework

Photo by Anthony Cantin on Unsplash

log4j is a reliable, fast and flexible logging framework (APIs) written in Java under the Apache. It offers direct logging information to a variety of destinations, such as a database, file, console, UNIX Syslog, etc.

Log4j has three main components:

  • loggers: capture logging information.
  • appenders: publish logging information to various preferred destinations.
  • layouts: format logging information in different styles.

It has other Support objects — Level, Filter, ObjectRenderer for string representation, and LogManager for reading configurations.

  • It is thread-safe.
  • It supports multiple output appenders per logger to alter target output.
  • The format of the log output can be changed by extending the Layout class.
  • It uses multiple levels ALL, TRACE, DEBUG, INFO, WARN, ERROR, FATAL.
  • does not guarantee delivery.

Log4j offers debugging, easy maintenance, and structured storage of an application’s runtime information. But It can slow down an application.

log4j sets the Level, Appender, and Layout objects in a file.

# Define the root logger with appender file
log4j.rootLogger = DEBUG, FILE
# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${log}/log.out
# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n

immediateFlush flag is by default set to true, which means the output stream to the file being flushed with each append operation.

bufferedIO This flag indicates whether we need buffered writing enabled. By default, it is set to false.

To write your logging information into multiple files, you would have to use org.apache.log4j.RollingFileAppender class which extends the FileAppender class and inherits all its properties.

org.apache.log4j.jdbc.JDBCAppender object, which can put logging information in a specified database.