How to use Log4j – An efficient and sufficient guide with examples
Logging, in short, is required to track programming flow. It is very difficult to track code flow or to find faults in Big applications. Log4j makes it easier.
Log4j is usually configured using a property file or XML file externally. You can easily control its behavior through configuration file without modifying the source code.
Prerequisite
- What is log4j and why to use it – A short review
- Download and import log4j.jar to your project.
Main components
- Logger – used to log messages
- Appender – specifies the output destination like console or a file (default ConsoleAppender)
- Layout – specify the format in which the log messages should be logged (default PatternLayout)
In short to remember
- Logger – Who writes to log (Worker)
- Appender – Tells where to write (Navigator)
- Layout – format the log message (Designer)
Sample configuration file
log4j.rootLogger=WARN, CA log4j.appender.CA=org.apache.log4j.ConsoleAppender log4j.appender.CA.layout=org.apache.log4j.PatternLayout log4j.appender.CA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n<span style="font-size: 10pt; font-family: &quot;Courier New&quot;;"> </span></pre> <pre>
Explanation -1st line in above configuration line is used to declare logger (who will write). 2nd line is declaring appender (Where he will write). 3rd & 4th line are saying in what format logger will write.
You can define any number of loggers per your need. Every logger will have an appender and a pattern layout. You can specify more setting that we learn in further session.
Level – Many times we need to write error log in a separate log file while debug logs in separate log files. Log4j ease to write logs in separate log files for a same logger based on their levels.
The log4j levels follow the following order.
- DEBUG
- INFO
- WARN
- ERROR
- FATAL
In the above sample configuration file, logger level is set to WARN. It means, all log message up to WARN level (WARN, ERROR and FATAL) will be written to console (since appender type is ConsoleAppender). Rest logs would be dropped.
- Errors
- Client IP tracke
- Login, Logout time
- etc.
How to write logs
Once you have done all settings in configuration file ie log4j.properties, place it on the root of your project folder. Your application will pick it automatically. Now
- You just need to create an object of logger class in your application.
public static Logger as_looger = Logger.getLogger("CA");
- And write log statement as we write System.out.println(). You can pass Exception object. It automatically prints stack trace.
as_logger.debug(“article-stack.com has been started.”);
Sample Application

- Create a java project
- Create a class, say basic.java
package com.articlestack.log4j; import org.apache.log4j.Logger; /** * This class fetch log settings from log4j.properties * @author amty */ public class basic { static final Logger logger = Logger.getLogger("CA"); public static void main(String[] args) { logger.debug("Sample debug message"); logger.info("Sample info message"); logger.warn("Sample warn message"); logger.error("Sample error message"); logger.fatal("Sample fatal message"); } } - Create log4j.properties. And place it to root of your project folder (refer above screen shot)
log4j.rootLogger=WARN, CA log4j.appender.CA=org.apache.log4j.ConsoleAppender log4j.appender.CA.layout=org.apache.log4j.PatternLayout #log4j.appender.CA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n #log4j.appender.CA.layout.ConversionPattern=%5r %-5p [%t] %c{2} - %m%n log4j.appender.CA.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %c{1} [%p] %m%n*Change the level WARN to DEBUG or to ERROR or something else. Run the application. And check what you get on console.
Some Alternates
- My own property file
Don’t you wanna refer log4j.properties? You can create your own property file similar to log4j.properties. Now place it somewhere. And configure its path through code.PropertyConfigurator.configure("amtyLog.properties");
- No property file
Don’t you wanna refer any property file?You can create a log class. You can do all settings from java code instead property file. Refer the below class.package com.articlestack.cofig; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; public class Log { public static Logger as_looger; public Log(){} static { as_looger = Logger.getLogger("articles logging"); ConsoleAppender as_appender = new ConsoleAppender(new PatternLayout("%d{dd-MM-yyyy HH:mm:ss} %C %L %-5p: %m%n")); as_looger.setLevel(Level.DEBUG); as_looger.addAppender(as_appender); } }Now you can log from any java class very easily
Log.as_looger.debug("DEBUG");
Please note thisYou can skip reading this. This is just an Appendix.
The org.apache.log4j.Level class provides following levels but you can also define your custom levels by sub-classing the Level class.
Level Description ALL All levels including custom levels. DEBUG Designates fine-grained informational events that are most useful to debug an application. ERROR Designates error events that might still allow the application to continue running. FATAL Designates very severe error events that will presumably lead the application to abort. INFO Designates informational messages that highlight the progress of the application at coarse-grained level. OFF The highest possible rank and is intended to turn off logging. TRACE Designates finer-grained informational events than the DEBUG. WARN Designates potentially harmful situations. *Above levels are alphabetically short not by priority.
I had tried to cover all basic concepts of log4j in this article. Tell me if something is not clear to your or missing. Now the time is to use the power of log4j. That we’ll discuss in next article.
Complete class
package com.articlestack.log4j;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class anotherFile {
static final Logger logger = Logger.getLogger("AC");
public static void main(String[] args) {
PropertyConfigurator.configure("amtyLog.properties");
logger.debug("Sample debug message");
logger.info("Sample info message");
logger.warn("Sample warn message");
logger.error("Sample error message");
logger.fatal("Sample fatal message");
}
}
views


JP @ unsupportedclassversionerror
4 Jul, 2011
Nice tips. In my opinion using correct logging level for different message is most important thing to learn and logging has important performance impact (ever found process running in DEBUG mode in production ) and has to be handled efficiently. I have also blogged my tips as my favorite java logging tips , let me know how do you find it.
Amit Gupta
8 Jul, 2011
@JP, its good that you find this post useful. But I never visited your site before as you stated in your last sentence.
Shrida
20 Sep, 2012
Hey Amit,
nice article…can you please help me in finding how could i make use of log4j to write the log files to hadoop
Amit Gupta
22 Sep, 2012
I never worked on Hadoop. But I googled “hadoop log4j” and found some good stuff. Read this from their official http://wiki.apache.org/hadoop/HowToConfigure
I hope it’ll help you