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