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