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