log

log4j is a reliable, fast and flexible logging framework(APIs) written in Java, which is distributed under the Apache Software License.

1. three main components:

  • loggers: Responsible for capturing logging information.

  • appenders: Responsible for publishing logging information to various preferred destinations.

  • layouts: Responsible for formatting logging information in different styles.

2. log4j Features

  • It is thread-safe.

  • It is optimized for speed.

  • It is based on a named logger hierarchy.

  • It supports multiple output appenders per logger.

  • It supports internationalization.

  • It is not restricted to a predefined set of facilities.

  • Logging behavior can be set at runtime using a configuration file.

  • It is designed to handle Java Exceptions from the start.

  • It uses multiple levels, namely ALL, TRACE, DEBUG, INFO, WARN, ERROR and FATAL.

  • The format of the log output can be easily changed by extending the Layout class.

  • The target of the log output as well as the writing strategy can be altered by implementations of the Appender interface.

  • It is fail-stop. However, although it certainly strives to ensure delivery, log4j does not guarantee that each log statement

default file

log4j.properties

e.g. print to console, file & database

# Root logger option
log4j.rootLogger=DEBUG, stdout, DB

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

# Redirect log messages to a log file, support file rolling.
#log4j.appender.file=org.apache.log4j.RollingFileAppender
#log4j.appender.file.File=d:\\log4j-application.log
#log4j.appender.file.MaxFileSize=5MB
#log4j.appender.file.MaxBackupIndex=10
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

#define the db appender
log4j.appender.DB = org.apache.log4j.jdbc.JDBCAppender

#set jdbc url
log4j.appender.DB.URL = jdbc:mysql://localhost:3306/hello-world
#jdbc:mysql://localhost:3306/hello-world
#set database driver
log4j.appender.DB.driver = com.mysql.jdbc.Driver

#set database user name and password
log4j.appender.DB.user = root
log4j.appender.DB.password = 063374

#set the SQL statement to be executed
log4j.appender.DB.sql = INSERT INTO logs values('%x','%d{yyyy-MM-dd HH:mm:ss}','%C','%p','%m')

log4j.appender.DB.layout = org.apache.log4j.PatternLayout

e.g. for hibernate

#log everything
log4j.logger.org.hibernate = ALL
#show sql statements
log4j.logger.org.hibernate.SQL = INFO
#show the bind parameter values
log4j.logger.org.hibernate.type.descriptor.sql.BasicBinder = TRAACE

Last updated

Was this helpful?