I mean, I want the logger name to reflect the source.jsp file, no matter if it is included in another file or compiled to a class or whatever.
The following is the code. All the configuration file placement and configuration are the same as how it is use in Servlet or other class.
<%@ page import="org.apache.log4j.Logger" %>
Demonstration log4j usage in jsp
<% Logger log = Logger.getLogger("com.mobilefish.demo.test"); log.debug("Show DEBUG message"); log.info("Show INFO message"); log.warn("Show WARN message"); log.error("Show ERROR message"); log.fatal("Show FATAL message"); %>
The log messages are shown in the Tomcat console and in the ${catalina.home}/logs/demo.log file.
You could write a factory method which takes the current request as a parameter, and which obtains a Logger based on the JSP name, something like this:
public static Logger getLogger(HttpServletRequest request) {
String requestUri = request.getRequestURI();
String jspName = requestUri.substring(requestUri.lastIndexOf('/'));
return Logger.getLogger(jspName);
}
You might have to play with it a bit to make it work (I haven't tested the above code), but that's the gist of it.
This could be used directly from the JSP, or from a bean or tag class which is used by the JSP, as long as it has access to the request object.
Use the appropriate ConversionPattern when configuring log4j, e.g:
%d [%C] %-5p %c - %m%n
Here, the %C outputs the fully qualified class name when you call any of the Logger class methods.
What's wrong with:
Logger logger = Logger.getLogger( "source.jsp" );
You can prepend it with a better non-ambiguous prefix, of course. Actually, something along the lines JSPS.source.jsp
is better, as you can set up logging rules for JSPS
logger, that would later be applied to all sub-loggers.
Having said this, why do you need to log from JSP directly?