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 LoggingEvent.
26 * By default, outputs the full stack trace. %throwable{none}
27 * or %throwable{0} suppresses the stack trace. %throwable{short}
28 * or %throwable{1} outputs just the first line. %throwable{n}
29 * will output n lines for a positive integer or drop the last
30 * -n lines for a negative integer.
31 *
32 * @author Paul Smith
33 *
34 */
35 public class ThrowableInformationPatternConverter
36 extends LoggingEventPatternConverter {
37
38 /***
39 * Maximum lines of stack trace to output.
40 */
41 private int maxLines = Integer.MAX_VALUE;
42
43 /***
44 * Private constructor.
45 * @param options options, may be null.
46 */
47 private ThrowableInformationPatternConverter(
48 final String[] options) {
49 super("Throwable", "throwable");
50
51 if ((options != null) && (options.length > 0)) {
52 if("none".equals(options[0])) {
53 maxLines = 0;
54 } else if("short".equals(options[0])) {
55 maxLines = 1;
56 } else {
57 try {
58 maxLines = Integer.parseInt(options[0]);
59 } catch(NumberFormatException ex) {
60 maxLines = Integer.MAX_VALUE;
61 }
62 }
63 }
64 }
65
66 /***
67 * Gets an instance of the class.
68 * @param options pattern options, may be null. If first element is "short",
69 * only the first line of the throwable will be formatted.
70 * @return instance of class.
71 */
72 public static ThrowableInformationPatternConverter newInstance(
73 final String[] options) {
74 return new ThrowableInformationPatternConverter(options);
75 }
76
77 /***
78 * {@inheritDoc}
79 */
80 public void format(final LoggingEvent event, final StringBuffer toAppendTo) {
81 if (maxLines != 0) {
82 ThrowableInformation information = event.getThrowableInformation();
83
84 if (information != null) {
85 String[] stringRep = information.getThrowableStrRep();
86
87 int length = stringRep.length;
88 if (maxLines < 0) {
89 length += maxLines;
90 } else if (length > maxLines) {
91 length = maxLines;
92 }
93
94 for (int i = 0; i < length; i++) {
95 String string = stringRep[i];
96 toAppendTo.append(string).append("\n");
97 }
98 }
99 }
100 }
101
102 /***
103 * This converter obviously handles throwables.
104 * @return true.
105 */
106 public boolean handlesThrowable() {
107 return true;
108 }
109 }