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.nio.charset.StandardCharsets;
21  import java.util.HashMap;
22  import java.util.Map;
23  
24  import org.apache.logging.log4j.core.Layout;
25  import org.apache.logging.log4j.core.config.Configuration;
26  import org.apache.logging.log4j.core.config.DefaultConfiguration;
27  import org.apache.logging.log4j.core.config.Node;
28  import org.apache.logging.log4j.core.config.plugins.Plugin;
29  import org.apache.logging.log4j.core.config.plugins.PluginBuilderFactory;
30  import org.apache.logging.log4j.core.util.KeyValuePair;
31  import org.apache.logging.log4j.util.Strings;
32  
33  /**
34   * Appends a series of YAML events as strings serialized as bytes.
35   *
36   * <h3>Encoding</h3>
37   * <p>
38   * Appenders using this layout should have their {@code charset} set to {@code UTF-8} or {@code UTF-16}, otherwise
39   * events containing non ASCII characters could result in corrupted log files.
40   * </p>
41   * <h3>Additional Fields</h3>
42   * <p>
43   * This property allows addition of custom fields into generated JSON.
44   * {@code <YamlLayout><KeyValuePair key="foo" value="bar"/></YamlLayout>} inserts {@code foo: "bar"} directly
45   * into YAML output. Supports Lookup expressions.
46   * </p>
47   */
48  @Plugin(name = "YamlLayout", category = Node.CATEGORY, elementType = Layout.ELEMENT_TYPE, printObject = true)
49  public final class YamlLayout extends AbstractJacksonLayout {
50  
51      private static final String DEFAULT_FOOTER = Strings.EMPTY;
52  
53      private static final String DEFAULT_HEADER = Strings.EMPTY;
54  
55      static final String CONTENT_TYPE = "application/yaml";
56  
57      public static class Builder<B extends Builder<B>> extends AbstractJacksonLayout.Builder<B>
58          implements org.apache.logging.log4j.core.util.Builder<YamlLayout> {
59  
60          public Builder() {
61              super();
62              setCharset(StandardCharsets.UTF_8);
63          }
64  
65          @Override
66          public YamlLayout build() {
67              final String headerPattern = toStringOrNull(getHeader());
68              final String footerPattern = toStringOrNull(getFooter());
69              return new YamlLayout(getConfiguration(), isLocationInfo(), isProperties(), isComplete(),
70                      isCompact(), getEventEol(), getEndOfLine(), headerPattern, footerPattern, getCharset(),
71                      isIncludeStacktrace(), isStacktraceAsString(), isIncludeNullDelimiter(),
72                      isIncludeTimeMillis(), getAdditionalFields());
73          }
74      }
75  
76      /**
77       * @deprecated Use {@link #newBuilder()} instead
78       */
79      @Deprecated
80      protected YamlLayout(final Configuration config, final boolean locationInfo, final boolean properties,
81              final boolean complete, final boolean compact, final boolean eventEol, final String headerPattern,
82              final String footerPattern, final Charset charset, final boolean includeStacktrace) {
83          super(config, new JacksonFactory.YAML(includeStacktrace, false).newWriter(locationInfo, properties, compact),
84                  charset, compact, complete, eventEol, null,
85                  PatternLayout.newSerializerBuilder().setConfiguration(config).setPattern(headerPattern).setDefaultPattern(DEFAULT_HEADER).build(),
86                  PatternLayout.newSerializerBuilder().setConfiguration(config).setPattern(footerPattern).setDefaultPattern(DEFAULT_FOOTER).build(),
87                  false, null);
88      }
89  
90      private YamlLayout(final Configuration config, final boolean locationInfo, final boolean properties,
91                         final boolean complete, final boolean compact, final boolean eventEol, final String endOfLine,
92                         final String headerPattern, final String footerPattern, final Charset charset,
93                         final boolean includeStacktrace, final boolean stacktraceAsString,
94                         final boolean includeNullDelimiter, final boolean includeTimeMillis,
95                         final KeyValuePair[] additionalFields) {
96          super(config, new JacksonFactory.YAML(includeStacktrace, stacktraceAsString)
97                          .newWriter(locationInfo, properties, compact, includeTimeMillis),
98                  charset, compact, complete, eventEol, endOfLine,
99                  PatternLayout.newSerializerBuilder().setConfiguration(config).setPattern(headerPattern).setDefaultPattern(DEFAULT_HEADER).build(),
100                 PatternLayout.newSerializerBuilder().setConfiguration(config).setPattern(footerPattern).setDefaultPattern(DEFAULT_FOOTER).build(),
101                 includeNullDelimiter,
102                 additionalFields);
103     }
104 
105     /**
106      * Returns appropriate YAML header.
107      *
108      * @return a byte array containing the header, opening the YAML array.
109      */
110     @Override
111     public byte[] getHeader() {
112         if (!this.complete) {
113             return null;
114         }
115         final StringBuilder buf = new StringBuilder();
116         final String str = serializeToString(getHeaderSerializer());
117         if (str != null) {
118             buf.append(str);
119         }
120         buf.append(this.eol);
121         return getBytes(buf.toString());
122     }
123 
124     /**
125      * Returns appropriate YAML footer.
126      *
127      * @return a byte array containing the footer, closing the YAML array.
128      */
129     @Override
130     public byte[] getFooter() {
131         if (!this.complete) {
132             return null;
133         }
134         final StringBuilder buf = new StringBuilder();
135         buf.append(this.eol);
136         final String str = serializeToString(getFooterSerializer());
137         if (str != null) {
138             buf.append(str);
139         }
140         buf.append(this.eol);
141         return getBytes(buf.toString());
142     }
143 
144     @Override
145     public Map<String, String> getContentFormat() {
146         final Map<String, String> result = new HashMap<>();
147         result.put("version", "2.0");
148         return result;
149     }
150 
151     /**
152      * @return The content type.
153      */
154     @Override
155     public String getContentType() {
156         return CONTENT_TYPE + "; charset=" + this.getCharset();
157     }
158 
159     /**
160      * Creates a YAML Layout.
161      *
162      * @param config
163      *            The plugin configuration.
164      * @param locationInfo
165      *            If "true", includes the location information in the generated YAML.
166      * @param properties
167      *            If "true", includes the thread context map in the generated YAML.
168      * @param headerPattern
169      *            The header pattern, defaults to {@code ""} if null.
170      * @param footerPattern
171      *            The header pattern, defaults to {@code ""} if null.
172      * @param charset
173      *            The character set to use, if {@code null}, uses "UTF-8".
174      * @param includeStacktrace
175      *            If "true", includes the stacktrace of any Throwable in the generated YAML, defaults to "true".
176      * @return A YAML Layout.
177      *
178      * @deprecated Use {@link #newBuilder()} instead
179      */
180     @Deprecated
181     public static AbstractJacksonLayout createLayout(
182             final Configuration config,
183             final boolean locationInfo,
184             final boolean properties,
185             final String headerPattern,
186             final String footerPattern,
187             final Charset charset,
188             final boolean includeStacktrace) {
189         return new YamlLayout(config, locationInfo, properties, false, false, true, null, headerPattern, footerPattern,
190                 charset, includeStacktrace, false, false, false, null);
191     }
192 
193     @PluginBuilderFactory
194     public static <B extends Builder<B>> B newBuilder() {
195         return new Builder<B>().asBuilder();
196     }
197 
198     /**
199      * Creates a YAML Layout using the default settings. Useful for testing.
200      *
201      * @return A YAML Layout.
202      */
203     public static AbstractJacksonLayout createDefaultLayout() {
204         return new YamlLayout(new DefaultConfiguration(), false, false, false, false, false, null, DEFAULT_HEADER,
205                 DEFAULT_FOOTER, StandardCharsets.UTF_8, true, false, false, false, null);
206     }
207 }