Log4J is the frame work used extensively in today java based example. It is based on singleton design pattern i.e. only one instance of Log class is maintained and hence is highly performance oriented.
Log4J has three main components
1- Logger: - This is base class which does the activity of logging. Advantage of this class is that we can differentiate the logging text in five different aspects. i.e. DEBUG, INFO, WARN,FATAL and ERROR.
2- Appender :- This is used to define the appender base. i.e. we had different appender like console, log file, xml,remote sockets etc.
3- Layout:- Define the layout in which format and layout structure we want the output. Many times it become easy to store the log file on date wise, sometime our requirement ask us to store the log files depends on its size. It the size get greater than specific number layout help us to crate a new file.
All the above three aspect of Log4J can be controlled by one single configuration files either it is called as log4j.xml or log4j.properties. If we had both then xml always take presentence over properties files.
#set the rootloger priority to DEBUG and its appender to stdout
log4j.rootLogger=debug, stdout, R
#set stdout to console appender
#set layout to PatternLayout
# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
# Keep one backup file
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
#Print only message of Priority WARN or above in the package com.test.myapp
Disadvantage using logger if not handled properly.
- In production it is generally mistaken to keep the Log level at DEBUG, but this wrong. Keeping log level to DEBUG will create huge log file on expense of loggin it. So generally for Production it is used as ERROR or FATAL.
- Don’t try to use accessed method in log in side loop
This will execute even though you had not set your log level to debug. In such case it is always advisible to use condition base logging.
How to Initialize and use Log4j?
Use following sets of line to log your application logger
Static Logger log = Logger.getLog(“com.test.siddhu.MyLogClass”);
log.debug(“Print this when logger level is set to DEBUG”);