29 July 2011

How to add and configure log4j.XML file in Spring 3

Solution works for Spring 3.0.5 and log4j  1.2.16 (but it should works with previous/future releases of both programs)

It is really easy task:

I assumed that you already has spring 3 stuff in place.
  1. You need add log4j to your libraries in your project
  2. Add information about log4j to web.xml file (It should be /MyCozyProject/src/main/webapp/WEB-INF/web.xml  
  3. Add information about location for log4j.xml  in context.xml
  4. Configure your log4j 
Information which you need add in .2 (It tells spring where to look for information about log4j)

In 3. in context.xml (usually should be /src/main/webapp/META-INF/context.xml ) add information about where your log4j.xml file is
<Context displayName=" MyCozyProject ">
    <Parameter name="log4jConfigLocation" value="file:C:\myCozyProject\log4j.xml"/>

In 4 You just configure your log4j to your needs (below is example of saving log to file)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

<appender name="tofile" class="org.apache.log4j.FileAppender">
  <param name="file" value="C:\\myCozyProject.log"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ABSOLUTE} %5p %c{1}:%L - %m%n"/>

<priority value ="info" />
<appender-ref ref="tofile" />


 btw. If you want log4j.xml inside project, then you can use my example or check this blog :