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:


2. Create a new file called 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.rootLogger=INFO, R

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.
package com.bitbybit.web.controller;
import java.util.logging.Logger;
public class GreetingController {
	protected static Logger logger = Logger.getLogger("GreetingController");
	public String showAllGreetings() {"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