Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use SLF4J Loggers in a JSP

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:

  • way too verbose, and needs a lot of work to convert the existing JSPs
  • a call is made to LoggerFactory.getLogger() every time the page is rendered (as opposed to a static logger field in a standard Java class)
  • I think the name of the logger is also going to be something not really straightforward this way

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)?

like image 212
Lóránt Pintér Avatar asked Aug 11 '09 07:08

Lóránt Pintér


People also ask

Can we use logger in JSP page?

Any JSP page that is part of the web application will be able to use the logging utilities.

Which Logger is used by SLF4J?

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.

How do you write log in SLF4J?

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.

What is SLF4J logger in Java?

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.


2 Answers

Have a look at slf4j-taglib.

like image 168
Ceki Avatar answered Sep 21 '22 17:09

Ceki


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.

like image 36
Michael Rutherfurd Avatar answered Sep 20 '22 17:09

Michael Rutherfurd