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.config.Configuration;
026import org.apache.logging.log4j.core.config.plugins.Plugin;
027import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
028import org.apache.logging.log4j.core.config.plugins.PluginConfiguration;
029import org.apache.logging.log4j.core.config.plugins.PluginElement;
030import org.apache.logging.log4j.core.config.plugins.PluginFactory;
031import org.apache.logging.log4j.core.layout.PatternLayout;
032import org.apache.logging.log4j.core.net.Advertiser;
033import org.apache.logging.log4j.core.util.Booleans;
034import org.apache.logging.log4j.core.util.Integers;
035
036/**
037 * File Appender.
038 */
039@Plugin(name = "File", category = "Core", elementType = "appender", printObject = true)
040public final class FileAppender extends AbstractOutputStreamAppender<FileManager> {
041
042    private static final long serialVersionUID = 1L;
043    private static final int DEFAULT_BUFFER_SIZE = 8192;
044    private final String fileName;
045    private final Advertiser advertiser;
046    private Object advertisement;
047
048    private FileAppender(final String name, final Layout<? extends Serializable> layout, final Filter filter,
049            final FileManager manager, final String filename, final boolean ignoreExceptions,
050            final boolean immediateFlush, final Advertiser advertiser) {
051        
052        super(name, layout, filter, ignoreExceptions, immediateFlush, manager);
053        if (advertiser != null) {
054            final Map<String, String> configuration = new HashMap<>(layout.getContentFormat());
055            configuration.putAll(manager.getContentFormat());
056            configuration.put("contentType", layout.getContentType());
057            configuration.put("name", name);
058            advertisement = advertiser.advertise(configuration);
059        }
060        this.fileName = filename;
061        this.advertiser = advertiser;
062    }
063
064    @Override
065    public void stop() {
066        super.stop();
067        if (advertiser != null) {
068            advertiser.unadvertise(advertisement);
069        }
070    }
071
072    /**
073     * Returns the file name this appender is associated with.
074     * @return The File name.
075     */
076    public String getFileName() {
077        return this.fileName;
078    }
079
080    /**
081     * Create a File Appender.
082     * @param fileName The name and path of the file.
083     * @param append "True" if the file should be appended to, "false" if it should be overwritten.
084     * The default is "true".
085     * @param locking "True" if the file should be locked. The default is "false".
086     * @param name The name of the Appender.
087     * @param immediateFlush "true" if the contents should be flushed on every write, "false" otherwise. The default
088     * is "true".
089     * @param ignore If {@code "true"} (default) exceptions encountered when appending events are logged; otherwise
090     *               they are propagated to the caller.
091     * @param bufferedIo "true" if I/O should be buffered, "false" otherwise. The default is "true".
092     * @param bufferSizeStr buffer size for buffered IO (default is 8192).
093     * @param layout The layout to use to format the event. If no layout is provided the default PatternLayout
094     * will be used.
095     * @param filter The filter, if any, to use.
096     * @param advertise "true" if the appender configuration should be advertised, "false" otherwise.
097     * @param advertiseUri The advertised URI which can be used to retrieve the file contents.
098     * @param config The Configuration
099     * @return The FileAppender.
100     */
101    @PluginFactory
102    public static FileAppender createAppender(
103            // @formatter:off
104            @PluginAttribute("fileName") final String fileName,
105            @PluginAttribute("append") final String append,
106            @PluginAttribute("locking") final String locking,
107            @PluginAttribute("name") final String name,
108            @PluginAttribute("immediateFlush") final String immediateFlush,
109            @PluginAttribute("ignoreExceptions") final String ignore,
110            @PluginAttribute("bufferedIo") final String bufferedIo,
111            @PluginAttribute("bufferSize") final String bufferSizeStr,
112            @PluginElement("Layout") Layout<? extends Serializable> layout,
113            @PluginElement("Filter") final Filter filter,
114            @PluginAttribute("advertise") final String advertise,
115            @PluginAttribute("advertiseUri") final String advertiseUri,
116            @PluginConfiguration final Configuration config) {
117        // @formatter:on
118        final boolean isAppend = Booleans.parseBoolean(append, true);
119        final boolean isLocking = Boolean.parseBoolean(locking);
120        boolean isBuffered = Booleans.parseBoolean(bufferedIo, true);
121        final boolean isAdvertise = Boolean.parseBoolean(advertise);
122        if (isLocking && isBuffered) {
123            if (bufferedIo != null) {
124                LOGGER.warn("Locking and buffering are mutually exclusive. No buffering will occur for " + fileName);
125            }
126            isBuffered = false;
127        }
128        final int bufferSize = Integers.parseInt(bufferSizeStr, DEFAULT_BUFFER_SIZE);
129        if (!isBuffered && bufferSize > 0) {
130            LOGGER.warn("The bufferSize is set to {} but bufferedIO is not true: {}", bufferSize, bufferedIo);
131        }
132        final boolean isFlush = Booleans.parseBoolean(immediateFlush, true);
133        final boolean ignoreExceptions = Booleans.parseBoolean(ignore, true);
134
135        if (name == null) {
136            LOGGER.error("No name provided for FileAppender");
137            return null;
138        }
139
140        if (fileName == null) {
141            LOGGER.error("No filename provided for FileAppender with name "  + name);
142            return null;
143        }
144        if (layout == null) {
145            layout = PatternLayout.createDefaultLayout();
146        }
147
148        final FileManager manager = FileManager.getFileManager(fileName, isAppend, isLocking, isBuffered, advertiseUri,
149            layout, bufferSize);
150        if (manager == null) {
151            return null;
152        }
153
154        return new FileAppender(name, layout, filter, manager, fileName, ignoreExceptions, isFlush,
155                isAdvertise ? config.getAdvertiser() : null);
156    }
157}