728x90 AdSpace

Saturday, 12 April 2014

Servlet – Log4j Configuration in Web Application

In this tutorial we are going to see about, how to configure Log4j in web application.See more Log4j Examples
1. Create new Dynamic web project by choosing File –> New –> Dynamic Web Project .
2. Create the Project called ServletExample as given below.
Servlet-dynamic web project
3. Create package called com.javatutorialscorner.servlet under ServletExample.
4. Create following Servlet  as shown in figure.
  • Log4jServlet.java
  • HelloWorldServlet.java
Create Servlet
http servlet 

5. Click Next it will show URL mapping.You can edit Servlet URL if you need.
6. Click Next it will show methods available  in HttpServlet. Select appropriate method you need.
http servlet Services
7. By default your servlet will be mapped in web.xml, if your servlet not mapped in your web.xml use the following configuration to map the servlet in your web.xml
Servlet Mapping
<servlet>
    <servlet-name>Your Servlet Name</servlet-name>
    <servlet-class>Fully Qulaified Servlet Class Name</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Your Servlet Name</servlet-name>
    <url-pattern>/URL to Call Servlet</url-pattern>
  </servlet-mapping> 

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 id="WebApp_ID" version="3.0">
 <display-name>ServetExample</display-name>
 <welcome-file-list>
  <welcome-file>index.html</welcome-file>
 </welcome-file-list>
 <servlet>
  <servlet-name>Log4jServlet</servlet-name>
  <servlet-class>com.javatutorialscorner.servlet.Log4jServlet</servlet-class>
  <init-param>
   <param-name>log4j</param-name>
   <param-value>WEB-INF/classes/log4j.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet>
  <servlet-name>HelloWorld</servlet-name>
  <servlet-class>com.javatutorialscorner.servlet.HelloWorld</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>HelloWorld</servlet-name>
  <url-pattern>/HelloWorld</url-pattern>
 </servlet-mapping>

</web-app>

8.Add log4j-x.x.xx.jar in your build path.

9. Create log4j.xml in WEB-INF/classes/ folder

log4j.xml

<?xml version="1.0" encoding="UTF-8" ?>
 <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>
 <appender name="console" class="org.apache.log4j.ConsoleAppender">
  <layout class="org.apache.log4j.PatternLayout">
  <param name="ConversionPattern" value="%r [%t] %p %c %x - %m%n" />
  </layout>
 </appender>
 <appender name="FILE" class="org.apache.log4j.FileAppender">
  <param name="file" value="${user.home}/log.log" />
  <param name="append" value="true" />
  <layout class="org.apache.log4j.PatternLayout">
  <param name="conversionPattern" value="%r [%t] %p %c %x - %m%n" />
  </layout>
 </appender>

 <root>
  <level value="DEBUG" />
  <appender-ref ref="FILE" />
  <appender-ref ref="console" />
 </root>
</log4j:configuration>

10. Add the required code inside doGet() method.

Log4jServlet.java

package com.javatutorialscorner.servlet;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.xml.DOMConfigurator;

/**
 * Servlet implementation class Log4jServlet
 */

public class Log4jServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;

 /**
  * @see HttpServlet#HttpServlet()
  */
 public Log4jServlet() {
  super();
  // TODO Auto-generated constructor stub
 }

 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
  *      response)
  */
 protected void doGet(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
  try {

   String appPath = getServletContext().getRealPath("/");
   String filePath = getInitParameter("log4j");
   if (filePath != null) {
    DOMConfigurator.configure(appPath + filePath);
   }
  } catch (Exception e) {
   // TODO: handle exception
   e.printStackTrace();
  }

 }

 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
  *      response)
  */
 protected void doPost(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
 }

}

HelloWorldServlet.java

package com.javatutorialscorner.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

/**
 * Servlet implementation class HelloWorld
 */
public class HelloWorld extends HttpServlet {
 private static final long serialVersionUID = 1L;
 private static final Logger log = Logger.getLogger(HelloWorld.class);

 /**
  * @see HttpServlet#HttpServlet()
  */
 public HelloWorld() {
  super();
  // TODO Auto-generated constructor stub
 }

 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
  *      response)
  */
 protected void doGet(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
  log.info("Log4j Configured with Web application");
 }

 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
  *      response)
  */
 protected void doPost(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
 }

}

11. Now save and Run the servlet, Run As –> Run on Server – Select your web Server to run the servlet. ( see How to configure tomcat in eclipse) 
http://www.javatutorialcorner.com/2014/03/how-to-configure-tomcat-in-eclipse.html

12.call the URL which is mapped in web.xml. You can see the log  message in log file and console.

http://localhost:8080/ServletExample/HelloWorld

Output

0 [http-bio-8080-exec-9] INFO com.javatutorialscorner.servlet.HelloWorld  - Log4j Configured with Web application
Annamalai Thangaraj

Annamalai is working as Technical Lead in Leading Telecom company with 5+ years experience in Identity and Access Management , Telecom and Networks, BigData, Java, Spring, Struts, Hibernate, AngularJS, and Enterprise Web Application Development.

Website: Java Tutorials Corner

Shop and help us

Flipkart Offer Snapdeal offer Amazon.in offer Amazon.com offer
  • Blogger Comments
  • Facebook Comments
  • Disqus Comments

0 comments:

Post a Comment

Item Reviewed: Servlet – Log4j Configuration in Web Application Rating: 5 Reviewed By: Annamalai Thangaraj