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                      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,
95                         final KeyValuePair[] additionalFields) {
96          super(config, new JacksonFactory.YAML(includeStacktrace, stacktraceAsString).newWriter(locationInfo, properties, compact),
97                  charset, compact, complete, eventEol, endOfLine,
98                  PatternLayout.newSerializerBuilder().setConfiguration(config).setPattern(headerPattern).setDefaultPattern(DEFAULT_HEADER).build(),
99                  PatternLayout.newSerializerBuilder().setConfiguration(config).setPattern(footerPattern).setDefaultPattern(DEFAULT_FOOTER).build(),
100                 includeNullDelimiter,
101                 additionalFields);
102     }
103 
104     /**
105      * Returns appropriate YAML header.
106      *
107      * @return a byte array containing the header, opening the YAML array.
108      */
109     @Override
110     public byte[] getHeader() {
111         if (!this.complete) {
112             return null;
113         }
114         final StringBuilder buf = new StringBuilder();
115         final String str = serializeToString(getHeaderSerializer());
116         if (str != null) {
117             buf.append(str);
118         }
119         buf.append(this.eol);
120         return getBytes(buf.toString());
121     }
122 
123     /**
124      * Returns appropriate YAML footer.
125      *
126      * @return a byte array containing the footer, closing the YAML array.
127      */
128     @Override
129     public byte[] getFooter() {
130         if (!this.complete) {
131             return null;
132         }
133         final StringBuilder buf = new StringBuilder();
134         buf.append(this.eol);
135         final String str = serializeToString(getFooterSerializer());
136         if (str != null) {
137             buf.append(str);
138         }
139         buf.append(this.eol);
140         return getBytes(buf.toString());
141     }
142 
143     @Override
144     public Map<String, String> getContentFormat() {
145         final Map<String, String> result = new HashMap<>();
146         result.put("version", "2.0");
147         return result;
148     }
149 
150     /**
151      * @return The content type.
152      */
153     @Override
154     public String getContentType() {
155         return CONTENT_TYPE + "; charset=" + this.getCharset();
156     }
157 
158     /**
159      * Creates a YAML Layout.
160      *
161      * @param config
162      *            The plugin configuration.
163      * @param locationInfo
164      *            If "true", includes the location information in the generated YAML.
165      * @param properties
166      *            If "true", includes the thread context map in the generated YAML.
167      * @param headerPattern
168      *            The header pattern, defaults to {@code ""} if null.
169      * @param footerPattern
170      *            The header pattern, defaults to {@code ""} if null.
171      * @param charset
172      *            The character set to use, if {@code null}, uses "UTF-8".
173      * @param includeStacktrace
174      *            If "true", includes the stacktrace of any Throwable in the generated YAML, defaults to "true".
175      * @return A YAML Layout.
176      *
177      * @deprecated Use {@link #newBuilder()} instead
178      */
179     @Deprecated
180     public static AbstractJacksonLayout createLayout(
181             final Configuration config,
182             final boolean locationInfo,
183             final boolean properties,
184             final String headerPattern,
185             final String footerPattern,
186             final Charset charset,
187             final boolean includeStacktrace) {
188         return new YamlLayout(config, locationInfo, properties, false, false, true, null, headerPattern, footerPattern,
189                 charset, includeStacktrace, false, false, null);
190     }
191 
192     @PluginBuilderFactory
193     public static <B extends Builder<B>> B newBuilder() {
194         return new Builder<B>().asBuilder();
195     }
196 
197     /**
198      * Creates a YAML Layout using the default settings. Useful for testing.
199      *
200      * @return A YAML Layout.
201      */
202     public static AbstractJacksonLayout createDefaultLayout() {
203         return new YamlLayout(new DefaultConfiguration(), false, false, false, false, false, null, DEFAULT_HEADER,
204                 DEFAULT_FOOTER, StandardCharsets.UTF_8, true, false, false, null);
205     }
206 }