Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I implement log4j logging to an existing J2EE Struts web application?
    text
    copied!<p>I have recently inherited a J2EE Struts web app that was written back in 2002. There is no logging in the application other than the odd System.out.println().<br> I have added log4j logging so that I can write out some info to the console, but I'm concerned on how best to approach this. Any suggestions, tips, best practices would be welcome as I don't want to spend too much time adding logging to every method or class (or trying to find what places where logging would be best - ie. bad code blocks/defects).<br> My current approach is to just add some logging to the few classes that I have been looking at to understand the code, but are there a few key places where I can add logging to maximize my use of adding log4j?</p> <p><strong>Edit:</strong><br> Progress update:<br> I extended the Struts (v.1) <code>ExceptionHandler</code> and configured the <code>struts-config.xml</code> to use my <code>CustomExceptionHandler</code> instead of the Struts version. Then by overriding the <code>execute()</code> method, I added some logic to log the exception using <code>log4j</code>. See below:</p> <pre>public class CustomExceptionHandler extends ExceptionHandler { static Logger logger = Logger.getLogger(CustomExceptionHandler.class); public ActionForward execute(Exception ex, ExceptionConfig ae, ActionMapping mapping, ActionForm formInstance, HttpServletRequest request, HttpServletResponse response) throws ServletException { logException(ex); return super.execute(ex, ae, mapping, formInstance, request, response); } private void logException(Throwable thr) { // Add code here to log the exception appropiately // i.e. logger.error("Exception is: " + ex.getMessage()); } </pre> <p>The struts-config.xml file had to be updated as well:</p> <p><code>&lt;global-exceptions&gt;<br> &lt;exception key="" type="java.lang.Throwable" handler="com.mycompany.CustomExceptionHandler" /&gt;<br> &lt;/global-exceptions&gt;</code></p> <p>Now I can be sure that I will always appropiately log any exceptions.<br> For the exceptions that were getting eaten, I wrap them in unchecked exceptions so that they make it to the top:</p> <pre> } catch (Exception e) { //nothing here } </pre> <p>Changed to:</p> <pre> } catch (Exception e) { throw new RuntimeException(e); }</pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload