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.layout;
18  
19  import java.nio.charset.Charset;
20  import java.util.HashMap;
21  import java.util.List;
22  import java.util.Map;
23  
24  import org.apache.logging.log4j.core.LogEvent;
25  import org.apache.logging.log4j.core.config.Configuration;
26  import org.apache.logging.log4j.core.config.plugins.Plugin;
27  import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
28  import org.apache.logging.log4j.core.config.plugins.PluginConfiguration;
29  import org.apache.logging.log4j.core.config.plugins.PluginElement;
30  import org.apache.logging.log4j.core.config.plugins.PluginFactory;
31  import org.apache.logging.log4j.core.helpers.Booleans;
32  import org.apache.logging.log4j.core.helpers.Charsets;
33  import org.apache.logging.log4j.core.helpers.OptionConverter;
34  import org.apache.logging.log4j.core.pattern.LogEventPatternConverter;
35  import org.apache.logging.log4j.core.pattern.PatternFormatter;
36  import org.apache.logging.log4j.core.pattern.PatternParser;
37  import org.apache.logging.log4j.core.pattern.RegexReplacement;
38  
39  /**
40   * <p>A flexible layout configurable with pattern string. The goal of this class
41   * is to {@link org.apache.logging.log4j.core.Layout#toByteArray format} a {@link LogEvent} and return the results.
42   * The format of the result depends on the <em>conversion pattern</em>.
43   * <p>
44   * <p/>
45   * <p>The conversion pattern is closely related to the conversion
46   * pattern of the printf function in C. A conversion pattern is
47   * composed of literal text and format control expressions called
48   * <em>conversion specifiers</em>.
49   *
50   * See the Log4j Manual for details on the supported pattern converters.
51   */
52  @Plugin(name = "PatternLayout", category = "Core", elementType = "layout", printObject = true)
53  public final class PatternLayout extends AbstractStringLayout {
54      /**
55       * Default pattern string for log output. Currently set to the
56       * string <b>"%m%n"</b> which just prints the application supplied
57       * message.
58       */
59      public static final String DEFAULT_CONVERSION_PATTERN = "%m%n";
60  
61      /**
62       * A conversion pattern equivalent to the TTCCCLayout.
63       * Current value is <b>%r [%t] %p %c %x - %m%n</b>.
64       */
65      public static final String TTCC_CONVERSION_PATTERN =
66          "%r [%t] %p %c %x - %m%n";
67  
68      /**
69       * A simple pattern.
70       * Current value is <b>%d [%t] %p %c - %m%n</b>.
71       */
72      public static final String SIMPLE_CONVERSION_PATTERN =
73          "%d [%t] %p %c - %m%n";
74  
75      /** Key to identify pattern converters. */
76      public static final String KEY = "Converter";
77  
78      /**
79       * Initial converter for pattern.
80       */
81      private List<PatternFormatter> formatters;
82  
83      /**
84       * Conversion pattern.
85       */
86      private final String conversionPattern;
87  
88  
89      /**
90       * The current Configuration.
91       */
92      private final Configuration config;
93  
94      private final RegexReplacement replace;
95  
96      private final boolean alwaysWriteExceptions;
97  
98      private final boolean noConsoleNoAnsi;
99  
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 }