I'm in the process of migrating the logging of a middle-sized application from a custom solution to something more standard. I've decided on using Logback and SLF4J, and I have successfully migrated most of the Java code. However, I have quite a bit of JSPs that simply use System.out for logging. I've never worked much with JSPs, and started to wonder: how am I supposed to use proper logging in a JSP?
<%@page import="org.slf4j.Logger"%>
<%@page import="org.slf4j.LoggerFactory"%>
<%
Logger log = LoggerFactory.getLogger(getClass());
%>
<!-- ... -->
<%
log.info("Hello Logging!");
%>
This is what came to mind first, but it seems wrong on several points:
logger
field in a standard Java class)Is there some kind of standard, or a best practice, or anything for logging in JSPs?
Also, IIRC, there was some kind of taglib for Log4J. Is there something similar for SLF4J (or maybe Logback)?
Any JSP page that is part of the web application will be able to use the logging utilities.
If SLF4J cannot find a binding on the class path it will emit a single warning message and default to no-operation implementation. SLF4J supports popular logging frameworks, namely log4j, java. util. logging, Simple logging and NOP.
We create the Logger instance by using the LoggerFactory class and its getLogger method and providing the name of the class. That way we bind the logger to the class name which gives us the context of the log message. Once we have that, we can use the Logger methods to create LogRecord on a given level.
SLF4J stands for Simple Logging Facade for Java. It provides a simple abstraction of all the logging frameworks. It enables a user to work with any of the logging frameworks such as Log4j, Logback, JUL (java.
Have a look at slf4j-taglib.
You could try (Note the "!")
<%! org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger("JSPname"); %>
Then replace your System.out's with
<% log.info("Hello Logging!"); %>
Boris's comment should really be taken into concideration though, JSPs should not need logging in general. I would only use this technique (or anything similiar) to replace existing logging that needed to be kept.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With