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.IOException;
020import java.io.Writer;
021
022import org.apache.logging.log4j.core.StringLayout;
023
024/**
025 * Manages a Writer so that it can be shared by multiple Appenders and will
026 * allow appenders to reconfigure without requiring a new writer.
027 */
028public class WriterManager extends AbstractManager {
029
030    /**
031     * Creates a Manager.
032     *
033     * @param name The name of the stream to manage.
034     * @param data The data to pass to the Manager.
035     * @param factory The factory to use to create the Manager.
036     * @param <T> The type of the WriterManager.
037     * @return A WriterManager.
038     */
039    public static <T> WriterManager getManager(final String name, final T data,
040                                                 final ManagerFactory<? extends WriterManager, T> factory) {
041        return AbstractManager.getManager(name, factory, data);
042    }
043    protected final StringLayout layout;
044
045    private volatile Writer writer;
046
047    public WriterManager(final Writer writer, final String streamName, final StringLayout layout,
048            final boolean writeHeader) {
049        super(streamName);
050        this.writer = writer;
051        this.layout = layout;
052        if (writeHeader && layout != null) {
053            final byte[] header = layout.getHeader();
054            if (header != null) {
055                try {
056                    this.writer.write(new String(header, layout.getCharset()));
057                } catch (final IOException e) {
058                    logError("Unable to write header", e);
059                }
060            }
061        }
062    }
063
064    protected synchronized void close() {
065        final Writer w = writer; // access volatile field only once per method
066        try {
067            w.close();
068        } catch (final IOException ex) {
069            logError("Unable to close stream", ex);
070        }
071    }
072
073    /**
074     * Flushes any buffers.
075     */
076    public synchronized void flush() {
077        try {
078            writer.flush();
079        } catch (final IOException ex) {
080            final String msg = "Error flushing stream " + getName();
081            throw new AppenderLoggingException(msg, ex);
082        }
083    }
084
085    protected Writer getWriter() {
086        return writer;
087    }
088
089    /**
090     * Returns the status of the stream.
091     * @return true if the stream is open, false if it is not.
092     */
093    public boolean isOpen() {
094        return getCount() > 0;
095    }
096
097    /**
098     * Default hook to write footer during close.
099     */
100    @Override
101    public void releaseSub() {
102        writeFooter();
103        close();
104    }
105
106    protected void setWriter(final Writer writer) {
107        final byte[] header = layout.getHeader();
108        if (header != null) {
109            try {
110                writer.write(new String(header, layout.getCharset()));
111                this.writer = writer; // only update field if writer.write() succeeded
112            } catch (final IOException ioe) {
113                logError("Unable to write header", ioe);
114            }
115        } else {
116            this.writer = writer;
117        }
118    }
119
120    /**
121     * Some output streams synchronize writes while others do not. Synchronizing here insures that
122     * log events won't be intertwined.
123     * @param bytes The serialized Log event.
124     * @param offset The offset into the byte array.
125     * @param length The number of bytes to write.
126     * @throws AppenderLoggingException if an error occurs.
127     */
128    protected synchronized void write(final String str)  {
129        try {
130            writer.write(str);
131        } catch (final IOException ex) {
132            final String msg = "Error writing to stream " + getName();
133            throw new AppenderLoggingException(msg, ex);
134        }
135    }
136
137    /**
138     * Writes the footer.
139     */
140    protected void writeFooter() {
141        if (layout == null) {
142            return;
143        }
144        final byte[] footer = layout.getFooter();
145        if (footer != null && footer.length > 0) {
146            write(new String(footer, layout.getCharset()));
147        }
148    }
149}