Search This Blog

Monday 2 February 2009

Using Log4J with Jdeveloper 11g / Integrated Weblogic Server

A quick demo on how to use Log4j within a JDeveloper workspace for 11g when running web projects. In this example we are using a simple HTTP servlet with just a doGet method defined

1. Create the default "log4j.properties" file within the root src folder of your web project.

# **Set root logger level to DEBUG and its only appender to A.
log4j.rootLogger=DEBUG, A
# ***** A is set to be a ConsoleAppender.
log4j.appender.A=org.apache.log4j.ConsoleAppender
# ***** A uses PatternLayout.

log4j.appender.A.layout=org.apache.log4j.PatternLayout
log4j.appender.A.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

Eg:




2. Add the log4j JAR file to the project's web-inf/lib directory for runtime and as a project library JAR file for compile time. In my case I used the JAR file as follows

> log4j-1.2.15.jar

3. Here is the servlet code which will then use log4j at runtime.


package pas.au.log4j;

import java.io.IOException;
import java.io.PrintWriter;
import org.apache.log4j.Category;
import org.apache.log4j.PropertyConfigurator;
import java.util.Properties;
import java.io.FileInputStream;

import javax.servlet.*;
import javax.servlet.http.*;

import org.apache.log4j.Logger;

public class Log4JServletDemo
extends HttpServlet
{
Logger log = Logger.getLogger(this.getClass().getSimpleName());
private static final String CONTENT_TYPE = "text/html; charset=windows-1252";

public void init(ServletConfig config)
throws ServletException
{
super.init(config);
log.info("init() method of servlet Log4JServletDemo");
}

public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Log4JServletDemo</title></head>");
out.println("<body>");
out.println("<h2>Log4j demo</h2>");

log.info("init() doGet method of servlet Log4JServletDemo");

out.println("</body></html>");
out.close();
}
}



4. When run within the "Integrated Weblogic Server" verify runtime output as follows within JDeveloper's log window.

Target URL -- http://127.0.0.1:7101/Log4JTest-ServletDemo-context-root/log4jservletdemo
0 [[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'] INFO Log4JServletDemo - init() method of servlet Log4JServletDemo
63 [[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'] INFO Log4JServletDemo - init() doGet method of servlet Log4JServletDemo


When your ready to create a WAR file for deployment to an External Weblogic 10.3 server then the log4j.properties file should be added to the web-inf/classes folder automatically with this setup.

No comments: