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      private static final long serialVersionUID = 1L;
30      protected static final String DEFAULT_EOL = "\r\n";
31      protected static final String COMPACT_EOL = Strings.EMPTY;
32      protected final String eol;
33      protected final ObjectWriter objectWriter;
34      protected final boolean compact;
35      protected final boolean complete;
36  
37      protected AbstractJacksonLayout(final ObjectWriter objectWriter, final Charset charset, final boolean compact, final boolean complete, boolean eventEol) {
38          super(charset);
39          this.objectWriter = objectWriter;
40          this.compact = compact;
41          this.complete = complete;
42          this.eol = compact && !eventEol ? COMPACT_EOL : DEFAULT_EOL;
43      }
44  
45      /**
46       * Formats a {@link org.apache.logging.log4j.core.LogEvent}.
47       * 
48       * @param event The LogEvent.
49       * @return The XML representation of the LogEvent.
50       */
51      @Override
52      public String toSerializable(final LogEvent event) {
53          try {
54              return this.objectWriter.writeValueAsString(event) + eol;
55          } catch (final JsonProcessingException e) {
56              // Should this be an ISE or IAE?
57              LOGGER.error(e);
58              return Strings.EMPTY;
59          }
60      }
61  
62  }