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