Home: www.vipan.com Vipan Singla e-mail: vipan@vipan.com
Don't Use System.out.println!
Use Log4j

Quick Start to Using Log4j

Log4j Details

  • Log4j has three main components: categories, appenders and layouts.
    • You instantiate a category and then call its various logging methods to send your message strings to log(s).
    • A category is configured to log to one or more destinations or targets. These logging destinations are called "appenders" in Log4j, probably because these classes by default "append" your message string to the end of the log. Log4j can send your log messages to the console, a text file, an html file, an xml file, a socket or even to the Windows NT Event Log, all with one logging call. It can even send your log message as an email (desirable for fatal errors, for example).
    • Some appender classes are ConsoleAppender, FileAppender, SMTPAppender, SocketAppender, NTEventLogAppender, SyslogAppender, JMSAppender, AsyncAppender and NullAppender.
    • An appender uses a layout to format your message before actually writing it to the log. For example, the HTMLLayout will format all your messages into a nice HTML table.
    • In addition to logging the message that you send, Log4j can also log the date, time, message priority (DEBUG, WARN, FATAL etc.), Java class name, source code line number, method name, Java thread name and much more. What to log is specified in the layout which an appender s configured with.

Configuring Log4j

Useful Layouts

Property Keys for Log4j, Appender and Layout Options

A Comprehensive Log4J Configuration Properties File

#log4j.debug=true
#log4j.disable=fatal
#log4j.additivity.TestLogging=false

log4j.rootCategory=, dest1
log4j.category.TestLogging=DEBUG, dest1
log4j.appender.dest1=org.apache.log4j.ConsoleAppender
#log4j.appender.dest1.layout=org.apache.log4j.SimpleLayout
log4j.appender.dest1.layout=org.apache.log4j.PatternLayout
#log4j.appender.dest1.layout.ConversionPattern=%-5p %l %x: %m%n


!----------------------####### END OF PROPERTIES #######----------------------!


###############################################################################
# Below I document in more detail how to write a log4j configuration file.    #
# SELECTIVELY copy lines beginning with #, paste and uncomment them above.    #
###############################################################################

!-----------------------------------------------------------------------------!
! PLACE THIS FILE ANYWHERE IN CLASSPATH                                       !
! Appenders are additive by default.                                          !
! Priorities are inherited until overridden in a category.                    !
! In ${property_key}, the value of the key can be defined as a system         !
! property or in this file itself.  System properties are searched first and  !
! then this file.                                                             !
!-----------------------------------------------------------------------------!



!-----------------------------------------------------------------------------!
! Configure log4j's operation at the meta level                               !
!-----------------------------------------------------------------------------!
! Observe log4j parsing this file
#log4j.debug=true
! Set this to false for log4j to actually obey the log4j.disable property(next)
#log4j.disableOverride=false
! Disable all logging in all categories for messages with priority equal to
! or lower than the one given here
#log4j.disable=INFO



!-----------------------------------------------------------------------------!
! Configure categories (loggers)                                              !
!-----------------------------------------------------------------------------!

! ROOT CATEGORY (Usually sufficient to set this one only)
! Here, logs messages with priority DEBUG (default) or higher
#log4j.rootCategory=, dest1
! Or,
#log4j.rootCategory=debug, dest1, dest2

! YOUR CATEGORIES (to customize logging per class/pkg/project/etc)
! Here, overrides ancestor's priority and makes it WARN or higher for this cat.
#log4j.category.TestLogging=WARN, dest3
! Or,
#log4j.category.TestLogging=DEBUG, dest3

!--------DON'T DO THIS!!!  APPENDERS ARE ADDITIVE BY DEFAULT!!!---------------!
! It will write the same log message TWICE to dest1. Once for root, then for  !
! this category.                                                              !
!#log4j.category.TestLogging=DEBUG, dest1, dest3                              !
! If you DO NOT want additivity for this category, say so                     !
!#log4j.additivity.TestLogging=false                                          !
!-----------------------------------------------------------------------------!



