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