File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes How do I initialise a servlet ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "How do I initialise a servlet ?" Watch "How do I initialise a servlet ?" New topic

How do I initialise a servlet ?

Chuan Ren
Ranch Hand

Joined: Aug 04, 2003
Posts: 42
Hi! I am very new to servlet and would appreciate your assistance in this problem.
I am using j2sdk1.3.1_08, Tomcat 4.1.27, Log4j 1.2.28
I would like to initialise log4j using servlet. Following are the codes I used. Somehow, this servlet does not get initialised as there are no logs generated. But if I run runLog.jsp following by test.jsp, it works. Do you know why?
------ runLog.jsp ---
<%@ page import="org.apache.log4j.*"%>
Logger logger = Logger.getLogger(getClass());
String LogConfigFilePath = getServletContext().getRealPath("/")+"WEB-INF/classes/config/";
PropertyConfigurator.configure(LogConfigFilePath);"runLog successful");
------ WEB-INF/class/com/log/ ----
package com.log;
import org.apache.log4j.*;
import javax.servlet.http.*;
public class Log4jInit extends HttpServlet {
public void init() {
String LogConfigFilePath = getServletContext().getRealPath("/") + "config//";
public void doGet(HttpServletRequest req, HttpServletResponse res) {}
--- web.xml ---
--- test.jsp ---
<%@ page import="org.apache.log4j.*" %>
<% Logger logger = Logger.getLogger("test.jsp");"befor say hi");
<h3> Hi</h3>
<%"after say hi");%>
David O'Meara

Joined: Mar 06, 2001
Posts: 13459

The way you have it set up, you'd have to include the Log4J initialisation code in every class that wants to use the Logger, or call either the runLog.jsp or Log4jInit servlet before any other code can use the logger.
The easier way to get things working is to allow Log4J to loads it's configuration. The first time Log4J is called, it looks on the ClassPath for its If the is not on the classpath, then you need to use the code you've used above, but letting Log4J take care of it is much easier.
Drop the in the WEB-INF/classes directory, then all web application code should be able to refer to the logger the same way you have it in test.jsp - ie you don't need all that other rubbish!
The WEB-INF/classes is on the classpath for the web application, so log4j should be able to find the properties file automatically.
Chuan Ren
Ranch Hand

Joined: Aug 04, 2003
Posts: 42
Thank you. That has solved my problem.
I agree. Here's the link:
subject: How do I initialise a servlet ?
It's not a secret anymore!