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