/*
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>cbck</short-name>
<description>Cookbook custom tags</description>
<uri>com.java2s.tags</uri>
<tag>
<name>log</name>
<tag-class>com.java2s.LoggerTag</tag-class>
<body-content>JSP</body-content>
<description>This tag uses log4j to log a message.</description>
<attribute>
<name>configFile</name>
<required>false</required>
<rtexprvalue>false</rtexprvalue>
<description>This attribute provides any configuration file name for the logger. The file must be located in WEB-INF/classes</description>
</attribute>
<attribute>
<name>level</name>
<required>true</required>
<rtexprvalue>false</rtexprvalue>
<description>This attribute provides the level for the log request.</description>
</attribute>
</tag>
</taglib>
*/
//Log4j from Apache is required
package com.java2s;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import java.lang.reflect.Method;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class LoggerTag extends BodyTagSupport {
private Logger log = null;
private String configFile = null;
private String level = null;
private final static String[] LEVELS = { "debug", "info", "warn", "error",
"fatal" };
public void setConfigFile(String fileName) {
this.configFile = fileName;
}
public void setLevel(String level) {
this.level = level;
}
public int doEndTag() throws JspException {
if (configFile != null)
PropertyConfigurator.configure(pageContext.getServletContext()
.getRealPath("/")
+ "WEB-INF/classes/" + configFile);
level = level.toLowerCase();
if (!contains(level))
throw new JspException(
"The value given for the level attribute is invalid.");
log = Logger.getLogger(LoggerTag.class);
String message = getBodyContent().getString().trim();
Method method = null;
try {
method = log.getClass().getMethod(level,
new Class[] { Object.class });
method.invoke(log, new String[] { message });
} catch (Exception e) {
}
return EVAL_PAGE;
}
public void release() {
log = null;
configFile = null;
level = null;
}
private boolean contains(String str) {
for (int i = 0; i < LEVELS.length; i++) {
if (LEVELS[i].equals(str))
return true;
}
return false;
}
}
|