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.Core;
026import org.apache.logging.log4j.core.Filter;
027import org.apache.logging.log4j.core.Layout;
028import org.apache.logging.log4j.core.LogEvent;
029import org.apache.logging.log4j.core.config.Configuration;
030import org.apache.logging.log4j.core.config.Property;
031import org.apache.logging.log4j.core.config.plugins.Plugin;
032import org.apache.logging.log4j.core.config.plugins.PluginBuilderAttribute;
033import org.apache.logging.log4j.core.config.plugins.PluginBuilderFactory;
034import org.apache.logging.log4j.core.net.Advertiser;
035import org.apache.logging.log4j.core.util.Booleans;
036import org.apache.logging.log4j.core.util.Integers;
037
038/**
039 * File Appender.
040 */
041@Plugin(name = "RandomAccessFile", category = Core.CATEGORY_NAME, elementType = Appender.ELEMENT_TYPE, printObject = true)
042public final class RandomAccessFileAppender extends AbstractOutputStreamAppender<RandomAccessFileManager> {
043
044    /**
045     * Builds RandomAccessFileAppender instances.
046     *
047     * @param <B>
048     *            The type to build
049     */
050    public static class Builder<B extends Builder<B>> extends AbstractOutputStreamAppender.Builder<B>
051            implements org.apache.logging.log4j.core.util.Builder<RandomAccessFileAppender> {
052
053        @PluginBuilderAttribute("fileName")
054        private String fileName;
055
056        @PluginBuilderAttribute("append")
057        private boolean append = true;
058
059        @PluginBuilderAttribute("advertise")
060        private boolean advertise;
061
062        @PluginBuilderAttribute("advertiseURI")
063        private String advertiseURI;
064
065        public Builder() {
066            this.withBufferSize(RandomAccessFileManager.DEFAULT_BUFFER_SIZE);
067        }
068
069        @Override
070        public RandomAccessFileAppender build() {
071            final String name = getName();
072            if (name == null) {
073                LOGGER.error("No name provided for RandomAccessFileAppender");
074                return null;
075            }
076
077            if (fileName == null) {
078                LOGGER.error("No filename provided for RandomAccessFileAppender with name {}", name);
079                return null;
080            }
081            final Layout<? extends Serializable> layout = getOrCreateLayout();
082            final boolean immediateFlush = isImmediateFlush();
083            final RandomAccessFileManager manager = RandomAccessFileManager.getFileManager(fileName, append,
084                    immediateFlush, getBufferSize(), advertiseURI, layout, null);
085            if (manager == null) {
086                return null;
087            }
088
089            return new RandomAccessFileAppender(name, layout, getFilter(), manager, fileName, isIgnoreExceptions(),
090                    immediateFlush, advertise ? getConfiguration().getAdvertiser() : null, getPropertyArray());
091        }
092
093        public B setFileName(final String fileName) {
094            this.fileName = fileName;
095            return asBuilder();
096        }
097
098        public B setAppend(final boolean append) {
099            this.append = append;
100            return asBuilder();
101        }
102
103        public B setAdvertise(final boolean advertise) {
104            this.advertise = advertise;
105            return asBuilder();
106        }
107
108        public B setAdvertiseURI(final String advertiseURI) {
109            this.advertiseURI = advertiseURI;
110            return asBuilder();
111        }
112
113    }
114
115    private final String fileName;
116    private Object advertisement;
117    private final Advertiser advertiser;
118
119    private RandomAccessFileAppender(final String name, final Layout<? extends Serializable> layout,
120            final Filter filter, final RandomAccessFileManager manager, final String filename,
121            final boolean ignoreExceptions, final boolean immediateFlush, final Advertiser advertiser,
122            final Property[] properties) {
123
124        super(name, layout, filter, ignoreExceptions, immediateFlush, properties, manager);
125        if (advertiser != null) {
126            final Map<String, String> configuration = new HashMap<>(
127                    layout.getContentFormat());
128            configuration.putAll(manager.getContentFormat());
129            configuration.put("contentType", layout.getContentType());
130            configuration.put("name", name);
131            advertisement = advertiser.advertise(configuration);
132        }
133        this.fileName = filename;
134        this.advertiser = advertiser;
135    }
136
137    @Override
138    public boolean stop(final long timeout, final TimeUnit timeUnit) {
139        setStopping();
140        super.stop(timeout, timeUnit, false);
141        if (advertiser != null) {
142            advertiser.unadvertise(advertisement);
143        }
144        setStopped();
145        return true;
146    }
147
148    /**
149     * Returns the file name this appender is associated with.
150     *
151     * @return The File name.
152     */
153    public String getFileName() {
154        return this.fileName;
155    }
156
157    /**
158     * Returns the size of the file manager's buffer.
159     * @return the buffer size
160     */
161    public int getBufferSize() {
162        return getManager().getBufferSize();
163    }
164
165    // difference from standard File Appender:
166    // locking is not supported and buffering cannot be switched off
167    /**
168     * Create a File Appender.
169     *
170     * @param fileName The name and path of the file.
171     * @param append "True" if the file should be appended to, "false" if it
172     *            should be overwritten. The default is "true".
173     * @param name The name of the Appender.
174     * @param immediateFlush "true" if the contents should be flushed on every
175     *            write, "false" otherwise. The default is "true".
176     * @param bufferSizeStr The buffer size, defaults to {@value RandomAccessFileManager#DEFAULT_BUFFER_SIZE}.
177     * @param ignore If {@code "true"} (default) exceptions encountered when appending events are logged; otherwise
178     *               they are propagated to the caller.
179     * @param layout The layout to use to format the event. If no layout is
180     *            provided the default PatternLayout will be used.
181     * @param filter The filter, if any, to use.
182     * @param advertise "true" if the appender configuration should be
183     *            advertised, "false" otherwise.
184     * @param advertiseURI The advertised URI which can be used to retrieve the
185     *            file contents.
186     * @param configuration The Configuration.
187     * @return The FileAppender.
188     * @deprecated Use {@link #newBuilder()}.
189     */
190    @Deprecated
191    public static <B extends Builder<B>> RandomAccessFileAppender createAppender(
192            final String fileName,
193            final String append,
194            final String name,
195            final String immediateFlush,
196            final String bufferSizeStr,
197            final String ignore,
198            final Layout<? extends Serializable> layout,
199            final Filter filter,
200            final String advertise,
201            final String advertiseURI,
202            final Configuration configuration) {
203
204        final boolean isAppend = Booleans.parseBoolean(append, true);
205        final boolean isFlush = Booleans.parseBoolean(immediateFlush, true);
206        final boolean ignoreExceptions = Booleans.parseBoolean(ignore, true);
207        final boolean isAdvertise = Boolean.parseBoolean(advertise);
208        final int bufferSize = Integers.parseInt(bufferSizeStr, RandomAccessFileManager.DEFAULT_BUFFER_SIZE);
209
210        return RandomAccessFileAppender.<B>newBuilder()
211        .setAdvertise(isAdvertise)
212        .setAdvertiseURI(advertiseURI)
213        .setAppend(isAppend)
214        .withBufferSize(bufferSize)
215        .setConfiguration(configuration)
216        .setFileName(fileName).setFilter(filter).setIgnoreExceptions(ignoreExceptions)
217            .withImmediateFlush(isFlush).setLayout(layout).setName(name)
218            .build();
219    }
220
221    /**
222     * Creates a builder for a RandomAccessFileAppender.
223     * @return a builder for a RandomAccessFileAppender.
224     */
225    @PluginBuilderFactory
226    public static <B extends Builder<B>> B newBuilder() {
227        return new Builder<B>().asBuilder();
228    }
229
230}