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