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