001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache license, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the license for the specific language governing permissions and
015 * limitations under the license.
016 */
017package org.apache.logging.log4j.core.layout;
018
019import java.nio.charset.Charset;
020import java.text.SimpleDateFormat;
021import java.util.Date;
022import java.util.HashMap;
023import java.util.Locale;
024import java.util.Map;
025import java.util.regex.Matcher;
026import java.util.regex.Pattern;
027
028import org.apache.logging.log4j.core.Layout;
029import org.apache.logging.log4j.core.LogEvent;
030import org.apache.logging.log4j.core.config.Node;
031import org.apache.logging.log4j.core.config.plugins.Plugin;
032import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
033import org.apache.logging.log4j.core.config.plugins.PluginFactory;
034import org.apache.logging.log4j.core.net.Facility;
035import org.apache.logging.log4j.core.net.Priority;
036import org.apache.logging.log4j.core.util.NetUtils;
037import org.apache.logging.log4j.util.Chars;
038
039
040/**
041 * Formats a log event as a BSD Log record.
042 */
043@Plugin(name = "SyslogLayout", category = Node.CATEGORY, elementType = Layout.ELEMENT_TYPE, printObject = true)
044public final class SyslogLayout extends AbstractStringLayout {
045
046    private static final long serialVersionUID = 1L;
047
048    /**
049     * Match newlines in a platform-independent manner.
050     */
051    public static final Pattern NEWLINE_PATTERN = Pattern.compile("\\r?\\n");
052
053    private final Facility facility;
054    private final boolean includeNewLine;
055    private final String escapeNewLine;
056
057    /**
058     * Date format used if header = true.
059     */
060    private final SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd HH:mm:ss", Locale.ENGLISH);
061    /**
062     * Host name used to identify messages from this appender.
063     */
064    private final String localHostname = NetUtils.getLocalHostname();
065
066    protected SyslogLayout(final Facility facility, final boolean includeNL, final String escapeNL, final Charset charset) {
067        super(charset);
068        this.facility = facility;
069        this.includeNewLine = includeNL;
070        this.escapeNewLine = escapeNL == null ? null : Matcher.quoteReplacement(escapeNL);
071    }
072
073    /**
074     * Formats a {@link org.apache.logging.log4j.core.LogEvent} in conformance with the BSD Log record format.
075     *
076     * @param event The LogEvent
077     * @return the event formatted as a String.
078     */
079    @Override
080    public String toSerializable(final LogEvent event) {
081        final StringBuilder buf = new StringBuilder();
082
083        buf.append('<');
084        buf.append(Priority.getPriority(facility, event.getLevel()));
085        buf.append('>');
086        addDate(event.getTimeMillis(), buf);
087        buf.append(Chars.SPACE);
088        buf.append(localHostname);
089        buf.append(Chars.SPACE);
090
091        String message = event.getMessage().getFormattedMessage();
092        if (null != escapeNewLine) {
093            message = NEWLINE_PATTERN.matcher(message).replaceAll(escapeNewLine);
094        }
095        buf.append(message);
096
097        if (includeNewLine) {
098            buf.append('\n');
099        }
100        return buf.toString();
101    }
102
103    private synchronized void addDate(final long timestamp, final StringBuilder buf) {
104        final int index = buf.length() + 4;
105        buf.append(dateFormat.format(new Date(timestamp)));
106        //  RFC 3164 says leading space, not leading zero on days 1-9
107        if (buf.charAt(index) == '0') {
108            buf.setCharAt(index, Chars.SPACE);
109        }
110    }
111
112    /**
113     * Gets this SyslogLayout's content format. Specified by:
114     * <ul>
115     * <li>Key: "structured" Value: "false"</li>
116     * <li>Key: "dateFormat" Value: "MMM dd HH:mm:ss"</li>
117     * <li>Key: "format" Value: "&lt;LEVEL&gt;TIMESTAMP PROP(HOSTNAME) MESSAGE"</li>
118     * <li>Key: "formatType" Value: "logfilepatternreceiver" (format uses the keywords supported by
119     * LogFilePatternReceiver)</li>
120     * </ul>
121     * 
122     * @return Map of content format keys supporting SyslogLayout
123     */
124    @Override
125    public Map<String, String> getContentFormat() {
126        final Map<String, String> result = new HashMap<String, String>();
127        result.put("structured", "false");
128        result.put("formatType", "logfilepatternreceiver");
129        result.put("dateFormat", dateFormat.toPattern());
130        result.put("format", "<LEVEL>TIMESTAMP PROP(HOSTNAME) MESSAGE");
131        return result;
132    }
133
134    /**
135     * Create a SyslogLayout.
136     * @param facility The Facility is used to try to classify the message.
137     * @param includeNewLine If true a newline will be appended to the result.
138     * @param escapeNL Pattern to use for replacing newlines.
139     * @param charset The character set.
140     * @return A SyslogLayout.
141     */
142    @PluginFactory
143    public static SyslogLayout createLayout(
144            @PluginAttribute(value = "facility", defaultString = "LOCAL0") final Facility facility,
145            @PluginAttribute(value = "newLine", defaultBoolean = false) final boolean includeNewLine,
146            @PluginAttribute("newLineEscape") final String escapeNL,
147            @PluginAttribute(value = "charset", defaultString = "UTF-8") final Charset charset) {
148        return new SyslogLayout(facility, includeNewLine, escapeNL, charset);
149    }
150}