View Javadoc

1   package ch.qos.logback.classic.pattern;
2   
3   import ch.qos.logback.classic.spi.LoggingEvent;
4   import ch.qos.logback.core.pattern.Converter;
5   import ch.qos.logback.core.pattern.ConverterUtil;
6   import ch.qos.logback.core.pattern.PostCompileProcessor;
7   
8   public class EnsureExceptionHandling implements
9       PostCompileProcessor<LoggingEvent> {
10  
11    /**
12     * This implementation checks if any of the converters in the chain handles
13     * exceptions. If not, then this method adds a
14     * {@link ExtendedThrowableProxyConverter} instance to the end of the chain.
15     * <p>
16     * This allows appenders using this layout to output exception information
17     * event if the user forgets to add %ex to the pattern. Note that the
18     * appenders defined in the Core package are not aware of exceptions nor
19     * LoggingEvents.
20     * <p>
21     * If for some reason the user wishes to NOT print exceptions, then she can
22     * add %nopex to the pattern.
23     * 
24     * 
25     */
26    public void process(Converter<LoggingEvent> head) {
27      if (!chainHandlesThrowable(head)) {
28        Converter<LoggingEvent> tail = ConverterUtil.findTail(head);
29        Converter<LoggingEvent> exConverter = new ExtendedThrowableProxyConverter();
30        if (tail == null) {
31          head = exConverter;
32        } else {
33          tail.setNext(exConverter);
34        }
35      }
36    }
37  
38    /**
39     * This method computes whether a chain of converters handles exceptions or
40     * not.
41     * 
42     * @param head
43     *                The first element of the chain
44     * @return true if can handle throwables contained in logging events
45     */
46    public boolean chainHandlesThrowable(Converter head) {
47      Converter c = head;
48      while (c != null) {
49        if (c instanceof ThrowableHandlingConverter) {
50          return true;
51        }
52        c = c.getNext();
53      }
54      return false;
55    }
56  }