We help IT Professionals succeed at work.

Adding log4J to a JSP

Angela123
Angela123 asked
on
I have been asked to add log4J to a JSP so I can test application logging. Im not sure where to begin and what to put in the jsp?

any help would be appreciated.
Comment
Watch Question

CERTIFIED EXPERT
Top Expert 2007
Commented:
You need to:

* get the log4j jar
* configure log4j
* add log4j code to your JSP page

This is the main log4j site:
http://logging.apache.org/

You can download log4j from there.

Then create a simple log4j.properties file, and put it in your WEB-INF/classes directory.  Something like this:

log4j.properties file:

log4j.rootCategory=DEBUG, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{MM/dd/yy HH:mm:ss} [%c{2}]:(%x):%-5p: %m%n

This will append log4j messages to your Tomcat console log for stdout.  It's a good way to start, then after you get it working, you can make the log4j logs go to a separate log file if you wish.

Then make your jsp file use the logger.  This is a sample program:
<%@ page  import="org.apache.log4j.*, org.apache.log4j.PropertyConfigurator" %>
<%
      String loggerName = "TestLogger";
      loggerName = ":" + this.getClass();
      logger = Logger.getLogger(loggerName);
      PropertyConfigurator pc = new PropertyConfigurator();
      String log4jPropsFile = "D://Program Files//Apache Software Foundation//Tomcat 5.5//webapps//WEB-INF//classes//log4j.properties";
      pc.configure(log4jPropsFile);
%>
<html>
<head><title>Test logger</title>
</head>
<body>
<h1>Test log4j logger</h1>
<%  logger.debug("Writing logger.debug"); %>
</body>
<%!
      static Logger logger; %>
Jim CakalicSenior Engineer

Commented:
I agree with the above except for the part about manually configuring log4j using PropertyConfigurator. For one thing, the pattern above is going to reconfigure log4j every time you hit the page. I always like to leverage log4j's automatic configuration by putting the configuration file (and I prefer the XML form) somewhere on the classpath so that log4j can find it and configure itself when necessary. If you prefer a more JSP-ish way of logging, have a look at http://jakarta.apache.org/taglibs/doc/log-doc/intro.html.

Regards,
Jim Cakalic
CERTIFIED EXPERT
Top Expert 2007

Commented:
If you are going to use taglibs, then this site has a very nice walk-through of how to use log4j tags in a JSP page:
http://www.mobilefish.com/developer/log4j/log4j_quickguide_jsp.html

However, if you don't use taglibs, it's easier to set up a more basic configuration as I documented above.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.