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.appender;
018
019import java.io.Serializable;
020import java.util.concurrent.locks.Lock;
021import java.util.concurrent.locks.ReadWriteLock;
022import java.util.concurrent.locks.ReentrantReadWriteLock;
023
024import org.apache.logging.log4j.core.Filter;
025import org.apache.logging.log4j.core.Layout;
026import org.apache.logging.log4j.core.LogEvent;
027
028/**
029 * Appends log events as bytes to a byte output stream. The stream encoding is defined in the layout.
030 * 
031 * @param <M> The kind of {@link OutputStreamManager} under management
032 */
033public abstract class AbstractOutputStreamAppender<M extends OutputStreamManager> extends AbstractAppender {
034
035    private static final long serialVersionUID = 1L;
036
037    /**
038     * Immediate flush means that the underlying writer or output stream will be flushed at the end of each append
039     * operation. Immediate flush is slower but ensures that each append request is actually written. If
040     * <code>immediateFlush</code> is set to {@code false}, then there is a good chance that the last few logs events
041     * are not actually written to persistent media if and when the application crashes.
042     */
043    private final boolean immediateFlush;
044
045    private final M manager;
046
047    private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
048    private final Lock readLock = rwLock.readLock();
049
050    /**
051     * Instantiates a WriterAppender and set the output destination to a new {@link java.io.OutputStreamWriter}
052     * initialized with <code>os</code> as its {@link java.io.OutputStream}.
053     * 
054     * @param name The name of the Appender.
055     * @param layout The layout to format the message.
056     * @param manager The OutputStreamManager.
057     */
058    protected AbstractOutputStreamAppender(final String name, final Layout<? extends Serializable> layout,
059            final Filter filter, final boolean ignoreExceptions, final boolean immediateFlush, final M manager) {
060        super(name, filter, layout, ignoreExceptions);
061        this.manager = manager;
062        this.immediateFlush = immediateFlush;
063    }
064
065    /**
066     * Gets the immediate flush setting.
067     * 
068     * @return immediate flush.
069     */
070    public boolean getImmediateFlush() {
071        return immediateFlush;
072    }
073
074    /**
075     * Gets the manager.
076     * 
077     * @return the manager.
078     */
079    public M getManager() {
080        return manager;
081    }
082
083    @Override
084    public void start() {
085        if (getLayout() == null) {
086            LOGGER.error("No layout set for the appender named [" + getName() + "].");
087        }
088        if (manager == null) {
089            LOGGER.error("No OutputStreamManager set for the appender named [" + getName() + "].");
090        }
091        super.start();
092    }
093
094    @Override
095    public void stop() {
096        super.stop();
097        manager.release();
098    }
099
100    /**
101     * Actual writing occurs here.
102     * <p>
103     * Most subclasses of <code>AbstractOutputStreamAppender</code> will need to override this method.
104     * </p>
105     * 
106     * @param event The LogEvent.
107     */
108    @Override
109    public void append(final LogEvent event) {
110        readLock.lock();
111        try {
112            final byte[] bytes = getLayout().toByteArray(event);
113            if (bytes.length > 0) {
114                manager.write(bytes);
115                if (this.immediateFlush || event.isEndOfBatch()) {
116                    manager.flush();
117                }
118            }
119        } catch (final AppenderLoggingException ex) {
120            error("Unable to write to stream " + manager.getName() + " for appender " + getName());
121            throw ex;
122        } finally {
123            readLock.unlock();
124        }
125    }
126
127}