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  
21  import org.apache.logging.log4j.core.LogEvent;
22  import org.apache.logging.log4j.util.Strings;
23  
24  import com.fasterxml.jackson.core.JsonProcessingException;
25  import com.fasterxml.jackson.databind.ObjectWriter;
26  
27  abstract class AbstractJacksonLayout extends AbstractStringLayout {
28  
29      protected static final String DEFAULT_EOL = "\r\n";
30      protected static final String COMPACT_EOL = Strings.EMPTY;
31      protected final String eol;
32      protected final ObjectWriter objectWriter;
33      protected final boolean compact;
34      protected final boolean complete;
35  
36      protected AbstractJacksonLayout(final ObjectWriter objectWriter, final Charset charset, final boolean compact, final boolean complete) {
37          super(charset);
38          this.objectWriter = objectWriter;
39          this.compact = compact;
40          this.complete = complete;
41          this.eol = compact ? COMPACT_EOL : DEFAULT_EOL;
42      }
43  
44      /**
45       * Formats a {@link org.apache.logging.log4j.core.LogEvent}.
46       * 
47       * @param event The LogEvent.
48       * @return The XML representation of the LogEvent.
49       */
50      @Override
51      public String toSerializable(final LogEvent event) {
52          try {
53              return this.objectWriter.writeValueAsString(event);
54          } catch (final JsonProcessingException e) {
55              // Should this be an ISE or IAE?
56              LOGGER.error(e);
57              return Strings.EMPTY;
58          }
59      }
60  
61  }