View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the license for the specific language governing permissions and
15   * limitations under the license.
16   */
17  package org.apache.logging.log4j.core.pattern;
18  
19  import java.io.PrintWriter;
20  import java.io.StringWriter;
21  import java.util.ArrayList;
22  import java.util.Collections;
23  import java.util.List;
24  
25  import org.apache.logging.log4j.core.LogEvent;
26  import org.apache.logging.log4j.core.config.Configuration;
27  import org.apache.logging.log4j.core.config.plugins.Plugin;
28  import org.apache.logging.log4j.core.impl.ThrowableFormatOptions;
29  import org.apache.logging.log4j.core.layout.PatternLayout;
30  import org.apache.logging.log4j.util.Strings;
31  
32  
33  /**
34   * Outputs the Throwable portion of the LoggingEvent as a full stack trace
35   * unless this converter's option is 'short', where it just outputs the first line of the trace, or if
36   * the number of lines to print is explicitly specified.
37   */
38  @Plugin(name = "ThrowablePatternConverter", category = PatternConverter.CATEGORY)
39  @ConverterKeys({ "ex", "throwable", "exception" })
40  public class ThrowablePatternConverter extends LogEventPatternConverter {
41  
42      /**
43       * Lists {@link PatternFormatter}s for the suffix attribute.
44       */
45      protected final List<PatternFormatter> formatters;
46      private String rawOption;
47  
48      /**
49       * Options.
50       */
51      protected final ThrowableFormatOptions options;
52  
53      /**
54       * Constructor.
55       * @param name Name of converter.
56       * @param style CSS style for output.
57       * @param options options, may be null.
58       * @param config
59       */
60      protected ThrowablePatternConverter(final String name, final String style, final String[] options, final Configuration config) {
61          super(name, style);
62          this.options = ThrowableFormatOptions.newInstance(options);
63          if (options != null && options.length > 0) {
64              rawOption = options[0];
65          }
66          if (this.options.getSuffix() != null) {
67              final PatternParser parser = PatternLayout.createPatternParser(config);
68              final List<PatternFormatter> parsedSuffixFormatters = parser.parse(this.options.getSuffix());
69              // filter out nested formatters that will handle throwable
70              boolean hasThrowableSuffixFormatter = false;
71              for (final PatternFormatter suffixFormatter : parsedSuffixFormatters) {
72                  if (suffixFormatter.handlesThrowable()) {
73                      hasThrowableSuffixFormatter = true;
74                  }
75              }
76              if (!hasThrowableSuffixFormatter) {
77                  this.formatters = parsedSuffixFormatters;
78              } else {
79                  final List<PatternFormatter> suffixFormatters = new ArrayList<>();
80                  for (final PatternFormatter suffixFormatter : parsedSuffixFormatters) {
81                      if (!suffixFormatter.handlesThrowable()) {
82                          suffixFormatters.add(suffixFormatter);
83                      }
84                  }
85                  this.formatters = suffixFormatters;
86              }
87          } else {
88              this.formatters = Collections.emptyList();
89          }
90  
91      }
92  
93      /**
94       * Gets an instance of the class.
95       *
96       * @param config
97       * @param options pattern options, may be null.  If first element is "short",
98       *                only the first line of the throwable will be formatted.
99       * @return instance of class.
100      */
101     public static ThrowablePatternConverter newInstance(final Configuration config, final String[] options) {
102         return new ThrowablePatternConverter("Throwable", "throwable", options, config);
103     }
104 
105     /**
106      * {@inheritDoc}
107      */
108     @Override
109     public void format(final LogEvent event, final StringBuilder buffer) {
110         final Throwable t = event.getThrown();
111 
112         if (isSubShortOption()) {
113             formatSubShortOption(t, getSuffix(event), buffer);
114         }
115         else if (t != null && options.anyLines()) {
116             formatOption(t, getSuffix(event), buffer);
117         }
118     }
119 
120     private boolean isSubShortOption() {
121         return ThrowableFormatOptions.MESSAGE.equalsIgnoreCase(rawOption) ||
122                 ThrowableFormatOptions.LOCALIZED_MESSAGE.equalsIgnoreCase(rawOption) ||
123                 ThrowableFormatOptions.FILE_NAME.equalsIgnoreCase(rawOption) ||
124                 ThrowableFormatOptions.LINE_NUMBER.equalsIgnoreCase(rawOption) ||
125                 ThrowableFormatOptions.METHOD_NAME.equalsIgnoreCase(rawOption) ||
126                 ThrowableFormatOptions.CLASS_NAME.equalsIgnoreCase(rawOption);
127     }
128 
129     private void formatSubShortOption(final Throwable t, final String suffix, final StringBuilder buffer) {
130         StackTraceElement[] trace;
131         StackTraceElement throwingMethod = null;
132         int len;
133 
134         if (t != null) {
135             trace = t.getStackTrace();
136             if (trace !=null && trace.length > 0) {
137                 throwingMethod = trace[0];
138             }
139         }
140 
141         if (t != null && throwingMethod != null) {
142             String toAppend = Strings.EMPTY;
143 
144             if (ThrowableFormatOptions.CLASS_NAME.equalsIgnoreCase(rawOption)) {
145                 toAppend = throwingMethod.getClassName();
146             }
147             else if (ThrowableFormatOptions.METHOD_NAME.equalsIgnoreCase(rawOption)) {
148                 toAppend = throwingMethod.getMethodName();
149             }
150             else if (ThrowableFormatOptions.LINE_NUMBER.equalsIgnoreCase(rawOption)) {
151                 toAppend = String.valueOf(throwingMethod.getLineNumber());
152             }
153             else if (ThrowableFormatOptions.MESSAGE.equalsIgnoreCase(rawOption)) {
154                 toAppend = t.getMessage();
155             }
156             else if (ThrowableFormatOptions.LOCALIZED_MESSAGE.equalsIgnoreCase(rawOption)) {
157                 toAppend = t.getLocalizedMessage();
158             }
159             else if (ThrowableFormatOptions.FILE_NAME.equalsIgnoreCase(rawOption)) {
160                 toAppend = throwingMethod.getFileName();
161             }
162 
163             len = buffer.length();
164             if (len > 0 && !Character.isWhitespace(buffer.charAt(len - 1))) {
165                 buffer.append(' ');
166             }
167             buffer.append(toAppend);
168 
169             if (Strings.isNotBlank(suffix)) {
170                 buffer.append(' ');
171                 buffer.append(suffix);
172             }
173         }
174     }
175 
176     private void formatOption(final Throwable throwable, final String suffix, final StringBuilder buffer) {
177         final StringWriter w = new StringWriter();
178 
179         throwable.printStackTrace(new PrintWriter(w));
180         final int len = buffer.length();
181         if (len > 0 && !Character.isWhitespace(buffer.charAt(len - 1))) {
182             buffer.append(' ');
183         }
184         if (!options.allLines() || !Strings.LINE_SEPARATOR.equals(options.getSeparator()) || Strings.isNotBlank(suffix)) {
185             final StringBuilder sb = new StringBuilder();
186             final String[] array = w.toString().split(Strings.LINE_SEPARATOR);
187             final int limit = options.minLines(array.length) - 1;
188             final boolean suffixNotBlank = Strings.isNotBlank(suffix);
189             for (int i = 0; i <= limit; ++i) {
190                 sb.append(array[i]);
191                 if (suffixNotBlank) {
192                     sb.append(' ');
193                     sb.append(suffix);
194                 }
195                 if (i < limit) {
196                     sb.append(options.getSeparator());
197                 }
198             }
199             buffer.append(sb.toString());
200 
201         } else {
202             buffer.append(w.toString());
203         }
204     }
205 
206     /**
207      * This converter obviously handles throwables.
208      *
209      * @return true.
210      */
211     @Override
212     public boolean handlesThrowable() {
213         return true;
214     }
215 
216     protected String getSuffix(final LogEvent event) {
217         //noinspection ForLoopReplaceableByForEach
218         final StringBuilder toAppendTo = new StringBuilder();
219         for (int i = 0, size = formatters.size(); i <  size; i++) {
220             formatters.get(i).format(event, toAppendTo);
221         }
222         return toAppendTo.toString();
223     }
224 
225     public ThrowableFormatOptions getOptions() {
226         return options;
227     }
228 }