log4j example

This Example shows you how to create a log in a Servlet.

log4j example

log4j example

     

This Example shows you how to create a log in a Servlet.

Description of the code:

Logger.getLogger(): Logger class is used for handling the majority of log operations and getLogger method is used for return a logger according to the value of the parameter. If the logger already exists, then the existing instance will be returned. If the logger is not already exist, then create a new instance.

log.info(): This method is used to check that the specified category is INFO enabled or not, if yes then it converts the massage passed as a string argument to a string by using appropriate object renderer of class ObjectRenderer.

 

  log4jexample.java


import org.apache.log4j.Logger;

class CustomerOrder {

  private String productName;
  private int productCode;
  private int productPrice;

  public int getProductCode() {
  return productCode;
  }

  public void setProductCode(int productCode) {
  this.productCode = productCode;
  }

  public String getProductName() {
  return productName;
  }

  public void setProductName(String productName) {
  this.productName = productName;
  }

  public int getProductPrice() {
  return productPrice;
  }

  public void setProductPrice(int productPrice) {
  this.productPrice = productPrice;
  }

  public CustomerOrder(String productName, int productCode, 
   int productPrice) {

  this.productName = productName;
  this.productCode = productCode;
  this.productPrice = productPrice;
  }
}

public class Log4jExample {

  private static Logger logger = Logger.getLogger("name");

  public void processOrder(CustomerOrder order) {
  logger.info(order.getProductName());
  }

  public static void main(String args[]) {
  CustomerOrder order1 = new CustomerOrder("Beer"10120);
  CustomerOrder order2 = new CustomerOrder("Lemonade"9510);
  CustomerOrder order3 = new CustomerOrder("Chocolate"2235);

  Log4jExample demo = new Log4jExample();
  demo.processOrder(order1);
  demo.processOrder(order2);
  demo.processOrder(order3);
  }
}


log4j.properties


log4j.rootLogger=debug, 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=%t %-5p %c{2} - %m%n


Output:

main INFO name - Beer
main INFO name - Lemonade
main INFO name - Chocolate

Download code