!-----------------------------------------------------------------------------!
! Configure appenders (log destinations/targets) and their options            !
!-----------------------------------------------------------------------------!

! WRITE TO CONSOLE (stdout or stderr)
#log4j.appender.dest1=org.apache.log4j.ConsoleAppender
#log4j.appender.dest1.ImmediateFlush=true

! WRITE LOG TO A FILE, ROLL THE FILE AFTER SOME SIZE
#log4j.appender.dest2=org.apache.log4j.RollingFileAppender
! This appender will only log messages with priority equal to or higher than
! the one specified here
#log4j.appender.dest2.Threshold=ERROR
! Specify the file name (${property_key} gets substituted with its value)
#log4j.appender.dest2.File=${java.home}/log4j.log
! Don't append, overwrite
#log4j.appender.dest2.Append=false
! Control the maximum log file size
#log4j.appender.dest2.MaxFileSize=100KB
! Keep backup file(s) (backups will be in filename.1, .2 etc.)
#log4j.appender.dest2.MaxBackupIndex=2

! WRITE LOG TO A FILE, ROLL THE FILE EVERY WEEK
#log4j.appender.dest3=org.apache.log4j.DailyRollingFileAppender
! Specify the file name
#log4j.appender.dest3.File=log4TestLogging2.html
! Control the maximum log file size
#log4j.appender.dest3.MaxFileSize=300KB
! Rollover log file at the start of each week
#log4j.appender.dest3.DatePattern='.'yyyy-ww



!-----------------------------------------------------------------------------!
! Configure appender layouts (log formats) and their options                  !
!-----------------------------------------------------------------------------!

! USE SIMPLE LOG FORMAT (e.g. INFO - your log message)
#log4j.appender.dest1.layout=org.apache.log4j.SimpleLayout

! USE A C PRINTF STYLE PATTERN TO FORMAT LOG MESSAGE
#log4j.appender.dest1.layout=org.apache.log4j.PatternLayout
! For a pattern layout, specify the pattern (Default is %m%n which is fastest)
#log4j.appender.dest1.layout.ConversionPattern=%-5p: %m%n
! Or,
#log4j.appender.dest1.layout.ConversionPattern=%-5p %6.10r[%t]%x(%F:%L) - %m%n

#log4j.appender.dest2.layout=org.apache.log4j.PatternLayout
#log4j.appender.dest2.layout.ConversionPattern=[%d{ISO8601}]%5p%6.6r[%t]%x(%F:%L) - %m%n
! Or, (the pattern below will slow down your app)
#log4j.appender.dest2.layout.ConversionPattern=[%d{yyyy-mm-dd hh:mm},%6.6r]%-5p[%t]%x(%F:%L) - %m%n


! FORMAT LOG MESSAGES IN THE FORM OF AN HTML TABLE
#log4j.appender.dest3.layout=org.apache.log4j.HTMLLayout
! Include Java file name and line number (Default is false)
#log4j.appender.dest3.layout.LocationInfo=true
! Set <title> tag (Default: Log4J Log Messages)
#log4j.appender.dest3.layout.Title=My App Log


