Using Log4J

I l @ ve RuBoard

You will want to generate log messages, both for debugging and to report state during the operation of the Web site. You should standardize this, too; otherwise , everyone will end up placing System.out.println s all over the code, and you'll have a nightmare of a time cleaning them up later. The Apache folks have a nifty little (actually, fairly robust) logging package called Log4J (that's log for Java, get it?)

Log4J is easy to use but a bit tricky to configure. In the examples throughout the book, you will be using it in a fairly simple fashion, but it's worth taking about its full capabilities.

After installing Log4J using the instructions in Appendix C,you need to configure it for your application, just as Turbine needed to be configured. This is accomplished with another HttpServlet class that will be invoked on startup (see Listing 7.7).

Listing 7.7 Log4JInit.java
 package com.bfg.services; import org.apache.log4j.PropertyConfigurator; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.PrintWriter; import java.io.IOException; public class Log4jInit extends HttpServlet {   public   void init() {     String prefix =  getServletContext().getRealPath("/");     String file = getInitParameter("log4j-init-file");     // if the log4j-init-file is not set, then no point in trying     if(file != null) {       PropertyConfigurator.configure(prefix+file);     }   }   public   void doGet(HttpServletRequest req, HttpServletResponse res) {   } } 

The Log4jInit class simply gets the path and name of the property file with the initialization data for the Log4J package and then calls the Log4J configurator class that is set up to read its data from a configuration file.

With this class in place, you need to add another servlet to the web.xml configuration file to request that the Log4J initialization be run at startup. This is shown in Listing 7.8.

Listing 7.8 Addition to web.xml for Log4J
 <servlet>   <servlet-name>log4j-init</servlet-name>   <servlet-class>com.bfg.services.Log4jInit</servlet-class>   <init-param>     <param-name>log4j-init-file</param-name>     <param-value>WEB-INF/log4j.properties</param-value>   </init-param>   <load-on-startup>1</load-on-startup> </servlet> 

As with the Turbine configuration files, you should make sure that you add code to your Ant build script to copy over the property file. You should also make sure that the logs directory is present so that Ant will have a location to write the log files to. Listing 7.9 shows the additions made to the build.xml script.

Listing 7.9 Additions to build.xml
 <mkdir dir="${appdir} /logs"/> . . .      <copy todir="${appdir} /WEB-INF">         <fileset dir="props" includes="log4j.properties"/>      </copy> 

To use Log4J, each class that wants to log puts the following code snippet in the source:

 import org.apache.log4j.Category; . . . public class MyClass {     static Category cat = Category.getInstance(MyClass.class); 

The name of the class specified in the getInstance call should match the name of the class in which it is being used. This is because the name of the class will be included in the log output. The class and package are used to determine the level of logging output that will be generated, as you'll see shortly.

After this log code is in place, you use a standard set of logging functions to generate log messages:

 cat.debug(String message) cat.debug(String message, Throwable t) cat.info(String message) cat.info(String message, Throwable t) cat.warn(String message) cat.warn(String message, Throwable t) cat.error(String message) cat.error(String message, Throwable t) cat.fatal(String message) cat.fatal(String message, Throwable t) 

Basically, there are two versions at each level: one that just prints a message and one that also prints a stacktrace from an exception. If you have an exception available, it's always a good idea to include it in the log message by using the two-argument versions of the logging methods . But if you are logging something that isn't the result of an exception, you can still use the simpler version.

Listings 7.10 and 7.11 show a simple example of Log4J that illustrates some of the ways you can log using the package.

Listing 7.10 Logger.java
 package com.bfg.demo; import org.apache.log4j.Category; public class Logger {     static Category cat = Category.getInstance(Logger.class);     public Logger() {       try {           String aString = null;           aString.substring(5);      }  catch (Exception e) {           cat.error("Got error during substring", e);      }      cat.debug("Hi mom!");     } } 
Listing 7.11 LoggerDemo.jsp
 <%@ page import="com.bfg.demo.Logger" %> <HTML> <HEAD> <TITLE>A Logger Smoketest</TITLE> </HEAD> <BODY> This is a smoketest <%     Logger l = new Logger(); %> </BODY> </HTML> 

When LoggerDemo.jsp is run from a browser, the following output should be displayed in the console output (in the Tomcat window under Windows, or in catalina.out under Linux).

 0    [HttpProcessor[8080][4]] ERROR com.bfg.demo.Logger  - Got error during substring java.lang.NullPointerException         at com.bfg.demo.Logger.<init>(Unknown Source)         at org.apache.jsp._0002fjsp_0002fLoggerDemo_jsp._jspService( graphics/ccc.gif _0002fjsp_0002fLoggerDemo_jsp.java:61)         at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:107)         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)         at org.apache.jasper.servlet.JspServlet$JspServletWrapper.service(JspServlet.java: graphics/ccc.gif 200)         at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:379)         at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:456)         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter( graphics/ccc.gif ApplicationFilterChain.java:247) . . . 10   [HttpProcessor[8080][4]] DEBUG com.bfg.demo.Logger  - Hi mom! 

As you can see, the log information is presented in a structured format that is easy for automated monitoring tools to parse. You will use the Log4J interface throughout the application to provide error and debugging information.

I l @ ve RuBoard


MySQL and JSP Web Applications. Data-Driven Programming Using Tomcat and MySQL
MySQL and JSP Web Applications: Data-Driven Programming Using Tomcat and MySQL
ISBN: 0672323095
EAN: 2147483647
Year: 2002
Pages: 203
Authors: James Turner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net