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     */
017    package org.apache.logging.log4j.core.appender;
018    
019    import org.apache.logging.log4j.core.Filter;
020    import org.apache.logging.log4j.core.Layout;
021    import org.apache.logging.log4j.core.LogEvent;
022    import org.apache.logging.log4j.core.config.Configuration;
023    import org.apache.logging.log4j.core.config.plugins.Plugin;
024    import org.apache.logging.log4j.core.config.plugins.PluginAttr;
025    import org.apache.logging.log4j.core.config.plugins.PluginConfiguration;
026    import org.apache.logging.log4j.core.config.plugins.PluginElement;
027    import org.apache.logging.log4j.core.config.plugins.PluginFactory;
028    import org.apache.logging.log4j.core.layout.PatternLayout;
029    import org.apache.logging.log4j.core.net.Advertiser;
030    
031    import java.io.Serializable;
032    import java.util.HashMap;
033    import java.util.Map;
034    
035    /**
036     * File Appender.
037     */
038    @Plugin(name = "FastFile", category = "Core", elementType = "appender", printObject = true)
039    public final class FastFileAppender<T extends Serializable> extends AbstractOutputStreamAppender<T> {
040    
041        private final String fileName;
042        private Object advertisement;
043        private final Advertiser advertiser;
044    
045        private FastFileAppender(String name, Layout<T> layout, Filter filter,
046                FastFileManager manager, String filename, boolean handleException,
047                boolean immediateFlush, Advertiser advertiser) {
048            super(name, layout, filter, handleException, immediateFlush, manager);
049            if (advertiser != null) {
050                Map<String, String> configuration = new HashMap<String, String>(
051                        layout.getContentFormat());
052                configuration.putAll(manager.getContentFormat());
053                configuration.put("contentType", layout.getContentType());
054                configuration.put("name", name);
055                advertisement = advertiser.advertise(configuration);
056            }
057            this.fileName = filename;
058            this.advertiser = advertiser;
059        }
060    
061        @Override
062        public void stop() {
063            super.stop();
064            if (advertiser != null) {
065                advertiser.unadvertise(advertisement);
066            }
067        }
068    
069        /**
070         * Write the log entry rolling over the file when required.
071         *
072         * @param event The LogEvent.
073         */
074        @Override
075        public void append(LogEvent event) {
076    
077            // Leverage the nice batching behaviour of async Loggers/Appenders:
078            // we can signal the file manager that it needs to flush the buffer
079            // to disk at the end of a batch.
080            // From a user's point of view, this means that all log events are
081            // _always_ available in the log file, without incurring the overhead
082            // of immediateFlush=true.
083            ((FastFileManager) getManager()).setEndOfBatch(event.isEndOfBatch());
084            super.append(event);
085        }
086    
087        /**
088         * Returns the file name this appender is associated with.
089         *
090         * @return The File name.
091         */
092        public String getFileName() {
093            return this.fileName;
094        }
095    
096        // difference from standard File Appender:
097        // locking is not supported and buffering cannot be switched off
098        /**
099         * Create a File Appender.
100         *
101         * @param fileName The name and path of the file.
102         * @param append "True" if the file should be appended to, "false" if it
103         *            should be overwritten. The default is "true".
104         * @param name The name of the Appender.
105         * @param immediateFlush "true" if the contents should be flushed on every
106         *            write, "false" otherwise. The default is "true".
107         * @param suppress "true" if exceptions should be hidden from the
108         *            application, "false" otherwise. The default is "true".
109         * @param layout The layout to use to format the event. If no layout is
110         *            provided the default PatternLayout will be used.
111         * @param filter The filter, if any, to use.
112         * @param advertise "true" if the appender configuration should be
113         *            advertised, "false" otherwise.
114         * @param advertiseURI The advertised URI which can be used to retrieve the
115         *            file contents.
116         * @param config The Configuration.
117         * @return The FileAppender.
118         */
119        @PluginFactory
120        public static <S extends Serializable> FastFileAppender<S> createAppender(
121                @PluginAttr("fileName") String fileName,
122                @PluginAttr("append") String append,
123                @PluginAttr("name") String name,
124                @PluginAttr("immediateFlush") String immediateFlush,
125                @PluginAttr("suppressExceptions") String suppress,
126                @PluginElement("layout") Layout<S> layout,
127                @PluginElement("filters") final Filter filter,
128                @PluginAttr("advertise") final String advertise,
129                @PluginAttr("advertiseURI") final String advertiseURI,
130                @PluginConfiguration final Configuration config) {
131    
132            boolean isAppend = append == null ? true : Boolean.valueOf(append);
133            boolean isFlush = immediateFlush == null ? true : Boolean
134                    .valueOf(immediateFlush);
135            boolean handleExceptions = suppress == null ? true : Boolean
136                    .valueOf(suppress);
137            boolean isAdvertise = advertise == null ? false : Boolean
138                    .valueOf(advertise);
139    
140            if (name == null) {
141                LOGGER.error("No name provided for FileAppender");
142                return null;
143            }
144    
145            if (fileName == null) {
146                LOGGER.error("No filename provided for FileAppender with name "
147                        + name);
148                return null;
149            }
150            if (layout == null) {
151                @SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"})
152                Layout<S> l = (Layout<S>)PatternLayout.createLayout(null, null, null, null, null);
153                layout = l;
154            }
155            FastFileManager manager = FastFileManager.getFileManager(fileName, isAppend, isFlush, advertiseURI, layout);
156            if (manager == null) {
157                return null;
158            }
159    
160            return new FastFileAppender<S>(name, layout, filter, manager, fileName,
161                    handleExceptions, isFlush, isAdvertise ? config.getAdvertiser()
162                            : null);
163        }
164    }