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.LogEvent;
029import org.apache.logging.log4j.core.config.plugins.Plugin;
030import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
031import org.apache.logging.log4j.core.config.plugins.PluginFactory;
032import org.apache.logging.log4j.core.net.Facility;
033import org.apache.logging.log4j.core.net.Priority;
034import org.apache.logging.log4j.core.util.NetUtils;
035
036
037/**
038 * Formats a log event as a BSD Log record.
039 */
040@Plugin(name = "SyslogLayout", category = "Core", elementType = "layout", printObject = true)
041public final class SyslogLayout extends AbstractStringLayout {
042    /**
043     * Match newlines in a platform-independent manner.
044     */
045    public static final Pattern NEWLINE_PATTERN = Pattern.compile("\\r?\\n");
046
047    private final Facility facility;
048    private final boolean includeNewLine;
049    private final String escapeNewLine;
050
051    /**
052     * Date format used if header = true.
053     */
054    private final SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd HH:mm:ss ", Locale.ENGLISH);
055    /**
056     * Host name used to identify messages from this appender.
057     */
058    private final String localHostname = NetUtils.getLocalHostname();
059
060
061
062    protected SyslogLayout(final Facility facility, final boolean includeNL, final String escapeNL, final Charset charset) {
063        super(charset);
064        this.facility = facility;
065        this.includeNewLine = includeNL;
066        this.escapeNewLine = escapeNL == null ? null : Matcher.quoteReplacement(escapeNL);
067    }
068
069    /**
070     * Formats a {@link org.apache.logging.log4j.core.LogEvent} in conformance with the BSD Log record format.
071     *
072     * @param event The LogEvent
073     * @return the event formatted as a String.
074     */
075    @Override
076    public String toSerializable(final LogEvent event) {
077        final StringBuilder buf = new StringBuilder();
078
079        buf.append('<');
080        buf.append(Priority.getPriority(facility, event.getLevel()));
081        buf.append('>');
082        addDate(event.getTimeMillis(), buf);
083        buf.append(' ');
084        buf.append(localHostname);
085        buf.append(' ');
086
087        String message = event.getMessage().getFormattedMessage();
088        if (null != escapeNewLine) {
089            message = NEWLINE_PATTERN.matcher(message).replaceAll(escapeNewLine);
090        }
091        buf.append(message);
092
093        if (includeNewLine) {
094            buf.append('\n');
095        }
096        return buf.toString();
097    }
098
099    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}