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    protected 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     * Instantiate 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 manager.
067     * 
068     * @return the manager.
069     */
070    public M getManager() {
071        return manager;
072    }
073
074    @Override
075    public void start() {
076        if (getLayout() == null) {
077            LOGGER.error("No layout set for the appender named [" + getName() + "].");
078        }
079        if (manager == null) {
080            LOGGER.error("No OutputStreamManager set for the appender named [" + getName() + "].");
081        }
082        super.start();
083    }
084
085    @Override
086    public void stop() {
087        super.stop();
088        manager.release();
089    }
090
091    /**
092     * Actual writing occurs here.
093     * <p>
094     * Most subclasses of <code>AbstractOutputStreamAppender</code> will need to override this method.
095     * </p>
096     * 
097     * @param event The LogEvent.
098     */
099    @Override
100    public void append(final LogEvent event) {
101        readLock.lock();
102        try {
103            final byte[] bytes = getLayout().toByteArray(event);
104            if (bytes.length > 0) {
105                manager.write(bytes);
106                if (this.immediateFlush || event.isEndOfBatch()) {
107                    manager.flush();
108                }
109            }
110        } catch (final AppenderLoggingException ex) {
111            error("Unable to write to stream " + manager.getName() + " for appender " + getName());
112            throw ex;
113        } finally {
114            readLock.unlock();
115        }
116    }
117}