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.layout;
018
019import java.nio.charset.Charset;
020import java.util.HashMap;
021import java.util.List;
022import java.util.Map;
023
024import org.apache.logging.log4j.core.LogEvent;
025import org.apache.logging.log4j.core.config.Configuration;
026import org.apache.logging.log4j.core.config.plugins.Plugin;
027import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
028import org.apache.logging.log4j.core.config.plugins.PluginConfiguration;
029import org.apache.logging.log4j.core.config.plugins.PluginElement;
030import org.apache.logging.log4j.core.config.plugins.PluginFactory;
031import org.apache.logging.log4j.core.helpers.Booleans;
032import org.apache.logging.log4j.core.helpers.Charsets;
033import org.apache.logging.log4j.core.helpers.OptionConverter;
034import org.apache.logging.log4j.core.pattern.LogEventPatternConverter;
035import org.apache.logging.log4j.core.pattern.PatternFormatter;
036import org.apache.logging.log4j.core.pattern.PatternParser;
037import org.apache.logging.log4j.core.pattern.RegexReplacement;
038
039/**
040 * <p>A flexible layout configurable with pattern string. The goal of this class
041 * is to {@link org.apache.logging.log4j.core.Layout#toByteArray format} a {@link LogEvent} and return the results.
042 * The format of the result depends on the <em>conversion pattern</em>.
043 * <p>
044 * <p/>
045 * <p>The conversion pattern is closely related to the conversion
046 * pattern of the printf function in C. A conversion pattern is
047 * composed of literal text and format control expressions called
048 * <em>conversion specifiers</em>.
049 *
050 * See the Log4j Manual for details on the supported pattern converters.
051 */
052@Plugin(name = "PatternLayout", category = "Core", elementType = "layout", printObject = true)
053public final class PatternLayout extends AbstractStringLayout {
054    /**
055     * Default pattern string for log output. Currently set to the
056     * string <b>"%m%n"</b> which just prints the application supplied
057     * message.
058     */
059    public static final String DEFAULT_CONVERSION_PATTERN = "%m%n";
060
061    /**
062     * A conversion pattern equivalent to the TTCCCLayout.
063     * Current value is <b>%r [%t] %p %c %x - %m%n</b>.
064     */
065    public static final String TTCC_CONVERSION_PATTERN =
066        "%r [%t] %p %c %x - %m%n";
067
068    /**
069     * A simple pattern.
070     * Current value is <b>%d [%t] %p %c - %m%n</b>.
071     */
072    public static final String SIMPLE_CONVERSION_PATTERN =
073        "%d [%t] %p %c - %m%n";
074
075    /** Key to identify pattern converters. */
076    public static final String KEY = "Converter";
077
078    /**
079     * Initial converter for pattern.
080     */
081    private List<PatternFormatter> formatters;
082
083    /**
084     * Conversion pattern.
085     */
086    private final String conversionPattern;
087
088
089    /**
090     * The current Configuration.
091     */
092    private final Configuration config;
093
094    private final RegexReplacement replace;
095
096    private final boolean alwaysWriteExceptions;
097
098    private final boolean noConsoleNoAnsi;
099
100    /**
101     * Constructs a EnhancedPatternLayout using the supplied conversion pattern.
102     *
103     * @param config The Configuration.
104     * @param replace The regular expression to match.
105     * @param pattern conversion pattern.
106     * @param charset The character set.
107     * @param alwaysWriteExceptions Whether or not exceptions should always be handled in this pattern (if {@code true},
108     *                         exceptions will be written even if the pattern does not specify so).
109     * @param noConsoleNoAnsiStr
110     *            If {@code "true"} (default) and {@link System#console()} is null, do not output ANSI escape codes
111     */
112    private PatternLayout(final Configuration config, final RegexReplacement replace, final String pattern,
113                          final Charset charset, final boolean alwaysWriteExceptions, boolean noConsoleNoAnsi) {
114        super(charset);
115        this.replace = replace;
116        this.conversionPattern = pattern;
117        this.config = config;
118        this.alwaysWriteExceptions = alwaysWriteExceptions;
119        this.noConsoleNoAnsi = noConsoleNoAnsi;
120        final PatternParser parser = createPatternParser(config);
121        this.formatters = parser.parse(pattern == null ? DEFAULT_CONVERSION_PATTERN : pattern, this.alwaysWriteExceptions, this.noConsoleNoAnsi);
122    }
123
124    /**
125     * Set the <b>ConversionPattern</b> option. This is the string which
126     * controls formatting and consists of a mix of literal content and
127     * conversion specifiers.
128     *
129     * @param conversionPattern conversion pattern.
130     */
131    public void setConversionPattern(final String conversionPattern) {
132        final String pattern = OptionConverter.convertSpecialChars(conversionPattern);
133        if (pattern == null) {
134            return;
135        }
136        final PatternParser parser = createPatternParser(this.config);
137        formatters = parser.parse(pattern, this.alwaysWriteExceptions, this.noConsoleNoAnsi);
138    }
139
140    public String getConversionPattern() {
141        return conversionPattern;
142    }
143
144    /**
145     * PatternLayout's content format is specified by:<p/>
146     * Key: "structured" Value: "false"<p/>
147     * Key: "formatType" Value: "conversion" (format uses the keywords supported by OptionConverter)<p/>
148     * Key: "format" Value: provided "conversionPattern" param
149     * @return Map of content format keys supporting PatternLayout
150     */
151    @Override
152    public Map<String, String> getContentFormat()
153    {
154        final Map<String, String> result = new HashMap<String, String>();
155        result.put("structured", "false");
156        result.put("formatType", "conversion");
157        result.put("format", conversionPattern);
158        return result;
159    }
160
161    /**
162     * Formats a logging event to a writer.
163     *
164     *
165     * @param event logging event to be formatted.
166     * @return The event formatted as a String.
167     */
168    @Override
169    public String toSerializable(final LogEvent event) {
170        final StringBuilder buf = new StringBuilder();
171        for (final PatternFormatter formatter : formatters) {
172            formatter.format(event, buf);
173        }
174        String str = buf.toString();
175        if (replace != null) {
176            str = replace.format(str);
177        }
178        return str;
179    }
180
181    /**
182     * Create a PatternParser.
183     * @param config The Configuration.
184     * @return The PatternParser.
185     */
186    public static PatternParser createPatternParser(final Configuration config) {
187        if (config == null) {
188            return new PatternParser(config, KEY, LogEventPatternConverter.class);
189        }
190        PatternParser parser = config.getComponent(KEY);
191        if (parser == null) {
192            parser = new PatternParser(config, KEY, LogEventPatternConverter.class);
193            config.addComponent(KEY, parser);
194            parser = (PatternParser) config.getComponent(KEY);
195        }
196        return parser;
197    }
198
199    @Override
200    public String toString() {
201        return conversionPattern;
202    }
203
204    /**
205     * Create a pattern layout.
206     * 
207     * @param pattern
208     *            The pattern. If not specified, defaults to DEFAULT_CONVERSION_PATTERN.
209     * @param config
210     *            The Configuration. Some Converters require access to the Interpolator.
211     * @param replace
212     *            A Regex replacement String.
213     * @param charsetName
214     *            The character set.
215     * @param always
216     *            If {@code "true"} (default) exceptions are always written even if the pattern contains no exception
217     *            tokens.
218     * @param noConsoleNoAnsiStr
219     *            If {@code "true"} (default is false) and {@link System#console()} is null, do not output ANSI escape codes
220     * @return The PatternLayout.
221     */
222    @PluginFactory
223    public static PatternLayout createLayout(
224            @PluginAttribute("pattern") final String pattern,
225            @PluginConfiguration final Configuration config,
226            @PluginElement("Replace") final RegexReplacement replace,
227            @PluginAttribute("charset") final String charsetName,
228            @PluginAttribute("alwaysWriteExceptions") final String always, 
229            @PluginAttribute("noConsoleNoAnsi") final String noConsoleNoAnsiStr) {
230        final Charset charset = Charsets.getSupportedCharset(charsetName);
231        final boolean alwaysWriteExceptions = Booleans.parseBoolean(always, true);
232        final boolean noConsoleNoAnsi = Booleans.parseBoolean(noConsoleNoAnsiStr, false);
233        return new PatternLayout(config, replace, pattern == null ? DEFAULT_CONVERSION_PATTERN : pattern, charset,
234                alwaysWriteExceptions, noConsoleNoAnsi);
235    }
236}