Log4j Configuration in Spring Application

Hi,
As we all know how loggers plays a crucial part in managing program flow messages  in the application.
Your application gets  better control on what messages needs to be logged to the files. This can be achieved using the Log Levels. For example., INFO, DEBUG, WARN, ERROR, FATAL etc. For more details on Log4J Framework, Read here @http://logging.apache.org/log4j/1.2/

Now lets see below the LOG4J Configuration in Spring App.

1. In Web.xml add the below entries.

<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/classes/log4j.properties</param-value>
<!– specify the log properties file location –>
</context-param>

<listener>
<!– spring based logger listener, which will read the log config and start the logger service  –>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>

2. Add the below log4j.properties inside. WEB-INF/classes/ folder.

# Set root logger level to INFO
log4j.rootLogger=INFO, ET

log4j.category.ETlogger=INFO,ET
# ET is set to be a File.
log4j.appender.ET=org.apache.log4j.DailyRollingFileAppender
log4j.appender.ET.File=ETLogger.log
log4j.appender.ET.DatePattern=’.’yyyy-MM-dd
log4j.appender.ET.Threshold=info
log4j.appender.ET.Append=true
log4j.appender.ET.ImmediateFlush=true

# ET uses PatternLayout.
log4j.appender.ET.layout=org.apache.log4j.PatternLayout
log4j.appender.ET.layout.ConversionPattern=[ %-5d %-5p %-4rms ] %F : %L – %m%n

3. Now load the logger from the Log factory in your Java class.

public static Logger logger = Logger.getLogger(“ET”);
OR public static Logger logger = Logger.getLogger();
logger.info(“Test message”);

I will try to post a new material on how to use Logging effectively in the application. Wait for that 😉


Thanks
R Vashi

One thought on “Log4j Configuration in Spring Application

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s