If you are new to Log4j, here is a short description on what is it and why should we care about it:
Log4j is a flexible logging library, an open source project from Apache. Using Log4j, we can replace the debugging print line statements, like System.out.println(“Value is ” + someVariable), with a configurable logging statement like logger.debug(“Value is ” + someVariable). The advantage in using Log4j is, if you do not want to print the debugging print lines in production application, you can easily switch them off using Log4j configuration file (which we will see it how, shortly).
How to add Log4j logger support to your project?
- Download the latest Log4j distribution from Apache website (at the time of this article is written, the latest version of Log4j is 1.2) and put the log4j-xxx.jar in your project class path. For Java web application, you can place the jar file in WEB-INF/lib folder. For Java applications, you can place the jar in any folder, but remember to add the folder to your classpath.
- Next we need to configure the Log4j library to our requirements. Log4j reads its configurations from log4j.properties file (or log4j.xml) placed in the CLASSPATH. Every log4j.properties file defines the following three things, mainly:
-
- an Log4j Appender – this is the class file which does the actual logging. It could be a simple Console appender which writes the log messages to stdout (screen) or a file appender, which sends the log messages to a log file.
- a Layout – is nothing but how the log message is formatted. This format is very simlar to C languages’s printf function formatting.
- and a Logger – a logger ties the appender with the log messages that are coming from the Java application. Basically, a logger tells that the log messages from these packages should go to some appender which will log the message in the defined layout.
- Below is a sample log4j.properties for configuring the console appender for your project.
#define the console appender log4j.appender.consoleAppender = org.apache.log4j.ConsoleAppender # now define the layout for the appender log4j.appender.consoleAppender.layout = org.apache.log4j.PatternLayout log4j.appender.consoleAppender.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n # now map our console appender as a root logger, means all log messages will go to this appender log4j.rootLogger = DEBUG, consoleAppender
In the above properties file, we are first defining a Console appender and a layout pattern (refer this complete documentation to know what’s the weired symbols in the conversion patterns means). Then we are mapping all the DEBUG level log messages from the entire application to go into the consoleAppender, since we added the consoleAppender to the rootLogger.
- In any of your Java file, add the below lines, in order to start logging:
private static Logger logger = Logger.getLogger(MyclassName.class); logger.debug("this is a sample log message."); - Now you are done. Run your application and you should be seeing the log messages coming in your console window.
Next: How to send log messages to a file?


{ 25 comments… read them below or add one }
Nice description.
.-= vishnu´s last blog ..??? ????? ?????? =-.
nice tut
thanks!
so, what’s about java.util.logging, log4j vs jul ?
I’ve never used any logging frameworks, other than log4j. Even I would like to learn about java.util.logging. Will try to publish tutorial for that also.
Have a look at logback, log4j’s successor. It’s very similar to log4j but better.
logback looks impressive. Will definitely give it a try.
Good. If you look closely, I am confident that you will find at least one cant-live-without feature that will have you prefer logback over log4j.
Hi Veera,
Your explanations made me to understand log4j quickly.
Please explain how the following can be achieved.
1) Seperate log file for each java class
2) Log files getting created must be stored in datewise folder.
nice tut
Any comments on SLF4J static binding with log4j or other logging frameworks? And also about how to NOT use commons-logging. Very often my profiling tools show that logging is the one place I am using too much time.
Oftentimes I end up doing something like the following:
if(currently active logging level > INFO) {
logger.info(String.format(“…..”,…);
}
thanks and its simple to understand in the same way in there any bugs means errors will coming configuration and run in project explian how it will be handled.
some possible errors and how it will be handled………..
once again thanks
quick and easy….
thanks veera…
could u tell me how can we work with log4j in eclipse
There are no special instructions for Eclipse alone. You can download the log4j jar, put it somewhere in your file system. Then, in Eclipse, right click on your project name and go to properties. there you can add the log4j JAR file to CLASSPATH.
Once that is done, follow the steps mentioned in this post and then you should be able to log message.
let me know in case you need any help.
thanks
hey sunder ,
i am new to eclipse. i had developed a simple project and build the project with ANT s/w.in the build i made a target to build a jar file. can u please tell me where i can find that jar file where i have developed.
give the details in a step by step process.thanks for ur last reply
Ramu,
in your build.xml file you would be having a target to build JAR file, something like:
<jar destfile="build/jar/HelloWorld.jar" basedir="build/classes">: in this case, the JAR file will be created in the directory PROJECT BASE DIRECTORY/build/jar/ and HelloWorld.jarHey Veera,
I have been trying to log my application, but it is still not working. I have the log4j.properties file configured right as you explained in one of the other posts, but I still can’t get the appender to write to the file I specify. It writes to the console in Eclipse instead. Also, the logger instantiation:
private static Logger logger = Logger.getLogger(MyclassName.class);
does not seem to work in my Java class, the syntax error I get is that Logger.getLogger method has a string argument so it should be Logger.getLogger(String subsystem), so what I did is just put in my clasess’s name (one i want to log) as a string argument. Can this be the problem for not getting the logger to write in the specified file? Any help is appreciable.
Thanks,
If you are getting the syntax error at
Logger.getLogger, it might be because the compiler can’t find the log4j JAR file in CLASSPATH. From your comment, I guess that you are using Java’s Logger utility , which is different from Log4j and takes a String as an argument.Please verify whether you have added the log4j.jar file to the class path and ensure that you have imported the Log4j Logger from by checking the import statements. It should be something like this.
import org.apache.log4j.Logger;Great! Thanks a lot Veera! Helped me meet my deadline.
Hi Veera,
Nice tutorial… I wanted to create separate log file on different folder on my every execution based on some logic. Can you please tell me how I can do it?
Regards,
Chetan
Kindly send me the Log4j pdf.
Thank You………..
Hi Veera,
I went through your instructions and implemented the above block of code, how ever i am receiving below error.
=================
D:\>javac testlogger.java
testlogger.java:20: error: expected
logger.DEBUG(“this is a sample log message”);
^
testlogger.java:20: error: illegal start of type
logger.DEBUG(“this is a sample log message”);
^
2 errors
D:\>
=================
At code : logger.debug(“message”);
================
I have the above code written in an servlet program.
I have few questions on setting up Class path.
My class path = .;C:\apache-tomcat-6.0.28\lib\servlet-api.jar
I have log4j 1.2.16 downloaded to below location
C:\apache-tomcat-6.0.28\webapps\examples\WEB-INF\lib,
Do let me know if i have to download log4j 1.2.16 to this location : , which is my class path : C:\apache-tomcat-6.0.28\lib\
Please get this fixed for me.
I got it fixed by myself, i mean, i changed the class path and restarted the server, it started to work
{ 3 trackbacks }