Using the Servlet Container for Logging

The Servlet specification requires that every servlet container allow developers to log events to the container log file. Although the name and location of the log file are container-dependent, the manner in which these events are logged is dictated by the specification and is portable across web containers.

The javax.servlet.ServletContext class contains two methods that can be used for logging messages to the container’s log:

public void log( String msg );
public void log( String msg, Throwable throwable );

You can use either of these methods by obtaining the ServletContext and passing the appropriate arguments. Example 15-1 illustrates how this can be done using a Struts Action.

Example 15-1. The LoginAction using the ServletContext to log messages

public class LoginAction extends StorefrontBaseAction { public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws Exception{ // Get the user's login name and password. They should have already been // validated by the ActionForm. String email = ((LoginForm)form).getEmail( ); String password = ((LoginForm)form).getPassword( ); // Obtain the ServletContext ServletContext context = getServlet( ).getServletContext( ); // Log which user is trying to enter the site context.log( "Login email: " + email ); // Log in through the security service IStorefrontService serviceImpl = getStorefrontService( ); UserView userView = serviceImpl.authenticate(email, ...

Get Programming Jakarta Struts, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.