Set up logging with log4j

We would like to create an application log now, so we can insert log statements in our java code. This is important because when we run our application from the tomcat server, we don’t always see what is going on from the console. Note that we won’t see our log file appear until after we add logging statements to java classes, redeploy, and run new the application in the next steps.

Let’s just get the configuration started now:

1. Add the log4j dependency to your pom.xml

Open up your pom.xml file in Eclipse and add the following to your list of dependencies:

<dependency>
   <groupId>log4j</groupId>
   <artifactId>log4j</artifactId>
   <version>1.2.14</version>
   <type>jar</type>
   <scope>compile</scope>
</dependency>

2. Create a new file called log4j.properties inside your “src/main/resources” folder

This is an example properties file that will get you up and running fast. You just have to specify where you want the log file to go. You can have the log write anywhere you wish. My log is inside my project at this path /Users/altheaparker/Documents/workspace/SpringGreetings/springgreetingslog.log

But, the log can also be outside the project and is often better to do so.

log4j.properties
log4j.debug=TRUE
log4j.rootLogger=INFO, R

log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=/Users/altheaparker/Documents/workspace/SpringGreetings/springgreetingslog.log
log4j.appender.R.MaxFileSize=100KB
log4j.appender.R.MaxBackupIndex=5
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSSS} %p %t %c \u2013 %m%n

This is just an example configuration! There are many ways to configure log4j. You can also configure log4j using an xml file which might be easier and more flexible, depending on your needs.

3. Add logging code to your java classes

When it comes time to add the java classes, here is how you can add logging statements to your java code. We will do this later.

GreetingController.java
package com.bitbybit.web.controller;
 
import java.util.logging.Logger;
 
public class GreetingController {
 
	protected static Logger logger = Logger.getLogger("GreetingController");
 
	public String showAllGreetings() {
		logger.info("entering method showAllGreetings()");
		return "some result";
	}
 
}

1 Comment
Clement wrote on 2012-10-17 at 14:37:46:
Simple and straight forward. Could you please add SpringJDBCTemplate examples as well?


Post a Comment

(required):