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 java.io.Serializable;
020    import java.util.HashMap;
021    import java.util.Map;
022    import java.util.zip.Deflater;
023    
024    import org.apache.logging.log4j.core.Filter;
025    import org.apache.logging.log4j.core.Layout;
026    import org.apache.logging.log4j.core.LogEvent;
027    import org.apache.logging.log4j.core.appender.rolling.DefaultRolloverStrategy;
028    import org.apache.logging.log4j.core.appender.rolling.RollingFileManager;
029    import org.apache.logging.log4j.core.appender.rolling.RollingRandomAccessFileManager;
030    import org.apache.logging.log4j.core.appender.rolling.RolloverStrategy;
031    import org.apache.logging.log4j.core.appender.rolling.TriggeringPolicy;
032    import org.apache.logging.log4j.core.config.Configuration;
033    import org.apache.logging.log4j.core.config.plugins.Plugin;
034    import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
035    import org.apache.logging.log4j.core.config.plugins.PluginConfiguration;
036    import org.apache.logging.log4j.core.config.plugins.PluginElement;
037    import org.apache.logging.log4j.core.config.plugins.PluginFactory;
038    import org.apache.logging.log4j.core.layout.PatternLayout;
039    import org.apache.logging.log4j.core.net.Advertiser;
040    import org.apache.logging.log4j.core.util.Booleans;
041    import 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)
048    public final class RollingRandomAccessFileAppender extends AbstractOutputStreamAppender<RollingFileManager> {
049    
050        private final String fileName;
051        private final String filePattern;
052        private Object advertisement;
053        private final Advertiser advertiser;
054    
055        private RollingRandomAccessFileAppender(final String name, final Layout<? extends Serializable> layout,
056                final Filter filter, final RollingFileManager manager, final String fileName,
057                final String filePattern, final boolean ignoreExceptions,
058                final boolean immediateFlush, final int bufferSize, final Advertiser advertiser) {
059            super(name, layout, filter, ignoreExceptions, immediateFlush, manager);
060            if (advertiser != null) {
061                final Map<String, String> configuration = new HashMap<String, String>(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         * Returns the size of the file manager's buffer.
119         * @return the buffer size
120         */
121        public int getBufferSize() {
122            return ((RollingRandomAccessFileManager) getManager()).getBufferSize();
123        }
124    
125        /**
126         * Create a RollingRandomAccessFileAppender.
127         *
128         * @param fileName The name of the file that is actively written to.
129         *            (required).
130         * @param filePattern The pattern of the file name to use on rollover.
131         *            (required).
132         * @param append If true, events are appended to the file. If false, the
133         *            file is overwritten when opened. Defaults to "true"
134         * @param name The name of the Appender (required).
135         * @param immediateFlush When true, events are immediately flushed. Defaults
136         *            to "true".
137         * @param bufferSizeStr The buffer size, defaults to {@value RollingRandomAccessFileManager#DEFAULT_BUFFER_SIZE}.
138         * @param policy The triggering policy. (required).
139         * @param strategy The rollover strategy. Defaults to
140         *            DefaultRolloverStrategy.
141         * @param layout The layout to use (defaults to the default PatternLayout).
142         * @param filter The Filter or null.
143         * @param ignore If {@code "true"} (default) exceptions encountered when appending events are logged; otherwise
144         *               they are propagated to the caller.
145         * @param advertise "true" if the appender configuration should be
146         *            advertised, "false" otherwise.
147         * @param advertiseURI The advertised URI which can be used to retrieve the
148         *            file contents.
149         * @param config The Configuration.
150         * @return A RollingRandomAccessFileAppender.
151         */
152        @PluginFactory
153        public static RollingRandomAccessFileAppender createAppender(
154                @PluginAttribute("fileName") final String fileName,
155                @PluginAttribute("filePattern") final String filePattern,
156                @PluginAttribute("append") final String append,
157                @PluginAttribute("name") final String name,
158                @PluginAttribute("immediateFlush") final String immediateFlush,
159                @PluginAttribute("bufferSize") final String bufferSizeStr,
160                @PluginElement("Policy") final TriggeringPolicy policy,
161                @PluginElement("Strategy") RolloverStrategy strategy,
162                @PluginElement("Layout") Layout<? extends Serializable> layout,
163                @PluginElement("Filter") final Filter filter,
164                @PluginAttribute("ignoreExceptions") final String ignore,
165                @PluginAttribute("advertise") final String advertise,
166                @PluginAttribute("advertiseURI") final String advertiseURI,
167                @PluginConfiguration final Configuration config) {
168    
169            final boolean isAppend = Booleans.parseBoolean(append, true);
170            final boolean ignoreExceptions = Booleans.parseBoolean(ignore, true);
171            final boolean isFlush = Booleans.parseBoolean(immediateFlush, true);
172            final boolean isAdvertise = Boolean.parseBoolean(advertise);
173            final int bufferSize = Integers.parseInt(bufferSizeStr, RollingRandomAccessFileManager.DEFAULT_BUFFER_SIZE);
174    
175            if (name == null) {
176                LOGGER.error("No name provided for FileAppender");
177                return null;
178            }
179    
180            if (fileName == null) {
181                LOGGER.error("No filename was provided for FileAppender with name " + name);
182                return null;
183            }
184    
185            if (filePattern == null) {
186                LOGGER.error("No filename pattern provided for FileAppender with name " + name);
187                return null;
188            }
189    
190            if (policy == null) {
191                LOGGER.error("A TriggeringPolicy must be provided");
192                return null;
193            }
194    
195            if (strategy == null) {
196                strategy = DefaultRolloverStrategy.createStrategy(null, null, null,
197                        String.valueOf(Deflater.DEFAULT_COMPRESSION), config);
198            }
199    
200            if (layout == null) {
201                layout = PatternLayout.createDefaultLayout();
202            }
203    
204            final RollingRandomAccessFileManager manager = RollingRandomAccessFileManager.getRollingRandomAccessFileManager(
205                    fileName, filePattern, isAppend, isFlush, bufferSize, policy, strategy, advertiseURI, layout);
206            if (manager == null) {
207                return null;
208            }
209    
210            return new RollingRandomAccessFileAppender(name, layout, filter, manager,
211                    fileName, filePattern, ignoreExceptions, isFlush, bufferSize,
212                    isAdvertise ? config.getAdvertiser() : null);
213        }
214    }