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.zip.Deflater;
023
024import org.apache.logging.log4j.core.Filter;
025import org.apache.logging.log4j.core.Layout;
026import org.apache.logging.log4j.core.LogEvent;
027import org.apache.logging.log4j.core.appender.rolling.DefaultRolloverStrategy;
028import org.apache.logging.log4j.core.appender.rolling.RollingFileManager;
029import org.apache.logging.log4j.core.appender.rolling.RollingRandomAccessFileManager;
030import org.apache.logging.log4j.core.appender.rolling.RolloverStrategy;
031import org.apache.logging.log4j.core.appender.rolling.TriggeringPolicy;
032import org.apache.logging.log4j.core.config.Configuration;
033import org.apache.logging.log4j.core.config.plugins.Plugin;
034import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
035import org.apache.logging.log4j.core.config.plugins.PluginConfiguration;
036import org.apache.logging.log4j.core.config.plugins.PluginElement;
037import org.apache.logging.log4j.core.config.plugins.PluginFactory;
038import org.apache.logging.log4j.core.layout.PatternLayout;
039import org.apache.logging.log4j.core.net.Advertiser;
040import org.apache.logging.log4j.core.util.Booleans;
041import org.apache.logging.log4j.core.util.Integers;
042
043/**
044 * An appender that writes to random access files and can roll over at
045 * intervals.
046 */
047@Plugin(name = "RollingRandomAccessFile", category = "Core", elementType = "appender", printObject = true)
048public final class RollingRandomAccessFileAppender extends AbstractOutputStreamAppender<RollingFileManager> {
049
050    private static final long serialVersionUID = 1L;
051
052    private final String fileName;
053    private final String filePattern;
054    private Object advertisement;
055    private final Advertiser advertiser;
056
057    private RollingRandomAccessFileAppender(final String name, final Layout<? extends Serializable> layout,
058            final Filter filter, final RollingFileManager manager, final String fileName,
059            final String filePattern, final boolean ignoreExceptions,
060            final boolean immediateFlush, final int bufferSize, final Advertiser advertiser) {
061        super(name, layout, filter, ignoreExceptions, immediateFlush, manager);
062        if (advertiser != null) {
063            final Map<String, String> configuration = new HashMap<>(layout.getContentFormat());
064            configuration.put("contentType", layout.getContentType());
065            configuration.put("name", name);
066            advertisement = advertiser.advertise(configuration);
067        }
068        this.fileName = fileName;
069        this.filePattern = filePattern;
070        this.advertiser = advertiser;
071    }
072
073    @Override
074    public void stop() {
075        super.stop();
076        if (advertiser != null) {
077            advertiser.unadvertise(advertisement);
078        }
079    }
080
081    /**
082     * Write the log entry rolling over the file when required.
083     *
084     * @param event The LogEvent.
085     */
086    @Override
087    public void append(final LogEvent event) {
088        final RollingRandomAccessFileManager manager = (RollingRandomAccessFileManager) getManager();
089        manager.checkRollover(event);
090
091        // Leverage the nice batching behaviour of async Loggers/Appenders:
092        // we can signal the file manager that it needs to flush the buffer
093        // to disk at the end of a batch.
094        // From a user's point of view, this means that all log events are
095        // _always_ available in the log file, without incurring the overhead
096        // of immediateFlush=true.
097        manager.setEndOfBatch(event.isEndOfBatch());
098        super.append(event);
099    }
100
101    /**
102     * Returns the File name for the Appender.
103     *
104     * @return The file name.
105     */
106    public String getFileName() {
107        return fileName;
108    }
109
110    /**
111     * Returns the file pattern used when rolling over.
112     *
113     * @return The file pattern.
114     */
115    public String getFilePattern() {
116        return filePattern;
117    }
118    
119    /**
120     * Returns the size of the file manager's buffer.
121     * @return the buffer size
122     */
123    public int getBufferSize() {
124        return getManager().getBufferSize();
125    }
126
127    /**
128     * Create a RollingRandomAccessFileAppender.
129     *
130     * @param fileName The name of the file that is actively written to.
131     *            (required).
132     * @param filePattern The pattern of the file name to use on rollover.
133     *            (required).
134     * @param append If true, events are appended to the file. If false, the
135     *            file is overwritten when opened. Defaults to "true"
136     * @param name The name of the Appender (required).
137     * @param immediateFlush When true, events are immediately flushed. Defaults
138     *            to "true".
139     * @param bufferSizeStr The buffer size, defaults to {@value RollingRandomAccessFileManager#DEFAULT_BUFFER_SIZE}.
140     * @param policy The triggering policy. (required).
141     * @param strategy The rollover strategy. Defaults to
142     *            DefaultRolloverStrategy.
143     * @param layout The layout to use (defaults to the default PatternLayout).
144     * @param filter The Filter or null.
145     * @param ignore If {@code "true"} (default) exceptions encountered when appending events are logged; otherwise
146     *               they are propagated to the caller.
147     * @param advertise "true" if the appender configuration should be
148     *            advertised, "false" otherwise.
149     * @param advertiseURI The advertised URI which can be used to retrieve the
150     *            file contents.
151     * @param config The Configuration.
152     * @return A RollingRandomAccessFileAppender.
153     */
154    @PluginFactory
155    public static RollingRandomAccessFileAppender createAppender(
156            @PluginAttribute("fileName") final String fileName,
157            @PluginAttribute("filePattern") final String filePattern,
158            @PluginAttribute("append") final String append,
159            @PluginAttribute("name") final String name,
160            @PluginAttribute("immediateFlush") final String immediateFlush,
161            @PluginAttribute("bufferSize") final String bufferSizeStr,
162            @PluginElement("Policy") final TriggeringPolicy policy,
163            @PluginElement("Strategy") RolloverStrategy strategy,
164            @PluginElement("Layout") Layout<? extends Serializable> layout,
165            @PluginElement("Filter") final Filter filter,
166            @PluginAttribute("ignoreExceptions") final String ignore,
167            @PluginAttribute("advertise") final String advertise,
168            @PluginAttribute("advertiseURI") final String advertiseURI,
169            @PluginConfiguration final Configuration config) {
170
171        final boolean isAppend = Booleans.parseBoolean(append, true);
172        final boolean ignoreExceptions = Booleans.parseBoolean(ignore, true);
173        final boolean isFlush = Booleans.parseBoolean(immediateFlush, true);
174        final boolean isAdvertise = Boolean.parseBoolean(advertise);
175        final int bufferSize = Integers.parseInt(bufferSizeStr, RollingRandomAccessFileManager.DEFAULT_BUFFER_SIZE);
176
177        if (name == null) {
178            LOGGER.error("No name provided for FileAppender");
179            return null;
180        }
181
182        if (fileName == null) {
183            LOGGER.error("No filename was provided for FileAppender with name " + name);
184            return null;
185        }
186
187        if (filePattern == null) {
188            LOGGER.error("No filename pattern provided for FileAppender with name " + name);
189            return null;
190        }
191
192        if (policy == null) {
193            LOGGER.error("A TriggeringPolicy must be provided");
194            return null;
195        }
196
197        if (strategy == null) {
198            strategy = DefaultRolloverStrategy.createStrategy(null, null, null,
199                    String.valueOf(Deflater.DEFAULT_COMPRESSION), null, true, config);
200        }
201
202        if (layout == null) {
203            layout = PatternLayout.createDefaultLayout();
204        }
205
206        final RollingRandomAccessFileManager manager = RollingRandomAccessFileManager.getRollingRandomAccessFileManager(
207                fileName, filePattern, isAppend, isFlush, bufferSize, policy, strategy, advertiseURI, layout);
208        if (manager == null) {
209            return null;
210        }
211
212        return new RollingRandomAccessFileAppender(name, layout, filter, manager,
213                fileName, filePattern, ignoreExceptions, isFlush, bufferSize,
214                isAdvertise ? config.getAdvertiser() : null);
215    }
216}