views:

550

answers:

4

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.

A: 

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.

Adventure10
A: 

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.

skaffman
this is not what I am looking for, as the relation between the request url and the .jsp page is less than tight, specially if you use frameworks like spring mvc, but not only.
flybywire
No, if you're executing a JSP, then the requestUri property of the request *will* by the URL of the JSP, *not* the original URL that arrived at the container. Remember, the request is forwarded from the servlet to the JSP, which results in a new request. It works, trust me, I use this technique myself.
skaffman
+1  A: 

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.

_NT
+1  A: 

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?

Alexander Pogrebnyak