001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache license, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the license for the specific language governing permissions and 015 * limitations under the license. 016 */ 017package org.apache.logging.log4j.core.pattern; 018 019import java.io.PrintWriter; 020import java.io.StringWriter; 021import java.util.ArrayList; 022import java.util.Collections; 023import java.util.List; 024 025import org.apache.logging.log4j.core.LogEvent; 026import org.apache.logging.log4j.core.config.Configuration; 027import org.apache.logging.log4j.core.config.plugins.Plugin; 028import org.apache.logging.log4j.core.impl.ThrowableFormatOptions; 029import org.apache.logging.log4j.core.layout.PatternLayout; 030import org.apache.logging.log4j.util.Strings; 031 032 033/** 034 * Outputs the Throwable portion of the LoggingEvent as a full stack trace 035 * unless this converter's option is 'short', where it just outputs the first line of the trace, or if 036 * the number of lines to print is explicitly specified. 037 */ 038@Plugin(name = "ThrowablePatternConverter", category = PatternConverter.CATEGORY) 039@ConverterKeys({ "ex", "throwable", "exception" }) 040public class ThrowablePatternConverter extends LogEventPatternConverter { 041 042 protected final List<PatternFormatter> formatters; 043 private String rawOption; 044 045 /** 046 * The number of lines to write. 047 */ 048 protected final ThrowableFormatOptions options; 049 050 /** 051 * Constructor. 052 * @param name Name of converter. 053 * @param style CSS style for output. 054 * @param options options, may be null. 055 * @param config 056 */ 057 protected ThrowablePatternConverter(final String name, final String style, final String[] options, final Configuration config) { 058 super(name, style); 059 this.options = ThrowableFormatOptions.newInstance(options); 060 if (options != null && options.length > 0) { 061 rawOption = options[0]; 062 } 063 if (this.options.getSuffix() != null) { 064 final PatternParser parser = PatternLayout.createPatternParser(config); 065 final List<PatternFormatter> parsedFormatters = parser.parse(this.options.getSuffix()); 066 // filter out nested formatters that will handle throwable 067 boolean hasThrowableFormatter = false; 068 for (final PatternFormatter formatter : parsedFormatters) { 069 if (formatter.handlesThrowable()) { 070 hasThrowableFormatter = true; 071 } 072 } 073 if (!hasThrowableFormatter) { 074 this.formatters = parsedFormatters; 075 } else { 076 final List<PatternFormatter> formatters = new ArrayList<>(); 077 for (final PatternFormatter formatter : parsedFormatters) { 078 if (!formatter.handlesThrowable()) { 079 formatters.add(formatter); 080 } 081 } 082 this.formatters = formatters; 083 } 084 } else { 085 this.formatters = Collections.emptyList(); 086 } 087 088 } 089 090 /** 091 * Gets an instance of the class. 092 * 093 * 094 * @param config 095 * @param options pattern options, may be null. If first element is "short", 096 * only the first line of the throwable will be formatted. 097 * @return instance of class. 098 */ 099 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(final LogEvent event) { 215 //noinspection ForLoopReplaceableByForEach 216 final 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}