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.text.SimpleDateFormat;
21  import java.util.Date;
22  import java.util.HashMap;
23  import java.util.Locale;
24  import java.util.Map;
25  import java.util.regex.Matcher;
26  import java.util.regex.Pattern;
27  
28  import org.apache.logging.log4j.core.Layout;
29  import org.apache.logging.log4j.core.LogEvent;
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.PluginAttribute;
33  import org.apache.logging.log4j.core.config.plugins.PluginFactory;
34  import org.apache.logging.log4j.core.net.Facility;
35  import org.apache.logging.log4j.core.net.Priority;
36  import org.apache.logging.log4j.core.util.NetUtils;
37  import org.apache.logging.log4j.util.Chars;
38  
39  
40  /**
41   * Formats a log event as a BSD Log record.
42   */
43  @Plugin(name = "SyslogLayout", category = Node.CATEGORY, elementType = Layout.ELEMENT_TYPE, printObject = true)
44  public final class SyslogLayout extends AbstractStringLayout {
45  
46      /**
47       * Match newlines in a platform-independent manner.
48       */
49      public static final Pattern NEWLINE_PATTERN = Pattern.compile("\\r?\\n");
50  
51      private final Facility facility;
52      private final boolean includeNewLine;
53      private final String escapeNewLine;
54  
55      /**
56       * Date format used if header = true.
57       */
58      private final SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd HH:mm:ss", Locale.ENGLISH);
59      /**
60       * Host name used to identify messages from this appender.
61       */
62      private final String localHostname = NetUtils.getLocalHostname();
63  
64      protected SyslogLayout(final Facility facility, final boolean includeNL, final String escapeNL, final Charset charset) {
65          super(charset);
66          this.facility = facility;
67          this.includeNewLine = includeNL;
68          this.escapeNewLine = escapeNL == null ? null : Matcher.quoteReplacement(escapeNL);
69      }
70  
71      /**
72       * Formats a {@link org.apache.logging.log4j.core.LogEvent} in conformance with the BSD Log record format.
73       *
74       * @param event The LogEvent
75       * @return the event formatted as a String.
76       */
77      @Override
78      public String toSerializable(final LogEvent event) {
79          final StringBuilder buf = getStringBuilder();
80  
81          buf.append('<');
82          buf.append(Priority.getPriority(facility, event.getLevel()));
83          buf.append('>');
84          addDate(event.getTimeMillis(), buf);
85          buf.append(Chars.SPACE);
86          buf.append(localHostname);
87          buf.append(Chars.SPACE);
88  
89          String message = event.getMessage().getFormattedMessage();
90          if (null != escapeNewLine) {
91              message = NEWLINE_PATTERN.matcher(message).replaceAll(escapeNewLine);
92          }
93          buf.append(message);
94  
95          if (includeNewLine) {
96              buf.append('\n');
97          }
98          return buf.toString();
99      }
100 
101     private synchronized void addDate(final long timestamp, final StringBuilder buf) {
102         final int index = buf.length() + 4;
103         buf.append(dateFormat.format(new Date(timestamp)));
104         //  RFC 3164 says leading space, not leading zero on days 1-9
105         if (buf.charAt(index) == '0') {
106             buf.setCharAt(index, Chars.SPACE);
107         }
108     }
109 
110     /**
111      * Gets this SyslogLayout's content format. Specified by:
112      * <ul>
113      * <li>Key: "structured" Value: "false"</li>
114      * <li>Key: "dateFormat" Value: "MMM dd HH:mm:ss"</li>
115      * <li>Key: "format" Value: "&lt;LEVEL&gt;TIMESTAMP PROP(HOSTNAME) MESSAGE"</li>
116      * <li>Key: "formatType" Value: "logfilepatternreceiver" (format uses the keywords supported by
117      * LogFilePatternReceiver)</li>
118      * </ul>
119      * 
120      * @return Map of content format keys supporting SyslogLayout
121      */
122     @Override
123     public Map<String, String> getContentFormat() {
124         final Map<String, String> result = new HashMap<>();
125         result.put("structured", "false");
126         result.put("formatType", "logfilepatternreceiver");
127         result.put("dateFormat", dateFormat.toPattern());
128         result.put("format", "<LEVEL>TIMESTAMP PROP(HOSTNAME) MESSAGE");
129         return result;
130     }
131 
132     /**
133      * Create a SyslogLayout.
134      * @param facility The Facility is used to try to classify the message.
135      * @param includeNewLine If true a newline will be appended to the result.
136      * @param escapeNL Pattern to use for replacing newlines.
137      * @param charset The character set.
138      * @return A SyslogLayout.
139      */
140     @PluginFactory
141     public static SyslogLayout createLayout(
142             @PluginAttribute(value = "facility", defaultString = "LOCAL0") final Facility facility,
143             @PluginAttribute(value = "newLine", defaultBoolean = false) final boolean includeNewLine,
144             @PluginAttribute("newLineEscape") final String escapeNL,
145             @PluginAttribute(value = "charset", defaultString = "UTF-8") final Charset charset) {
146         return new SyslogLayout(facility, includeNewLine, escapeNL, charset);
147     }
148 }