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      protected final List<PatternFormatter> formatters;
43      private String rawOption;
44  
45      /**
46       * The number of lines to write.
47       */
48      protected final ThrowableFormatOptions options;
49  
50      /**
51       * Constructor.
52       * @param name Name of converter.
53       * @param style CSS style for output.
54       * @param options options, may be null.
55       * @param config
56       */
57      protected ThrowablePatternConverter(final String name, final String style, final String[] options, final Configuration config) {
58          super(name, style);
59          this.options = ThrowableFormatOptions.newInstance(options);
60          if (options != null && options.length > 0) {
61              rawOption = options[0];
62          }
63          if (this.options.getSuffix() != null) {
64              final PatternParser parser = PatternLayout.createPatternParser(config);
65              List<PatternFormatter> parsedFormatters = parser.parse(this.options.getSuffix());
66              // filter out nested formatters that will handle throwable
67              boolean hasThrowableFormatter = false;
68              for (PatternFormatter formatter : parsedFormatters) {
69                  if (formatter.handlesThrowable()) {
70                      hasThrowableFormatter = true;
71                  }
72              }
73              if (!hasThrowableFormatter) {
74                  this.formatters = parsedFormatters;
75              } else {
76                  List<PatternFormatter> formatters = new ArrayList<>();
77                  for (PatternFormatter formatter : parsedFormatters) {
78                      if (!formatter.handlesThrowable()) {
79                          formatters.add(formatter);
80                      }
81                  }
82                  this.formatters = formatters;
83              }
84          } else {
85              this.formatters = Collections.emptyList();
86          }
87  
88      }
89  
90      /**
91       * Gets an instance of the class.
92       *
93       *
94       * @param config
95       * @param options pattern options, may be null.  If first element is "short",
96       *                only the first line of the throwable will be formatted.
97       * @return instance of class.
98       */
99      public static ThrowablePatternConverter newInstance(final Configuration config, final String[] options) {
100         return new ThrowablePatternConverter("Throwable", "throwable", options, config);
101     }
102 
103     /**
104      * {@inheritDoc}
105      */
106     @Override
107     public void format(final LogEvent event, final StringBuilder buffer) {
108         final Throwable t = event.getThrown();
109 
110         if (isSubShortOption()) {
111             formatSubShortOption(t, getSuffix(event), buffer);
112         }
113         else if (t != null && options.anyLines()) {
114             formatOption(t, getSuffix(event), buffer);
115         }
116     }
117 
118     private boolean isSubShortOption() {
119         return ThrowableFormatOptions.MESSAGE.equalsIgnoreCase(rawOption) ||
120                 ThrowableFormatOptions.LOCALIZED_MESSAGE.equalsIgnoreCase(rawOption) ||
121                 ThrowableFormatOptions.FILE_NAME.equalsIgnoreCase(rawOption) ||
122                 ThrowableFormatOptions.LINE_NUMBER.equalsIgnoreCase(rawOption) ||
123                 ThrowableFormatOptions.METHOD_NAME.equalsIgnoreCase(rawOption) ||
124                 ThrowableFormatOptions.CLASS_NAME.equalsIgnoreCase(rawOption);
125     }
126 
127     private void formatSubShortOption(final Throwable t, final String suffix, final StringBuilder buffer) {
128         StackTraceElement[] trace;
129         StackTraceElement throwingMethod = null;
130         int len;
131 
132         if (t != null) {
133             trace = t.getStackTrace();
134             if (trace !=null && trace.length > 0) {
135                 throwingMethod = trace[0];
136             }
137         }
138 
139         if (t != null && throwingMethod != null) {
140             String toAppend = Strings.EMPTY;
141 
142             if (ThrowableFormatOptions.CLASS_NAME.equalsIgnoreCase(rawOption)) {
143                 toAppend = throwingMethod.getClassName();
144             }
145             else if (ThrowableFormatOptions.METHOD_NAME.equalsIgnoreCase(rawOption)) {
146                 toAppend = throwingMethod.getMethodName();
147             }
148             else if (ThrowableFormatOptions.LINE_NUMBER.equalsIgnoreCase(rawOption)) {
149                 toAppend = String.valueOf(throwingMethod.getLineNumber());
150             }
151             else if (ThrowableFormatOptions.MESSAGE.equalsIgnoreCase(rawOption)) {
152                 toAppend = t.getMessage();
153             }
154             else if (ThrowableFormatOptions.LOCALIZED_MESSAGE.equalsIgnoreCase(rawOption)) {
155                 toAppend = t.getLocalizedMessage();
156             }
157             else if (ThrowableFormatOptions.FILE_NAME.equalsIgnoreCase(rawOption)) {
158                 toAppend = throwingMethod.getFileName();
159             }
160 
161             len = buffer.length();
162             if (len > 0 && !Character.isWhitespace(buffer.charAt(len - 1))) {
163                 buffer.append(' ');
164             }
165             buffer.append(toAppend);
166 
167             if (Strings.isNotBlank(suffix)) {
168                 buffer.append(' ');
169                 buffer.append(suffix);
170             }
171         }
172     }
173 
174     private void formatOption(final Throwable throwable, final String suffix, final StringBuilder buffer) {
175         final StringWriter w = new StringWriter();
176 
177         throwable.printStackTrace(new PrintWriter(w));
178         final int len = buffer.length();
179         if (len > 0 && !Character.isWhitespace(buffer.charAt(len - 1))) {
180             buffer.append(' ');
181         }
182         if (!options.allLines() || !Strings.LINE_SEPARATOR.equals(options.getSeparator()) || Strings.isNotBlank(suffix)) {
183             final StringBuilder sb = new StringBuilder();
184             final String[] array = w.toString().split(Strings.LINE_SEPARATOR);
185             final int limit = options.minLines(array.length) - 1;
186             final boolean suffixNotBlank = Strings.isNotBlank(suffix);
187             for (int i = 0; i <= limit; ++i) {
188                 sb.append(array[i]);
189                 if (suffixNotBlank) {
190                     sb.append(' ');
191                     sb.append(suffix);
192                 }
193                 if (i < limit) {
194                     sb.append(options.getSeparator());
195                 }
196             }
197             buffer.append(sb.toString());
198 
199         } else {
200             buffer.append(w.toString());
201         }
202     }
203 
204     /**
205      * This converter obviously handles throwables.
206      *
207      * @return true.
208      */
209     @Override
210     public boolean handlesThrowable() {
211         return true;
212     }
213 
214     protected String getSuffix(LogEvent event) {
215         //noinspection ForLoopReplaceableByForEach
216         StringBuilder toAppendTo = new StringBuilder();
217         for (int i = 0, size = formatters.size(); i <  size; i++) {
218             formatters.get(i).format(event, toAppendTo);
219         }
220         return toAppendTo.toString();
221     }
222 }