Friday, August 27, 2010

Creating server logs with Log4j

By using Log4J, it can make log files on server side easily.

Log4j is a easy way to manage logs on server side. Mostly logs are written to a log file on the server to keep track of changes. We can write a log to a fie using two different methodologies. One is by using a XML file and the other is by using a property file.

  • Using an XML file : xmllog4jconfig




Several attributes like file name, lay out and many others contains in xml file.

And then we have to use this xml file inside our codes as follows.

import org.apache.log4j.*;
import org.apache.log4j.xml.DOMConfigurator;
Logger logger;
try{
logger = Logger.getLogger("Update.class");


DOMConfigurator.configure(getServletContext().getRealPath("/") + "WEB-INF" + File.separator +"classes"+ File.separator + "xmllog4jconfig.xml");

logger.info("Log has been appended to your output.txt");
logger.info("device information changed from "+ imei_db +" to "+ imei);
System.out.println("succesfully written to output.txt");

}catch(Exception e){
System.out.println("Exception in log4j- "+e.getMessage());
}



  • Using a property file : log4j

log4j.rootLogger=DEBUG, R

log4j.appender.R = org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.File = $CATALINA_HOME/logs/oooutput.log
log4j.appender.R.Append = true
log4j.appender.R.DatePattern = '.'yyy-MM-dd
log4j.appender.R.layout = org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} %c{1} [%p] %m%n






No comments:

Post a Comment