1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.log4j.pattern;
19
20 import org.apache.log4j.spi.LoggingEvent;
21 import org.apache.log4j.spi.ThrowableInformation;
22
23
24 /***
25 * Outputs the ThrowableInformation portion of the LoggingiEvent as a full stacktrace
26 * unless this converter's option is 'short', where it just outputs the first line of the trace.
27 *
28 * @author Paul Smith
29 *
30 */
31 public class ThrowableInformationPatternConverter
32 extends LoggingEventPatternConverter {
33 /***
34 * If "short", only first line of throwable report will be formatted.
35 */
36 private final String option;
37
38 /***
39 * Private constructor.
40 * @param options options, may be null.
41 */
42 private ThrowableInformationPatternConverter(
43 final String[] options) {
44 super("Throwable", "throwable");
45
46 if ((options != null) && (options.length > 0)) {
47 option = options[0];
48 } else {
49 option = null;
50 }
51 }
52
53 /***
54 * Gets an instance of the class.
55 * @param options pattern options, may be null. If first element is "short",
56 * only the first line of the throwable will be formatted.
57 * @return instance of class.
58 */
59 public static ThrowableInformationPatternConverter newInstance(
60 final String[] options) {
61 return new ThrowableInformationPatternConverter(options);
62 }
63
64 /***
65 * {@inheritDoc}
66 */
67 public void format(final LoggingEvent event, final StringBuffer toAppendTo) {
68 ThrowableInformation information = event.getThrowableInformation();
69
70 if (information != null) {
71 String[] stringRep = information.getThrowableStrRep();
72
73 int length = 0;
74
75 if (option == null) {
76 length = stringRep.length;
77 } else if (option.equals("full")) {
78 length = stringRep.length;
79 } else if (option.equals("short")) {
80 length = 1;
81 } else {
82 length = stringRep.length;
83 }
84
85 for (int i = 0; i < length; i++) {
86 String string = stringRep[i];
87 toAppendTo.append(string).append("\n");
88 }
89 }
90 }
91
92 /***
93 * This converter obviously handles throwables.
94 * @return true.
95 */
96 public boolean handlesThrowable() {
97 return true;
98 }
99 }