Log4j Properties

Log4j configuration with log4j.properties

Logging to Console-

log4j.properties:

# Root logger option
log4j.rootLogger=INFO, stdout
 
# Direct log messages to stdout
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

Here logging level is set at INFO, Appender is console,Layout is Pattern with timestamp.

Logging to file-

log4j.properties:

# Root logger option
log4j.rootLogger=INFO, file
 
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
 
log4j.appender.file.File=D:\logs\applog.log
log4j.appender.file.MaxFileSize=10MB
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

Here logging level is set at INFO, Appender is file,Layout is Pattern with timestamp.

Logging to Database-

Suppose we have table in our DB:

CREATE TABLE LOG_TABLE
   (USER_ID VARCHAR(10) NOT NULL,
    DATED   DATE NOT NULL,
    LOGGER  VARCHAR(50) NOT NULL,
    LEVEL   VARCHAR(10) NOT NULL,
    MESSAGE VARCHAR(1000) NOT NULL
   );

log4j.properties:

# Root logger option
log4j.rootLogger = DEBUG, DB

# DB appender
log4j.appender.DB=org.apache.log4j.jdbc.JDBCAppender

# Set JDBC URL
log4j.appender.DB.URL=jdbc:mysql://localhost/DBNAME

# Set Database Driver
log4j.appender.DB.driver=com.mysql.jdbc.Driver

# user name and password
log4j.appender.DB.user=username
log4j.appender.DB.password=password

# SQL statement to be executed.
log4j.appender.DB.sql=INSERT INTO LOG_TABLE 
                      VALUES('%x','%d','%C','%p','%m')

# layout for file appender
log4j.appender.DB.layout=org.apache.log4j.PatternLayout