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