1 /**
2 * Logback: the reliable, generic, fast and flexible logging framework.
3 * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
4 *
5 * This program and the accompanying materials are dual-licensed under
6 * either the terms of the Eclipse Public License v1.0 as published by
7 * the Eclipse Foundation
8 *
9 * or (per the licensee's choosing)
10 *
11 * under the terms of the GNU Lesser General Public License version 2.1
12 * as published by the Free Software Foundation.
13 */
14 package ch.qos.logback.classic.pattern;
15
16 import ch.qos.logback.classic.LoggerContext;
17 import ch.qos.logback.classic.spi.ILoggingEvent;
18 import ch.qos.logback.core.Context;
19 import ch.qos.logback.core.pattern.Converter;
20 import ch.qos.logback.core.pattern.ConverterUtil;
21 import ch.qos.logback.core.pattern.PostCompileProcessor;
22
23 public class EnsureExceptionHandling implements PostCompileProcessor<ILoggingEvent> {
24
25 /**
26 * This implementation checks if any of the converters in the chain handles
27 * exceptions. If not, then this method adds a
28 * {@link ExtendedThrowableProxyConverter} instance to the end of the chain.
29 * <p>
30 * This allows appenders using this layout to output exception information
31 * event if the user forgets to add %ex to the pattern. Note that the
32 * appenders defined in the Core package are not aware of exceptions nor
33 * LoggingEvents.
34 * <p>
35 * If for some reason the user wishes to NOT print exceptions, then she can
36 * add %nopex to the pattern.
37 *
38 *
39 */
40 public void process(Context context, Converter<ILoggingEvent> head) {
41 if (head == null) {
42 // this should never happen
43 throw new IllegalArgumentException("cannot process empty chain");
44 }
45 if (!chainHandlesThrowable(head)) {
46 Converter<ILoggingEvent> tail = ConverterUtil.findTail(head);
47 Converter<ILoggingEvent> exConverter = null;
48 LoggerContext loggerContext = (LoggerContext) context;
49 if (loggerContext.isPackagingDataEnabled()) {
50 exConverter = new ExtendedThrowableProxyConverter();
51 } else {
52 exConverter = new ThrowableProxyConverter();
53 }
54 tail.setNext(exConverter);
55 }
56 }
57
58 /**
59 * This method computes whether a chain of converters handles exceptions or
60 * not.
61 *
62 * @param head
63 * The first element of the chain
64 * @return true if can handle throwables contained in logging events
65 */
66 public boolean chainHandlesThrowable(Converter<ILoggingEvent> head) {
67 Converter<ILoggingEvent> c = head;
68 while (c != null) {
69 if (c instanceof ThrowableHandlingConverter) {
70 return true;
71 }
72 c = c.getNext();
73 }
74 return false;
75 }
76 }
77