A very simple incorporation of log4j is here!If you really want to know as to how to incorporate log4j logging in your application, here are the details. Though this is simple, I see a bunch of questions related to this in every java related forum and hence I thought of posting this blog!
If you want to change the level of logging, you can make the warninggs or information to get printed in the log file by changing the log4j.rootCategory to INFO, WARN etc.
- Let us have a simple Bean.xml and Bean.class. the xml file has the bean definition and the bean class just prints a string. This is a very simple application written to make you all understand the incorporation of log4j!
- Just create a Spring Project in eclipse (since am using a bean and bean.xml is being used for configuring the bean). The project hierarchy is as shown below. You also have a log4j.properties file (empty file) in the classpath of this project as shown below:
- Select the project.Right click and go to properties. Here you can add the required jars. For the implementation of log4j in a spring project, you would need
- Spring jars (all the 3.0 version jars)
- log4j.jar(latest)
- Now add the following code to your log4j.properties.
# Set root category for logging error messages log4j.rootCategory=ERROR,AppAppender # Debug statements logged by Spring framework. log4j.category.org.springframework=ERROR, AppAppender #AppAppender is set to DailyRollingFileAppender and new file rolls every day. log4j.appender.AppAppender.File=/logs/application.log log4j.appender.AppAppender=org.apache.log4j.DailyRollingFileAppender log4j.appender.AppAppender.DatePattern='.'yyyyMMdd log4j.appender.AppAppender.layout=org.apache.log4j.PatternLayout
- Now just run bean.java as a java application. Only errors get printed in the log gile.
If you want to change the level of logging, you can make the warninggs or information to get printed in the log file by changing the log4j.rootCategory to INFO, WARN etc.
- If you have a directory hewrarchy in your application, you can enable logging levels for each of the package by adding an entry as
<br /><br />log4j.category.org.<your package structure>==ERROR, AppAppender<br /><br />
- AppAppender is nothing but a file in the logs folder under c: whose layout, date pattern and type are as described in the code above. Here, it is a daily rolling appender. A new file gets created everyday and the old file is stored after being renamed with proper dates.