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     */
017    package org.apache.logging.log4j.core.pattern;
018    
019    import org.apache.logging.log4j.core.LogEvent;
020    import org.apache.logging.log4j.core.config.plugins.Plugin;
021    
022    import java.io.PrintWriter;
023    import java.io.StringWriter;
024    
025    
026    /**
027     * Outputs the Throwable portion of the LoggingEvent as a full stacktrace
028     * unless this converter's option is 'short', where it just outputs the first line of the trace, or if
029     * the number of lines to print is explicitly specified.
030     */
031    @Plugin(name = "ThrowablePatternConverter", type = "Converter")
032    @ConverterKeys({"ex", "throwable", "exception" })
033    public class ThrowablePatternConverter extends LogEventPatternConverter {
034    
035        /**
036         * Do not format the exception.
037         */
038        protected static final String NONE = "none";
039        /**
040         * Format the whole stack trace.
041         */
042        protected static final String FULL = "full";
043        /**
044         * Format only the first line of the throwable.
045         */
046        protected static final String SHORT = "short";
047        /**
048         * If "short", only first line of throwable report will be formatted.<br>
049         * If "full", the whole stack trace will be formatted.<br>
050         * If "numeric" the output will be limited to the specified number of lines.
051         */
052        protected final String option;
053    
054        /**
055         * The number of lines to write.
056         */
057        protected final int lines;
058    
059        /**
060         * Constructor.
061         * @param name Name of converter.
062         * @param style CSS style for output.
063         * @param options options, may be null.
064         */
065        protected ThrowablePatternConverter(final String name, final String style, final String[] options) {
066            super(name, style);
067            int count = Integer.MAX_VALUE;
068            if (options != null && options.length > 0) {
069                option = options[0];
070                if (option == null) {
071                } else if (option.equalsIgnoreCase(NONE)) {
072                    count = 0;
073                } else if (option.equalsIgnoreCase(SHORT)) {
074                    count = 2;
075                } else if (!option.equalsIgnoreCase(FULL)) {
076                    count = Integer.parseInt(option);
077                }
078    
079            } else {
080                option = null;
081            }
082            lines = count;
083        }
084    
085        /**
086         * Gets an instance of the class.
087         *
088         * @param options pattern options, may be null.  If first element is "short",
089         *                only the first line of the throwable will be formatted.
090         * @return instance of class.
091         */
092        public static ThrowablePatternConverter newInstance(final String[] options) {
093            return new ThrowablePatternConverter("Throwable", "throwable", options);
094        }
095    
096        /**
097         * {@inheritDoc}
098         */
099        @Override
100        public void format(final LogEvent event, final StringBuilder toAppendTo) {
101            final Throwable t = event.getThrown();
102    
103            if (t != null && lines > 0) {
104                final StringWriter w = new StringWriter();
105                t.printStackTrace(new PrintWriter(w));
106                final int len = toAppendTo.length();
107                if (len > 0 && !Character.isWhitespace(toAppendTo.charAt(len - 1))) {
108                    toAppendTo.append(" ");
109                }
110                if (lines != Integer.MAX_VALUE) {
111                    final StringBuilder sb = new StringBuilder();
112                    final String[] array = w.toString().split("\n");
113                    final int limit = lines > array.length ? array.length : lines;
114                    for (int i = 0; i < limit; ++i) {
115                        sb.append(array[i]).append("\n");
116                    }
117                    toAppendTo.append(sb.toString());
118    
119                } else {
120                    toAppendTo.append(w.toString());
121                }
122            }
123        }
124    
125        /**
126         * This converter obviously handles throwables.
127         *
128         * @return true.
129         */
130        @Override
131        public boolean handlesThrowable() {
132            return true;
133        }
134    }