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.io.IOException;
20  import java.io.Writer;
21  import java.nio.charset.Charset;
22  import java.nio.charset.StandardCharsets;
23  import java.util.HashMap;
24  import java.util.Map;
25  
26  import org.apache.logging.log4j.core.Layout;
27  import org.apache.logging.log4j.core.LogEvent;
28  import org.apache.logging.log4j.core.config.Configuration;
29  import org.apache.logging.log4j.core.config.DefaultConfiguration;
30  import org.apache.logging.log4j.core.config.Node;
31  import org.apache.logging.log4j.core.config.plugins.Plugin;
32  import org.apache.logging.log4j.core.config.plugins.PluginBuilderAttribute;
33  import org.apache.logging.log4j.core.config.plugins.PluginBuilderFactory;
34  
35  /**
36   * Appends a series of JSON events as strings serialized as bytes.
37   *
38   * <h3>Complete well-formed JSON vs. fragment JSON</h3>
39   * <p>
40   * If you configure {@code complete="true"}, the appender outputs a well-formed JSON document. By default, with
41   * {@code complete="false"}, you should include the output as an <em>external file</em> in a separate file to form a
42   * well-formed JSON document.
43   * </p>
44   * <p>
45   * If {@code complete="false"}, the appender does not write the JSON open array character "[" at the start
46   * of the document, "]" and the end, nor comma "," between records.
47   * </p>
48   * <h3>Encoding</h3>
49   * <p>
50   * Appenders using this layout should have their {@code charset} set to {@code UTF-8} or {@code UTF-16}, otherwise
51   * events containing non ASCII characters could result in corrupted log files.
52   * </p>
53   * <h3>Pretty vs. compact JSON</h3>
54   * <p>
55   * By default, the JSON layout is not compact (a.k.a. "pretty") with {@code compact="false"}, which means the
56   * appender uses end-of-line characters and indents lines to format the text. If {@code compact="true"}, then no
57   * end-of-line or indentation is used. Message content may contain, of course, escaped end-of-lines.
58   * </p>
59   */
60  @Plugin(name = "JsonLayout", category = Node.CATEGORY, elementType = Layout.ELEMENT_TYPE, printObject = true)
61  public final class JsonLayout extends AbstractJacksonLayout {
62  
63      private static final String DEFAULT_FOOTER = "]";
64  
65      private static final String DEFAULT_HEADER = "[";
66  
67      static final String CONTENT_TYPE = "application/json";
68  
69      public static class Builder<B extends Builder<B>> extends AbstractJacksonLayout.Builder<B>
70              implements org.apache.logging.log4j.core.util.Builder<JsonLayout> {
71  
72          @PluginBuilderAttribute
73          private boolean propertiesAsList;
74          
75          public Builder() {
76              super();
77              setCharset(StandardCharsets.UTF_8);
78          }
79  
80          @Override
81          public JsonLayout build() {
82              final boolean encodeThreadContextAsList = isProperties() && propertiesAsList;
83              final String headerPattern = toStringOrNull(getHeader());
84              final String footerPattern = toStringOrNull(getFooter());
85              return new JsonLayout(getConfiguration(), isLocationInfo(), isProperties(), encodeThreadContextAsList,
86                      isComplete(), isCompact(), getEventEol(), headerPattern, footerPattern, getCharset(),
87                      isIncludeStacktrace(), isStacktraceAsString(), isIncludeNullDelimiter());
88          }
89  
90          public boolean isPropertiesAsList() {
91              return propertiesAsList;
92          }
93  
94          public B setPropertiesAsList(final boolean propertiesAsList) {
95              this.propertiesAsList = propertiesAsList;
96              return asBuilder();
97          }
98      }
99  
100     /**
101      * @deprecated Use {@link #newBuilder()} instead
102      */
103     @Deprecated
104     protected JsonLayout(final Configuration config, final boolean locationInfo, final boolean properties,
105             final boolean encodeThreadContextAsList,
106             final boolean complete, final boolean compact, final boolean eventEol, final String headerPattern,
107             final String footerPattern, final Charset charset, final boolean includeStacktrace) {
108         super(config, new JacksonFactory.JSON(encodeThreadContextAsList, includeStacktrace, false).newWriter(
109                 locationInfo, properties, compact),
110                 charset, compact, complete, eventEol,
111                 PatternLayout.newSerializerBuilder().setConfiguration(config).setPattern(headerPattern).setDefaultPattern(DEFAULT_HEADER).build(),
112                 PatternLayout.newSerializerBuilder().setConfiguration(config).setPattern(footerPattern).setDefaultPattern(DEFAULT_FOOTER).build(),
113                 false);
114     }
115 
116     private JsonLayout(final Configuration config, final boolean locationInfo, final boolean properties,
117                        final boolean encodeThreadContextAsList,
118                        final boolean complete, final boolean compact, final boolean eventEol,
119                        final String headerPattern,final String footerPattern, final Charset charset,
120                        final boolean includeStacktrace,final boolean stacktraceAsString,
121                        final boolean includeNullDelimiter) {
122         super(config, new JacksonFactory.JSON(encodeThreadContextAsList, includeStacktrace, stacktraceAsString).newWriter(
123                 locationInfo, properties, compact),
124                 charset, compact, complete, eventEol,
125                 PatternLayout.newSerializerBuilder().setConfiguration(config).setPattern(headerPattern).setDefaultPattern(DEFAULT_HEADER).build(),
126                 PatternLayout.newSerializerBuilder().setConfiguration(config).setPattern(footerPattern).setDefaultPattern(DEFAULT_FOOTER).build(),
127                 includeNullDelimiter);
128     }
129 
130     /**
131      * Returns appropriate JSON header.
132      *
133      * @return a byte array containing the header, opening the JSON array.
134      */
135     @Override
136     public byte[] getHeader() {
137         if (!this.complete) {
138             return null;
139         }
140         final StringBuilder buf = new StringBuilder();
141         final String str = serializeToString(getHeaderSerializer());
142         if (str != null) {
143             buf.append(str);
144         }
145         buf.append(this.eol);
146         return getBytes(buf.toString());
147     }
148 
149     /**
150      * Returns appropriate JSON footer.
151      *
152      * @return a byte array containing the footer, closing the JSON array.
153      */
154     @Override
155     public byte[] getFooter() {
156         if (!this.complete) {
157             return null;
158         }
159         final StringBuilder buf = new StringBuilder();
160         buf.append(this.eol);
161         final String str = serializeToString(getFooterSerializer());
162         if (str != null) {
163             buf.append(str);
164         }
165         buf.append(this.eol);
166         return getBytes(buf.toString());
167     }
168 
169     @Override
170     public Map<String, String> getContentFormat() {
171         final Map<String, String> result = new HashMap<>();
172         result.put("version", "2.0");
173         return result;
174     }
175 
176     /**
177      * @return The content type.
178      */
179     @Override
180     public String getContentType() {
181         return CONTENT_TYPE + "; charset=" + this.getCharset();
182     }
183 
184     /**
185      * Creates a JSON Layout.
186      * @param config
187      *           The plugin configuration.
188      * @param locationInfo
189      *            If "true", includes the location information in the generated JSON.
190      * @param properties
191      *            If "true", includes the thread context map in the generated JSON.
192      * @param propertiesAsList
193      *            If true, the thread context map is included as a list of map entry objects, where each entry has
194      *            a "key" attribute (whose value is the key) and a "value" attribute (whose value is the value).
195      *            Defaults to false, in which case the thread context map is included as a simple map of key-value
196      *            pairs.
197      * @param complete
198      *            If "true", includes the JSON header and footer, and comma between records.
199      * @param compact
200      *            If "true", does not use end-of-lines and indentation, defaults to "false".
201      * @param eventEol
202      *            If "true", forces an EOL after each log event (even if compact is "true"), defaults to "false". This
203      *            allows one even per line, even in compact mode.
204      * @param headerPattern
205      *            The header pattern, defaults to {@code "["} if null.
206      * @param footerPattern
207      *            The header pattern, defaults to {@code "]"} if null.
208      * @param charset
209      *            The character set to use, if {@code null}, uses "UTF-8".
210      * @param includeStacktrace
211      *            If "true", includes the stacktrace of any Throwable in the generated JSON, defaults to "true".
212      * @return A JSON Layout.
213      *
214      * @deprecated Use {@link #newBuilder()} instead
215      */
216     @Deprecated
217     public static JsonLayout createLayout(
218             final Configuration config,
219             final boolean locationInfo,
220             final boolean properties,
221             final boolean propertiesAsList,
222             final boolean complete,
223             final boolean compact,
224             final boolean eventEol,
225             final String headerPattern,
226             final String footerPattern,
227             final Charset charset,
228             final boolean includeStacktrace) {
229         final boolean encodeThreadContextAsList = properties && propertiesAsList;
230         return new JsonLayout(config, locationInfo, properties, encodeThreadContextAsList, complete, compact, eventEol,
231                 headerPattern, footerPattern, charset, includeStacktrace, false, false);
232     }
233 
234     @PluginBuilderFactory
235     public static <B extends Builder<B>> B newBuilder() {
236         return new Builder<B>().asBuilder();
237     }
238 
239     /**
240      * Creates a JSON Layout using the default settings. Useful for testing.
241      *
242      * @return A JSON Layout.
243      */
244     public static JsonLayout createDefaultLayout() {
245         return new JsonLayout(new DefaultConfiguration(), false, false, false, false, false, false,
246                 DEFAULT_HEADER, DEFAULT_FOOTER, StandardCharsets.UTF_8, true, false, false);
247     }
248 
249     @Override
250     public void toSerializable(final LogEvent event, final Writer writer) throws IOException {
251         if (complete && eventCount > 0) {
252             writer.append(", ");
253         }
254         super.toSerializable(event, writer);
255     }
256 }