Spring Log4j Integration

Spring Log4j Integration guide developers to configure logger for spring application as it is required to log messages, exceptions.  Spring uses commons logging by default. To use log4j logging, just add the log4j.jar to application.

Spring Log4J Configuration:

 

  •  add log4j dependency
 <dependency>
 <groupId>log4j</groupId>
 <artifactId>log4j</artifactId>
 <version>1.2.17</version>
 </dependency>
  • create log4j.properties file in src/main/resources folder as shown in below :Spring Log4J Configuration
  • copy the below log4j properties:

 

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%p] (%c{2}):%L - %m%n

log4j.appender.logFile=org.apache.log4j.RollingFileAppender
log4j.appender.logFile.File=C:/logs/App.log
log4j.appender.logFile.MaxFileSize=10MB
log4j.appender.logFile.MaxBackupIndex=10
##log4j.appender.logFile.Threshold=debug
log4j.appender.logFile.layout=org.apache.log4j.PatternLayout
log4j.appender.logFile.layout.ConversionPattern=%d [%p] (%c{2}):%L - %m%n


log4j.rootLogger=INFO, stdout, logFile

In the classes, you can access Log4J logger like below:

import org.apache.log4j.Logger;
public class CustomerController {
 
 Logger LOG = Logger.getLogger(CustomerController.class.getName());

 @GetMapping("/")
 public String getHome(){
     LOG.info("Home page invoked");
     return "redirect:customers.action";
 }
}

Log4J Listerner  is @Deprecated and   not required to register in web.xml

In some applications, you may still see the below config, but it is not required to register listener configuration in web.xml file ass  Log4JConfigListener class is deprecated Spring 4 version.

 <context-param>
 <param-name>log4jConfigLocation</param-name>
 <param-value>/WEB-INF/log4j.properties</param-value>
 </context-param>
 <listener>
 <listener-class>org.springframework.web.util.Log4jConfigListener
 </listener-class>
 </listener>

 

Leave a Comment

Your email address will not be published. Required fields are marked *