Spring log4j configuration
Every application requires logging mechanism. This page shows how to introduce logging mechanism to the spring framework using
log4j. It is pretty simple to configure logging with log4j. First, add maven dependency in your pom.xml file.
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
<type>jar</type>
</dependency>
|
Create log4j.properties file with the below content, and place it with in /src/main/resources folder, so that it will be
available in the application class path. Walk through each property and changes the settings as per your needs. Below configuration makes log
entries into file and on the console as well.
# Root logger option
log4j.rootLogger=INFO, file, stdout
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=test_logfile.log
log4j.appender.file.MaxFileSize=5MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
# Direct log messages to stdout
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{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
|
Finally, add your logs with in the class level. You are done with your log settings. The application is ready for logging.
package com.java2novice.test;
import org.apache.log4j.Logger;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.java2novice.beans.PaymentGateway;
public class SpringDemo {
static final Logger logger = Logger.getLogger(SpringDemo.class);
public static void main(String a[]){
logger.info("getting application context file...");
String confFile = "applicationContext.xml";
ConfigurableApplicationContext context
= new ClassPathXmlApplicationContext(confFile);
logger.info("getting bean reference...");
PaymentGateway paymentGateway = (PaymentGateway) context.getBean("paymentGateway");
System.out.println(paymentGateway.toString());
logger.info("done...");
}
}
|
|