!-----------------------------------------------------------------------------!
!                          PATTERN FORMATS GLOSSARY                           !
!-----------------------------------------------------------------------------!
! %n - newline                                                                !
! %m - your log message                                                       !
! %p - message priority (FATAL, ERROR, WARN, INFO, DEBUG or custom)           !
! %r - millisecs since program started running                                !
! %% - percent sign in output                                                 !
!                                                                             !
!-----------------------SOME MORE CLUTTER IN YOUR LOG-------------------------!
! %c - name of your category (logger), %c{2} will outputs last two components !
! %t - name of current thread                                                 !
! %x - Nested Diagnostic Context (NDC) (you supply it!)                       !
!                                                                             !
!-------------------------SLOW PERFORMANCE FORMATS----------------------------!
! %d - date and time, also %d{ISO8601}, %d{DATE}, %d{ABSOLUTE},               !
!        %d{HH:mm:ss,SSS}, %d{dd MMM yyyy HH:mm:ss,SSS} and so on             !
! %l - Shortcut for %F%L%C%M                                                  !
! %F - Java source file name                                                  !
! %L - Java source line number                                                !
! %C - Java class name, %C{1} will output the last one component              !
! %M - Java method name                                                       !
!                                                                             !
!------------------------------FORMAT MODIFIERS-------------------------------!
! %-any_letter_above - Left-justify in min. width (default is right-justify)  !
! %20any_letter_above - 20 char. min. width (pad with spaces if reqd.)        !
! %.30any_letter_above - 30 char. max. width (truncate beginning if reqd.)    !
! %-10.10r - Example.  Left-justify time elapsed within 10-wide field.        !
!              Truncate from beginning if wider than 10 characters.           !
!-----------------------------------------------------------------------------!


!-----------------------------------------------------------------------------!
!                             OPTIONS GLOSSARY                                !
!-----------------------------------------------------------------------------!
!-------------------------OVERALL OPTIONS FOR log4j---------------------------!
! Specify as command line option: -Dlog4j.defaultInitOverride=false
! Specify as command line option: -Dlog4j.configuration=app_config.properties
!#log4j.debug=true
!#log4j.disable=INFO
!#log4j.disableOverride=false
!#log4j.additivity.your.category.name=false
!
!----------------------------NullAppender OPTIONS-----------------------------!
!#log4j.appender.dest1.Threshold=INFO
!
!---------------------------ConsoleAppender OPTIONS---------------------------!
!#log4j.appender.dest1.Threshold=INFO
!#log4j.appender.dest1.ImmediateFlush=true
!#log4j.appender.dest1.Target=System.err
!
!-----------------------------FileAppender OPTIONS----------------------------!
!#log4j.appender.dest2.Threshold=INFO
!#log4j.appender.dest2.ImmediateFlush=true
!#log4j.appender.dest2.File=mylog.txt
!#log4j.appender.dest2.Append=false
!
!-------------------------RollingFileAppender OPTIONS-------------------------!
!#log4j.appender.dest2.Threshold=INFO
!#log4j.appender.dest2.ImmediateFlush=true
!#log4j.appender.dest2.File=mylog.txt
!#log4j.appender.dest2.Append=false
!#log4j.appender.dest2.MaxFileSize=100KB
!#log4j.appender.dest2.MaxBackupIndex=2
!
!-----------------------DailyRollingFileAppender OPTIONS----------------------!
!#log4j.appender.dest2.Threshold=INFO
!#log4j.appender.dest2.ImmediateFlush=true
!#log4j.appender.dest2.File=mylog.txt
!#log4j.appender.dest2.Append=false
!#log4j.appender.dest2.DatePattern='.'yyyy-ww
!
!-----------------------------SimpleLayout OPTIONS----------------------------!
!**None**
!
!-------------TTCCLayout OPTIONS (PatternLayout is more flexible)-------------!
!#log4j.appender.dest1.layout.DateFormat=ISO8601
!#log4j.appender.dest1.layout.TimeZoneID=GMT-8:00
!#log4j.appender.dest1.layout.CategoryPrefixing=false
!#log4j.appender.dest1.layout.ThreadPrinting=false
!#log4j.appender.dest1.layout.ContextPrinting=false
!
!-----------------------------PatternLayout OPTIONS---------------------------!
!#log4j.appender.dest1.layout.ConversionPattern=%m%n
!
!-------------------------------HTMLLayout OPTIONS----------------------------!
!#log4j.appender.dest3.layout.LocationInfo=true
!#log4j.appender.dest3.layout.Title=My app title
!
!--------------------------------XMLLayout OPTIONS----------------------------!
!#log4j.appender.dest3.layout.LocationInfo=true
!-----------------------------------------------------------------------------!

Miscellaneous Information


© Vipan Singla 2001