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.HashMap;
021import java.util.Map;
022
023import org.apache.logging.log4j.core.Filter;
024import org.apache.logging.log4j.core.Layout;
025import org.apache.logging.log4j.core.LogEvent;
026import org.apache.logging.log4j.core.config.Configuration;
027import org.apache.logging.log4j.core.config.plugins.Plugin;
028import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
029import org.apache.logging.log4j.core.config.plugins.PluginConfiguration;
030import org.apache.logging.log4j.core.config.plugins.PluginElement;
031import org.apache.logging.log4j.core.config.plugins.PluginFactory;
032import org.apache.logging.log4j.core.layout.PatternLayout;
033import org.apache.logging.log4j.core.net.Advertiser;
034import org.apache.logging.log4j.core.util.Booleans;
035import org.apache.logging.log4j.core.util.Integers;
036
037/**
038 * File Appender.
039 */
040@Plugin(name = "RandomAccessFile", category = "Core", elementType = "appender", printObject = true)
041public final class RandomAccessFileAppender extends AbstractOutputStreamAppender<RandomAccessFileManager> {
042
043    private final String fileName;
044    private Object advertisement;
045    private final Advertiser advertiser;
046
047    private RandomAccessFileAppender(final String name, final Layout<? extends Serializable> layout, final Filter filter,
048            final RandomAccessFileManager manager, final String filename, final boolean ignoreExceptions,
049            final boolean immediateFlush, final Advertiser advertiser) {
050        super(name, layout, filter, ignoreExceptions, immediateFlush, manager);
051        if (advertiser != null) {
052            final Map<String, String> configuration = new HashMap<String, String>(
053                    layout.getContentFormat());
054            configuration.putAll(manager.getContentFormat());
055            configuration.put("contentType", layout.getContentType());
056            configuration.put("name", name);
057            advertisement = advertiser.advertise(configuration);
058        }
059        this.fileName = filename;
060        this.advertiser = advertiser;
061    }
062
063    @Override
064    public void stop() {
065        super.stop();
066        if (advertiser != null) {
067            advertiser.unadvertise(advertisement);
068        }
069    }
070
071    /**
072     * Write the log entry rolling over the file when required.
073     *
074     * @param event The LogEvent.
075     */
076    @Override
077    public void append(final LogEvent event) {
078
079        // Leverage the nice batching behaviour of async Loggers/Appenders:
080        // we can signal the file manager that it needs to flush the buffer
081        // to disk at the end of a batch.
082        // From a user's point of view, this means that all log events are
083        // _always_ available in the log file, without incurring the overhead
084        // of immediateFlush=true.
085        getManager().setEndOfBatch(event.isEndOfBatch());
086        super.append(event);
087    }
088
089    /**
090     * Returns the file name this appender is associated with.
091     *
092     * @return The File name.
093     */
094    public String getFileName() {
095        return this.fileName;
096    }
097    
098    /**
099     * Returns the size of the file manager's buffer.
100     * @return the buffer size
101     */
102    public int getBufferSize() {
103        return getManager().getBufferSize();
104    }
105
106    // difference from standard File Appender:
107    // locking is not supported and buffering cannot be switched off
108    /**
109     * Create a File Appender.
110     *
111     * @param fileName The name and path of the file.
112     * @param append "True" if the file should be appended to, "false" if it
113     *            should be overwritten. The default is "true".
114     * @param name The name of the Appender.
115     * @param immediateFlush "true" if the contents should be flushed on every
116     *            write, "false" otherwise. The default is "true".
117     * @param bufferSizeStr The buffer size, defaults to {@value RandomAccessFileManager#DEFAULT_BUFFER_SIZE}.
118     * @param ignore If {@code "true"} (default) exceptions encountered when appending events are logged; otherwise
119     *               they are propagated to the caller.
120     * @param layout The layout to use to format the event. If no layout is
121     *            provided the default PatternLayout will be used.
122     * @param filter The filter, if any, to use.
123     * @param advertise "true" if the appender configuration should be
124     *            advertised, "false" otherwise.
125     * @param advertiseURI The advertised URI which can be used to retrieve the
126     *            file contents.
127     * @param config The Configuration.
128     * @return The FileAppender.
129     */
130    @PluginFactory
131    public static RandomAccessFileAppender createAppender(
132            @PluginAttribute("fileName") final String fileName,
133            @PluginAttribute("append") final String append,
134            @PluginAttribute("name") final String name,
135            @PluginAttribute("immediateFlush") final String immediateFlush,
136            @PluginAttribute("bufferSize") final String bufferSizeStr,
137            @PluginAttribute("ignoreExceptions") final String ignore,
138            @PluginElement("Layout") Layout<? extends Serializable> layout,
139            @PluginElement("Filter") final Filter filter,
140            @PluginAttribute("advertise") final String advertise,
141            @PluginAttribute("advertiseURI") final String advertiseURI,
142            @PluginConfiguration final Configuration config) {
143
144        final boolean isAppend = Booleans.parseBoolean(append, true);
145        final boolean isFlush = Booleans.parseBoolean(immediateFlush, true);
146        final boolean ignoreExceptions = Booleans.parseBoolean(ignore, true);
147        final boolean isAdvertise = Boolean.parseBoolean(advertise);
148        final int bufferSize = Integers.parseInt(bufferSizeStr, RandomAccessFileManager.DEFAULT_BUFFER_SIZE);
149
150        if (name == null) {
151            LOGGER.error("No name provided for FileAppender");
152            return null;
153        }
154
155        if (fileName == null) {
156            LOGGER.error("No filename provided for FileAppender with name "
157                    + name);
158            return null;
159        }
160        if (layout == null) {
161            layout = PatternLayout.createDefaultLayout();
162        }
163        final RandomAccessFileManager manager = RandomAccessFileManager.getFileManager(
164                fileName, isAppend, isFlush, bufferSize, advertiseURI, layout
165        );
166        if (manager == null) {
167            return null;
168        }
169
170        return new RandomAccessFileAppender(
171                name, layout, filter, manager, fileName, ignoreExceptions, isFlush,
172                isAdvertise ? config.getAdvertiser() : null
173        );
174    }
175}