As logging required in every project. Log4j provided by Apache to add logging to your system in best way. I also required logging to my application and decided to use Log4j but could find any comprehensive tutorial about logging as somewhere basic were forund and advance use on other site. the way you want to add logging into your application is also vary to normal system sometime. thats why i had to read many tutorial to implement loggin as my requirements. here i will cover applying logging in different and hope it will cover your requirement of logging. here goes my comprehensive tutorial for Log4j.
I will cover following thing in this Post/tutorial
-Simple logging tutorial
- Logging on console and File
- How to manage logging in different files and size
- How to do logging on different file for different package or for different functional functionality withing the application.
let me first introduce you LOG4J
Log4j is a Reliable, Fast and Flexible Logging Framework (APIs) written in Java which is distributed under the Apache Software License.
Log4j has been ported to the C, C++, C#, Perl, Python, Ruby, and Eiffel languages.
Log4j is highly configurable through external configuration files at runtime. It views the logging process in terms of levels of priorities and offers mechanisms to direct logging information to a great variety of destinations, such as a database, file, console, UNIX Syslog etc.
Log4j has three main components:
- loggers: Responsible for capturing logging information.
- appenders : Responsible for publishing logging information to various preferred destinations.
- layouts:Responsible to format logging information in different styles.LOGER :
The logger is the core component of the logging process. In log4j, there are 5 normal levels Levels of logger available (not including custom Levels), the following is borrowed from the log4j API (http://jakarta.apache.org/log4j/docs/api/index.html):
- static Level DEBUGThe DEBUG Level designates fine-grained informational events that are most useful to debug an application.
- static Level INFOThe INFO level designates informational messages that highlight the progress of the application at coarse-grained level.
- static Level WARNThe WARN level designates potentially harmful situations.
- static Level ERRORThe ERROR level designates error events that might still allow the application to continue running.
- static Level FATALThe FATAL level designates very severe error events that will presumably lead the application to abort.
In addition, there are two special levels of logging available: (descriptions borrowed from the log4j API http://jakarta.apache.org/log4j/docs/api/index.html):
- static Level ALLThe ALL Level has the lowest possible rank and is intended to turn on all logging.
- static Level OFFThe OFF Level has the highest possible rank and is intended to turn off logging.
The behaviour of loggers is hierarchical. The following table illustrates this:

There are a number of ways to create a logger, one can retrieve the root logger:
Logger logger = Logger.getRootLogger();
Logger logger = Logger.getLogger("MyLogger");More usually, one instantiates a static logger globally, based on the name of the class:
static Logger logger = Logger.getLogger(test.class);
All these create a logger called “logger”, one can set the level with:
logger.setLevel((Level)Level.WARN);
APPENDER:
The Appender controls how the logging is output. The Appenders available are (descriptions borrowed from the log4j API http://jakarta.apache.org/log4j/docs/api/index.html):
- ConsoleAppender: appends log events to System.out or System.err using a layout specified by the user. The default target is System.out.
- DailyRollingFileAppender extends FileAppender so that the underlying file is rolled over at a user chosen frequency.
- FileAppender appends log events to a file.
- RollingFileAppender extends FileAppender to backup the log files when they reach a certain size.
- WriterAppender appends log events to a Writer or an OutputStream depending on the user’s choice.
- SMTPAppender sends an e-mail when a specific logging event occurs, typically on errors or fatal errors.
- SocketAppender sends LoggingEvent objects to a remote a log server, usually a SocketNode.
- SocketHubAppender sends LoggingEvent objects to a set of remote log servers, usually a SocketNodes
- SyslogAppendersends messages to a remote syslog daemon.
- TelnetAppender is a log4j appender that specializes in writing to a read-only socket.
One may also implement the Appender interface to create ones own ways of outputting log statements.
LAYOUT:
- HTMLLayout formats the output as a HTML table.
- PatternLayout formats the output based on a conversion pattern specified, or if none is specified, the default conversion pattern.
- SimpleLayout formats the output in a very simple manner, it prints the Level, then a dash ‘-’ and then the log message.
1. Basic Log4j Basic Example:
To implement the log4j in your application, following you have to do.
- Create Properties file for log4j in your plication at root : log4j.properties
what you to define in the properties file. this is example of properties for logging on console
log4j.rootLogger = stdout // the root logger that is applied to whole aplication, if you dont wanted to apply this “stdou” logger at whole application then see below how to change to required use
log4j.appender.stdout=org.apache.log4j.ConsoleAppender // define appender, here is console
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L – %m%n // layour of log, how it should be printed
-Initialize logger in your application, as many ways are written above how to initialize.
the basic ways is(write this initialization code at starting of the class) :
static Logger log = Logger.getLogger(Myclass.class.getName());
- User logger object (initialized in your class) to perform logging. write log statment anywhere in the class like this.
log.debug(“this is first log”)
log.info(“this is first log”)
…………………………….
log.fatal(“this is first log”)
SO! thi is the basic one and its SIMPLE !!! not much complexity
- Logging in file
-Plus logging on console
- Manage logging file size
-Backup logging files
Properties file:
log4j.rootLogger = stdout ,FILE // Console and File logging
log4j.appender.stdout=org.apache.log4j.ConsoleAppender // Console logging
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L – %m%n
# Define the file appender
log4j.appender.FILE=org.apache.log4j.RollingFileAppender //file logging
log4j.appender.FILE.File=first.log //log file name
log4j.appender.FILE.MaxFileSize=2MB //log file size, if size increase to this then new file will be created
log4j.appender.FILE.MaxBackupIndex=2 //backup will be persist until two files
# Define the layout for file appenderlog4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n
3. File logging (with multipal files)
what you will achieve here
- Console loggign
- File logging
- define multiple log files within application
you can do it by two way.
3.1 -Define multipal log files
- for each log file define package of the application(mean “first.log” is for ”com.mypackage1 and come.mypakage2″ etc)
to implement this functionality yoz need to change log4j propertiues files and in the code intilization of the logger.
log4j.properties file:
# Define the root logger with appender file
log4j.rootLogger = stdout ,FILE, EXPORT
log4j.appender.stdout=org.apache.log4j.ConsoleAppender // Console logging
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L – %m%n
# Define the file appender
log4j.appender.FILE=org.apache.log4j.RollingFileAppender //file logging
log4j.appender.FILE.File=first.log //log file name
log4j.appender.FILE.MaxFileSize=2MB //log file size, if size increase to this then new file will be created
log4j.appender.FILE.MaxBackupIndex=2 //backup will be persist until two files
# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n
log4j.logger.com.mypackage1=info, EXPORT
log4j.logger.com.mypackage2=info, EXPORT
log4j.logger.com.mypackage1=info, EXPORT
# Define the file appender
log4j.appender.EXPORT=org.apache.log4j.RollingFileAppender
log4j.appender.EXPORT.Threshold=fatal
log4j.appender.EXPORT.File=second.log // second log file
log4j.appender.EXPORT.MaxFileSize=2MB
log4j.appender.EXPORT.MaxBackupIndex=2
# Define the layout for file appender
log4j.appender.EXPORT.layout=org.apache.log4j.PatternLayoutlog4j.appender.EXPORT.layout.conversionPattern=%m%n
to implement logging to specific to package is marked as RED .
now initialize the logger like this.
static Logger log =Logger.getLogger(“FILE”); for first log file , use this intialization in the code where you wanted to perform logging in first file
static Logger log =Logger.getLogger(“EXPORT”); for second log file , use this intialization in the code where you wanted to perform logging in second file
logging statements in the code you dont need to change(except you change the logging level)
3.2- Define different debug level for different files.
- for first.log define “fatal” logging level like this “log4j.appender.FIRST.Threshold=fatal”
- for second.log define “info” logging level like this “log4j.appender.SECOND.Threshold=debug”
how it helps, where you wnated to write limited log or related to some functionality use first logger becouse its lowses loggign level so its only print the
log.fatal(…..) statements log in the file.
for the rest of the application used second logger because its logging level is debug and its cover almost all logging level, therefor its write all log statement of application in log file.
log.debug(…..)
log.info(…..) etc you can check in above colorfull table how much logging level debug covers.
how you can implement in your application. for this you have to Chane your log4j. properties file, logging initialization and log statement in the code
log4j.properties :
# Define the root logger with appender file
log4j.rootLogger = stdout ,FILE, EXPORT
log4j.appender.stdout=org.apache.log4j.ConsoleAppender // Console logging
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L – %m%n
# Define the file appender
log4j.appender.FILE=org.apache.log4j.RollingFileAppender //file logging
log4j.appender.FILE.File=first.log //log file name
log4j.appender.FILE.MaxFileSize=2MB //log file size, if size increase to this then new file will be created
log4j.appender.FILE.MaxBackupIndex=2 //backup will be persist until two files
# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n
# Define the file appender
log4j.appender.EXPORT=org.apache.log4j.RollingFileAppender
log4j.appender.EXPORT.Threshold=fatal
log4j.appender.EXPORT.File=second.log // second log file
log4j.appender.EXPORT.MaxFileSize=2MB
log4j.appender.EXPORT.MaxBackupIndex=2
# Define the layout for file appender
log4j.appender.EXPORT.layout=org.apache.log4j.PatternLayoutlog4j.appender.EXPORT.layout.conversionPattern=%m%n
here you can see two log file.
what you have to change to intialize loggign in code. see below
static Logger log =Logger.getLogger(“FILE“); for first log file , use this intialization in the code where you wanted to perform logging in first file
static Logger log =Logger.getLogger(“EXPORT“); for second log file , use this intialization in the code where you wanted to perform logging in second file
becouse the second file we have define logging leve is FATAL, functionality in second filespecificthis line to perform logging for some write
log.fatal(“………”);
for the fist logging you can use any statement like log.debug, log.info because first logging level is debug which covers all.
Hope it helps you!!! if you like this post please comment and share with other.
Superb
Thanks
keep visiting