Tutorial List
Home
Interview Questions
Interview
Interview Questions
Links
Web Home
About Us

Logging : Trace Your Application

Logging is process of tracing the flow of application. This is usually done by marking some check points in your application and storing them in a file or db. Logging is very useful in multi threaded environment and large distributed system.
When we talk about Logging in Java, 99.99% times it means Log4j. we will discuss logging with log 4j only. You can download Log4j jar from here.Log4j is an API which provide utility methods to log application. Log 4j is pretty easy to configure with application. Lets see how...
Configure Log 4j:
We need to provide Log 4j configuration parameter to decide the pattern of logging. These configuration parameter can be set using property file or using xml. Both approach achieve the same result but xml is declarative and more flexible solution than property file.
****************Logger Configuration Property File*******************
You need to specify logging configuration in a property file. The Sample property file could be,
# Log 4j Configuration Proeprties
log4j.rootLogger=DEBUG, stdout,MyApp

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
log4j.appender.MyApp=org.apache.log4j.RollingFileAppender
log4j.appender.MyApp.File= /logs/ECSR.log
log4j.appender.MyApp.MaxFileSize=100KB
# Keep one backup file
log4j.appender.MyApp.MaxBackupIndex=2
log4j.appender.MyApp.layout=org.apache.log4j.PatternLayout
log4j.appender.MyApp.layout.ConversionPattern=%p %t %c - %m%n
log4j.logger.org.apache.commons.digester.Digester=error
log4j.threshold=error
You may just replace MyApps in with your Application name and use this file as such. I think terms are self explanatory and you might just unserdtand their usage by name itself. Lets move to loading property file. This property file can be load like normal property file and need to pass as arguemtn to PropertyConfigurator.configure(propertyObj). I am using servlet to upload the peroperty file to expalin one more way,
************************Load Logger Properties*********************
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.PropertyConfigurator;
public class Log4jInit extends HttpServlet {
private static final long serialVersionUID = 1L;
public void init() {
// reading file path from deployment descriptor
String file = getInitParameter("log4j-init-file");
InputStream logFileStream = this.getClass().getResourceAsStream("/"+file);
Properties logPorperties = new Properties();
try {
logPorperties.load(logFileStream);
} catch (IOException e) {
e.printStackTrace();
}
// Dosen't matter how you load the property file, just pass it here
PropertyConfigurator.configure(logPorperties);
}
public void doGet(HttpServletRequest req, HttpServletResponse res) {
// Empty Method
}
}
Now 80% job is done. Log4j is configured. Now we just need to log the application.
************************Logging Methods***************************
How to Log Application:
Just create logger member in class you want to log using following code,
private static Logger logger = Logger.getLogger(EmailSender.class);
Logger.getLogger() returns a singleton object of logger for the class whose name is provided in argument of method. logger object provide following methods for logging,
1:logger.debug(message): Save log useful for debugging application
2:logger.info(logMessage): Save logs that describes normal progress of application.
3:logger.warn(logMessage): Save logs to depict warnings.
4:logger.error(logMessage): Save logs that describes error events which application can recover and continue its normal execution.
5:logger.fatal(message): Save log that describe events fatal which application cannot recover and halts its execution.  

Above five methods are in ascending order of their level i.e. if you set the logging level to debug, you can view log for all five methods but if you set the logger level to warn, you can view logging from warn, error and fatal only as rest two are or lower level. Normally logging level is kept at info level.
You can set logging level in very first line of property file. There I set the level to debug If you want to set it to info level, just use
log4j.rootLogger=INFO, stdout,MyApp
Thats all about logging. Last thing I will do is to write a sample class which depicts the normal usage of logger methods. Just go through the class and claim you know logging with Log4j.
************************Logging Example*************************** package codinguide.come; 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.PreparedStatement; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import org.apache.log4j.Logger; 
public class JDBCConnection 
 private static Logger logger = Logger.getLogger(JDBCConnection.class); 
 public void testMethod() throws SQLException 
 { 
   Connection conn = null; 
   try { 
      logger.info("Loading SQL Driver");
      Class.forName("oracle.jdbc.driver.OracleDriver"); 
      String conStr = "jdbc:oracle:thin:@localhost:1521:xe"; 
      conn = DriverManager.getConnection(conStr, "scott", "tiger");
      logger.info("Connection Created " + conn); String queryStr = "SELECT *
      FROM tblEmployee where empName = ? AND empSalary = ?";
      PreparedStatement ps = conn.prepareStatement(queryStr); 
      ps.setString(1,   "Rahul"); 
      ps.setInt(2, 25000); 
      ResultSet rset = ps.executeQuery();
      logger.debug("resultset obtained "+ rset); 
      while (rset.next()) 
      { 
         System.out.println(rset.getString(1)); // empName
         System.out.println(rset.getInt(2)); // empCode
         System.out.println(rset.getInt(3)); // empSalary
         System.out.println(rset.getString(4)); // empAddress 
      } 
    } catch (ClassNotFoundException e) 
    { 
       logger.error("Exception in loading class", e); 
    } catch (SQLException ex) { 
       logger.error("SQLException occurred", ex); 
    } finally { 
       logger.debug("closing connection"); 
       conn.close(); 
       logger.debug("connection closed"); 
       } 
    } 
 } 

Thanks, 
Mohit Singh










No comments: