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  
22  import org.apache.logging.log4j.core.LogEvent;
23  import org.apache.logging.log4j.core.config.plugins.Plugin;
24  import org.apache.logging.log4j.core.impl.ThrowableFormatOptions;
25  import org.apache.logging.log4j.core.util.Constants;
26  import org.apache.logging.log4j.util.Strings;
27  
28  
29  /**
30   * Outputs the Throwable portion of the LoggingEvent as a full stacktrace
31   * unless this converter's option is 'short', where it just outputs the first line of the trace, or if
32   * the number of lines to print is explicitly specified.
33   */
34  @Plugin(name = "ThrowablePatternConverter", category = "Converter")
35  @ConverterKeys({ "ex", "throwable", "exception" })
36  public class ThrowablePatternConverter extends LogEventPatternConverter {
37  
38      private String rawOption;
39  
40      /**
41       * The number of lines to write.
42       */
43      protected final ThrowableFormatOptions options;
44  
45      /**
46       * Constructor.
47       * @param name Name of converter.
48       * @param style CSS style for output.
49       * @param options options, may be null.
50       */
51      protected ThrowablePatternConverter(final String name, final String style, final String[] options) {
52          super(name, style);
53          this.options = ThrowableFormatOptions.newInstance(options);
54          if (options != null && options.length > 0) {
55              rawOption = options[0];
56          }
57      }
58  
59      /**
60       * Gets an instance of the class.
61       *
62       * @param options pattern options, may be null.  If first element is "short",
63       *                only the first line of the throwable will be formatted.
64       * @return instance of class.
65       */
66      public static ThrowablePatternConverter newInstance(final String[] options) {
67          return new ThrowablePatternConverter("Throwable", "throwable", options);
68      }
69  
70      /**
71       * {@inheritDoc}
72       */
73      @Override
74      public void format(final LogEvent event, final StringBuilder buffer) {
75          final Throwable t = event.getThrown();
76  
77          if (isSubShortOption()) {
78              formatSubShortOption(t, buffer);
79          }
80          else if (t != null && options.anyLines()) {
81              formatOption(t, buffer);
82          }
83      }
84  
85      private boolean isSubShortOption() {
86          return ThrowableFormatOptions.MESSAGE.equalsIgnoreCase(rawOption) ||
87                  ThrowableFormatOptions.LOCALIZED_MESSAGE.equalsIgnoreCase(rawOption) ||
88                  ThrowableFormatOptions.FILE_NAME.equalsIgnoreCase(rawOption) ||
89                  ThrowableFormatOptions.LINE_NUMBER.equalsIgnoreCase(rawOption) ||
90                  ThrowableFormatOptions.METHOD_NAME.equalsIgnoreCase(rawOption) ||
91                  ThrowableFormatOptions.CLASS_NAME.equalsIgnoreCase(rawOption);
92      }
93  
94      private void formatSubShortOption(final Throwable t, final StringBuilder buffer) {
95          StackTraceElement[] trace;
96          StackTraceElement throwingMethod = null;
97          int len;
98  
99          if (t != null) {
100             trace = t.getStackTrace();
101             if (trace !=null && trace.length > 0) {
102                 throwingMethod = trace[0];
103             }
104         }
105 
106         if (t != null && throwingMethod != null) {
107             String toAppend = Strings.EMPTY;
108 
109             if (ThrowableFormatOptions.CLASS_NAME.equalsIgnoreCase(rawOption)) {
110                 toAppend = throwingMethod.getClassName();
111             }
112             else if (ThrowableFormatOptions.METHOD_NAME.equalsIgnoreCase(rawOption)) {
113                 toAppend = throwingMethod.getMethodName();
114             }
115             else if (ThrowableFormatOptions.LINE_NUMBER.equalsIgnoreCase(rawOption)) {
116                 toAppend = String.valueOf(throwingMethod.getLineNumber());
117             }
118             else if (ThrowableFormatOptions.MESSAGE.equalsIgnoreCase(rawOption)) {
119                 toAppend = t.getMessage();
120             }
121             else if (ThrowableFormatOptions.LOCALIZED_MESSAGE.equalsIgnoreCase(rawOption)) {
122                 toAppend = t.getLocalizedMessage();
123             }
124             else if (ThrowableFormatOptions.FILE_NAME.equalsIgnoreCase(rawOption)) {
125                 toAppend = throwingMethod.getFileName();
126             }
127 
128             len = buffer.length();
129             if (len > 0 && !Character.isWhitespace(buffer.charAt(len - 1))) {
130                 buffer.append(' ');
131             }
132             buffer.append(toAppend);
133         }
134     }
135 
136     private void formatOption(final Throwable throwable, final StringBuilder buffer) {
137         final StringWriter w = new StringWriter();
138 
139         throwable.printStackTrace(new PrintWriter(w));
140         final int len = buffer.length();
141         if (len > 0 && !Character.isWhitespace(buffer.charAt(len - 1))) {
142             buffer.append(' ');
143         }
144         if (!options.allLines() || !Constants.LINE_SEPARATOR.equals(options.getSeparator())) {
145             final StringBuilder sb = new StringBuilder();
146             final String[] array = w.toString().split(Constants.LINE_SEPARATOR);
147             final int limit = options.minLines(array.length) - 1;
148             for (int i = 0; i <= limit; ++i) {
149                 sb.append(array[i]);
150                 if (i < limit) {
151                     sb.append(options.getSeparator());
152                 }
153             }
154             buffer.append(sb.toString());
155 
156         } else {
157             buffer.append(w.toString());
158         }
159     }
160 
161     /**
162      * This converter obviously handles throwables.
163      *
164      * @return true.
165      */
166     @Override
167     public boolean handlesThrowable() {
168         return true;
169     }
170 }