1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.logging.log4j.core.pattern;
18
19 import org.apache.logging.log4j.core.LogEvent;
20 import org.apache.logging.log4j.core.config.plugins.Plugin;
21 import org.apache.logging.log4j.core.impl.ThrowableProxy;
22
23 import java.util.ArrayList;
24 import java.util.List;
25 import java.util.Scanner;
26
27
28
29
30
31
32
33
34
35
36 @Plugin(name = "RootThrowablePatternConverter", type = "Converter")
37 @ConverterKeys({"rEx", "rThrowable", "rException" })
38 public final class RootThrowablePatternConverter extends ThrowablePatternConverter {
39
40 private static final String FILTERS = "filters(";
41
42 private final List<String> packages;
43
44
45
46
47
48
49 private RootThrowablePatternConverter(final String[] options) {
50 super("RootThrowable", "throwable", options);
51 List<String> tempPackages = null;
52 if (options != null && options.length > 1) {
53 if (options[1].startsWith(FILTERS) && options[1].endsWith(")")) {
54 String filterStr = options[1].substring(FILTERS.length(), options[1].length() - 1);
55 String[] array = filterStr.split(",");
56 if (array.length > 0) {
57 tempPackages = new ArrayList<String>(array.length);
58 for (String token : array) {
59 tempPackages.add(token.trim());
60 }
61 }
62 }
63 }
64 packages = tempPackages;
65 }
66
67
68
69
70
71
72
73
74 public static RootThrowablePatternConverter newInstance(final String[] options) {
75 String type = null;
76 String[] array = options;
77 if (options != null && options.length == 1 && options[0].length() > 0) {
78 String[] opts = options[0].split(",", 2);
79 String first = opts[0].trim();
80 String filter;
81 Scanner scanner = new Scanner(first);
82 if (first.equalsIgnoreCase(FULL) || first.equalsIgnoreCase(SHORT) || scanner.hasNextInt()) {
83 type = first;
84 filter = opts[1].trim();
85 } else {
86 filter = options[0].trim();
87 }
88 array = new String[] {type, filter};
89 }
90
91 return new RootThrowablePatternConverter(array);
92 }
93
94
95
96
97 @Override
98 public void format(final LogEvent event, final StringBuilder toAppendTo) {
99 Throwable throwable = event.getThrown();
100 if (throwable != null) {
101 if (!(throwable instanceof ThrowableProxy)) {
102 super.format(event, toAppendTo);
103 return;
104 }
105 ThrowableProxy t = (ThrowableProxy) throwable;
106 String trace = t.getRootCauseStackTrace(packages);
107 int len = toAppendTo.length();
108 if (len > 0 && !Character.isWhitespace(toAppendTo.charAt(len - 1))) {
109 toAppendTo.append(" ");
110 }
111 if (lines > 0) {
112 StringBuilder sb = new StringBuilder();
113 String[] array = trace.split("\n");
114 for (int i = 0; i < lines; ++i) {
115 sb.append(array[i]).append("\n");
116 }
117 toAppendTo.append(sb.toString());
118
119 } else {
120 toAppendTo.append(trace);
121 }
122 }
123 }
124 }