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.io.Serializable;
020import java.util.HashMap;
021import java.util.Map;
022
023import org.apache.logging.log4j.Logger;
024import org.apache.logging.log4j.core.Layout;
025import org.apache.logging.log4j.core.LogEvent;
026import org.apache.logging.log4j.core.config.Configuration;
027import org.apache.logging.log4j.core.config.plugins.PluginBuilderAttribute;
028import org.apache.logging.log4j.core.config.plugins.PluginConfiguration;
029import org.apache.logging.log4j.status.StatusLogger;
030
031/**
032 * Abstract base class for Layouts.
033 *
034 * @param <T>
035 *            The Class that the Layout will format the LogEvent into.
036 */
037public abstract class AbstractLayout<T extends Serializable> implements Layout<T> {
038
039    /**
040     * Subclasses can extend this abstract Builder.
041     *
042     * @param <B> The type to build.
043     */
044    public abstract static class Builder<B extends Builder<B>> {
045
046        @PluginConfiguration
047        private Configuration configuration;
048
049        @PluginBuilderAttribute
050        private byte[] footer;
051
052        @PluginBuilderAttribute
053        private byte[] header;
054
055        @SuppressWarnings("unchecked")
056        public B asBuilder() {
057            return (B) this;
058        }
059
060        public Configuration getConfiguration() {
061            return configuration;
062        }
063
064        public byte[] getFooter() {
065            return footer;
066        }
067
068        public byte[] getHeader() {
069            return header;
070        }
071
072        public B setConfiguration(final Configuration configuration) {
073            this.configuration = configuration;
074            return asBuilder();
075        }
076
077        public B setFooter(final byte[] footer) {
078            this.footer = footer;
079            return asBuilder();
080        }
081
082        public B setHeader(final byte[] header) {
083            this.header = header;
084            return asBuilder();
085        }
086
087    }
088
089    /**
090     * Allow subclasses access to the status logger without creating another instance.
091     */
092    protected static final Logger LOGGER = StatusLogger.getLogger();
093
094    /**
095     * The current Configuration.
096     */
097    protected final Configuration configuration;
098
099    /**
100     * The number of events successfully processed by this layout.
101     */
102    protected long eventCount;
103
104    /**
105     * The footer to add when the stream is closed. May be null.
106     */
107    protected final byte[] footer;
108
109    /**
110     * The header to include when the stream is opened. May be null.
111     */
112    protected final byte[] header;
113
114    /**
115     * Constructs a layout with an optional header and footer.
116     *
117     * @param header
118     *            The header to include when the stream is opened. May be null.
119     * @param footer
120     *            The footer to add when the stream is closed. May be null.
121     * @deprecated Use {@link #AbstractLayout(Configuration, byte[], byte[])}
122     */
123    @Deprecated
124    public AbstractLayout(final byte[] header, final byte[] footer) {
125        this(null, header, footer);
126    }
127
128    /**
129     * Constructs a layout with an optional header and footer.
130     *
131     * @param configuration
132     *            The configuration
133     * @param header
134     *            The header to include when the stream is opened. May be null.
135     * @param footer
136     *            The footer to add when the stream is closed. May be null.
137     */
138    public AbstractLayout(final Configuration configuration, final byte[] header, final byte[] footer) {
139        this.configuration = configuration;
140        this.header = header;
141        this.footer = footer;
142    }
143
144    public Configuration getConfiguration() {
145        return configuration;
146    }
147
148    @Override
149    public Map<String, String> getContentFormat() {
150        return new HashMap<>();
151    }
152
153    /**
154     * Returns the footer, if one is available.
155     *
156     * @return A byte array containing the footer.
157     */
158    @Override
159    public byte[] getFooter() {
160        return footer;
161    }
162
163    /**
164     * Returns the header, if one is available.
165     *
166     * @return A byte array containing the header.
167     */
168    @Override
169    public byte[] getHeader() {
170        return header;
171    }
172
173    protected void markEvent() {
174        eventCount++;
175    }
176
177    /**
178     * Encodes the specified source LogEvent to some binary representation and writes the result to the specified
179     * destination.
180     * <p>
181     * The default implementation of this method delegates to the {@link #toByteArray(LogEvent)} method which allocates
182     * temporary objects.
183     * </p><p>
184     * Subclasses can override this method to provide a garbage-free implementation. For text-based layouts,
185     * {@code AbstractStringLayout} provides various convenience methods to help with this:
186     * </p>
187     * <pre>@Plugin(name = "MyLayout", category = Node.CATEGORY, elementType = Layout.ELEMENT_TYPE, printObject = true)
188     * public final class MyLayout extends AbstractStringLayout {
189     *     @Override
190     *     public void encode(LogEvent event, ByteBufferDestination destination) {
191     *         StringBuilder text = getStringBuilder();
192     *         convertLogEventToText(event, text);
193     *         getStringBuilderEncoder().encode(text, destination);
194     *     }
195     *
196     *     private void convertLogEventToText(LogEvent event, StringBuilder destination) {
197     *         ... // append a text representation of the log event to the StringBuilder
198     *     }
199     * }
200     * </pre>
201     *
202     * @param event the LogEvent to encode.
203     * @param destination holds the ByteBuffer to write into.
204     * @see AbstractStringLayout#getStringBuilder()
205     * @see AbstractStringLayout#getStringBuilderEncoder()
206     */
207    @Override
208    public void encode(final LogEvent event, final ByteBufferDestination destination) {
209        final byte[] data = toByteArray(event);
210        destination.writeBytes(data, 0, data.length);
211    }
212}