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.nio.charset.StandardCharsets;
021import java.text.SimpleDateFormat;
022import java.util.Date;
023import java.util.HashMap;
024import java.util.Locale;
025import java.util.Map;
026import java.util.regex.Matcher;
027import java.util.regex.Pattern;
028
029import org.apache.logging.log4j.core.Layout;
030import org.apache.logging.log4j.core.LogEvent;
031import org.apache.logging.log4j.core.config.Node;
032import org.apache.logging.log4j.core.config.plugins.Plugin;
033import org.apache.logging.log4j.core.config.plugins.PluginBuilderAttribute;
034import org.apache.logging.log4j.core.config.plugins.PluginBuilderFactory;
035import org.apache.logging.log4j.core.net.Facility;
036import org.apache.logging.log4j.core.net.Priority;
037import org.apache.logging.log4j.core.util.NetUtils;
038import org.apache.logging.log4j.util.Chars;
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    /**
047     * Builds a SyslogLayout.
048     * <p>The main arguments are</p>
049     * <ul>
050     * <li>facility: The Facility is used to try to classify the message.</li>
051     * <li>includeNewLine: If true a newline will be appended to the result.</li>
052     * <li>escapeNL: Pattern to use for replacing newlines.</li>
053     * <li>charset: The character set.</li>
054     * </ul>
055     * @param <B> the builder type
056     */
057    public static class Builder<B extends Builder<B>> extends AbstractStringLayout.Builder<B>
058            implements org.apache.logging.log4j.core.util.Builder<SyslogLayout> {
059
060        public Builder() {
061            super();
062            setCharset(StandardCharsets.UTF_8);
063        }
064
065        @PluginBuilderAttribute
066        private Facility facility = Facility.LOCAL0;
067
068        @PluginBuilderAttribute("newLine")
069        private boolean includeNewLine;
070
071        @PluginBuilderAttribute("newLineEscape")
072        private String escapeNL;
073
074        @Override
075        public SyslogLayout build() {
076            return new SyslogLayout(facility, includeNewLine, escapeNL, getCharset());
077        }
078
079        public Facility getFacility() {
080            return facility;
081        }
082
083        public boolean isIncludeNewLine() {
084            return includeNewLine;
085        }
086
087        public String getEscapeNL() {
088            return escapeNL;
089        }
090
091        public B setFacility(final Facility facility) {
092            this.facility = facility;
093            return asBuilder();
094        }
095
096        public B setIncludeNewLine(final boolean includeNewLine) {
097            this.includeNewLine = includeNewLine;
098            return asBuilder();
099        }
100
101        public B setEscapeNL(final String escapeNL) {
102            this.escapeNL = escapeNL;
103            return asBuilder();
104        }
105
106    }
107
108    @PluginBuilderFactory
109    public static <B extends Builder<B>> B newBuilder() {
110        return new Builder<B>().asBuilder();
111    }
112
113    /**
114     * Match newlines in a platform-independent manner.
115     */
116    public static final Pattern NEWLINE_PATTERN = Pattern.compile("\\r?\\n");
117
118    private final Facility facility;
119    private final boolean includeNewLine;
120    private final String escapeNewLine;
121
122    /**
123     * Date format used if header = true.
124     */
125    private final SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd HH:mm:ss", Locale.ENGLISH);
126
127    /**
128     * Host name used to identify messages from this appender.
129     */
130    private final String localHostname = NetUtils.getLocalHostname();
131
132    protected SyslogLayout(final Facility facility, final boolean includeNL, final String escapeNL, final Charset charset) {
133        super(charset);
134        this.facility = facility;
135        this.includeNewLine = includeNL;
136        this.escapeNewLine = escapeNL == null ? null : Matcher.quoteReplacement(escapeNL);
137    }
138
139    /**
140     * Formats a {@link org.apache.logging.log4j.core.LogEvent} in conformance with the BSD Log record format.
141     *
142     * @param event The LogEvent
143     * @return the event formatted as a String.
144     */
145    @Override
146    public String toSerializable(final LogEvent event) {
147        final StringBuilder buf = getStringBuilder();
148
149        buf.append('<');
150        buf.append(Priority.getPriority(facility, event.getLevel()));
151        buf.append('>');
152        addDate(event.getTimeMillis(), buf);
153        buf.append(Chars.SPACE);
154        buf.append(localHostname);
155        buf.append(Chars.SPACE);
156
157        String message = event.getMessage().getFormattedMessage();
158        if (null != escapeNewLine) {
159            message = NEWLINE_PATTERN.matcher(message).replaceAll(escapeNewLine);
160        }
161        buf.append(message);
162
163        if (includeNewLine) {
164            buf.append('\n');
165        }
166        return buf.toString();
167    }
168
169    private synchronized void addDate(final long timestamp, final StringBuilder buf) {
170        final int index = buf.length() + 4;
171        buf.append(dateFormat.format(new Date(timestamp)));
172        //  RFC 3164 says leading space, not leading zero on days 1-9
173        if (buf.charAt(index) == '0') {
174            buf.setCharAt(index, Chars.SPACE);
175        }
176    }
177
178    /**
179     * Gets this SyslogLayout's content format. Specified by:
180     * <ul>
181     * <li>Key: "structured" Value: "false"</li>
182     * <li>Key: "dateFormat" Value: "MMM dd HH:mm:ss"</li>
183     * <li>Key: "format" Value: "&lt;LEVEL&gt;TIMESTAMP PROP(HOSTNAME) MESSAGE"</li>
184     * <li>Key: "formatType" Value: "logfilepatternreceiver" (format uses the keywords supported by
185     * LogFilePatternReceiver)</li>
186     * </ul>
187     *
188     * @return Map of content format keys supporting SyslogLayout
189     */
190    @Override
191    public Map<String, String> getContentFormat() {
192        final Map<String, String> result = new HashMap<>();
193        result.put("structured", "false");
194        result.put("formatType", "logfilepatternreceiver");
195        result.put("dateFormat", dateFormat.toPattern());
196        result.put("format", "<LEVEL>TIMESTAMP PROP(HOSTNAME) MESSAGE");
197        return result;
198    }
199
200    /**
201     * Creates a SyslogLayout.
202     *
203     * @param facility The Facility is used to try to classify the message.
204     * @param includeNewLine If true a newline will be appended to the result.
205     * @param escapeNL Pattern to use for replacing newlines.
206     * @param charset The character set.
207     * @return A SyslogLayout.
208     * @deprecated Use {@link #newBuilder()}.
209     */
210    @Deprecated
211    public static SyslogLayout createLayout(final Facility facility, final boolean includeNewLine,
212                                            final String escapeNL, final Charset charset) {
213        return new SyslogLayout(facility, includeNewLine, escapeNL, charset);
214    }
215
216    /**
217     * Gets the facility.
218     *
219     * @return the facility
220     */
221    public Facility getFacility() {
222        return facility;
223    }
224}