View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the license for the specific language governing permissions and
15   * limitations under the license.
16   */
17  package org.apache.logging.log4j.core.appender;
18  
19  import java.io.Serializable;
20  import java.util.HashMap;
21  import java.util.Map;
22  import java.util.zip.Deflater;
23  
24  import org.apache.logging.log4j.core.Filter;
25  import org.apache.logging.log4j.core.Layout;
26  import org.apache.logging.log4j.core.LogEvent;
27  import org.apache.logging.log4j.core.appender.rolling.DefaultRolloverStrategy;
28  import org.apache.logging.log4j.core.appender.rolling.RollingFileManager;
29  import org.apache.logging.log4j.core.appender.rolling.RollingRandomAccessFileManager;
30  import org.apache.logging.log4j.core.appender.rolling.RolloverStrategy;
31  import org.apache.logging.log4j.core.appender.rolling.TriggeringPolicy;
32  import org.apache.logging.log4j.core.config.Configuration;
33  import org.apache.logging.log4j.core.config.plugins.Plugin;
34  import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
35  import org.apache.logging.log4j.core.config.plugins.PluginConfiguration;
36  import org.apache.logging.log4j.core.config.plugins.PluginElement;
37  import org.apache.logging.log4j.core.config.plugins.PluginFactory;
38  import org.apache.logging.log4j.core.layout.PatternLayout;
39  import org.apache.logging.log4j.core.net.Advertiser;
40  import org.apache.logging.log4j.core.util.Booleans;
41  import org.apache.logging.log4j.core.util.Integers;
42  
43  /**
44   * An appender that writes to random access files and can roll over at
45   * intervals.
46   */
47  @Plugin(name = "RollingRandomAccessFile", category = "Core", elementType = "appender", printObject = true)
48  public final class RollingRandomAccessFileAppender extends AbstractOutputStreamAppender<RollingFileManager> {
49  
50      private final String fileName;
51      private final String filePattern;
52      private Object advertisement;
53      private final Advertiser advertiser;
54  
55      private RollingRandomAccessFileAppender(final String name, final Layout<? extends Serializable> layout,
56              final Filter filter, final RollingFileManager manager, final String fileName,
57              final String filePattern, final boolean ignoreExceptions,
58              final boolean immediateFlush, final int bufferSize, final Advertiser advertiser) {
59          super(name, layout, filter, ignoreExceptions, immediateFlush, manager);
60          if (advertiser != null) {
61              final Map<String, String> configuration = new HashMap<String, String>(layout.getContentFormat());
62              configuration.put("contentType", layout.getContentType());
63              configuration.put("name", name);
64              advertisement = advertiser.advertise(configuration);
65          }
66          this.fileName = fileName;
67          this.filePattern = filePattern;
68          this.advertiser = advertiser;
69      }
70  
71      @Override
72      public void stop() {
73          super.stop();
74          if (advertiser != null) {
75              advertiser.unadvertise(advertisement);
76          }
77      }
78  
79      /**
80       * Write the log entry rolling over the file when required.
81       *
82       * @param event The LogEvent.
83       */
84      @Override
85      public void append(final LogEvent event) {
86          final RollingRandomAccessFileManager manager = (RollingRandomAccessFileManager) getManager();
87          manager.checkRollover(event);
88  
89          // Leverage the nice batching behaviour of async Loggers/Appenders:
90          // we can signal the file manager that it needs to flush the buffer
91          // to disk at the end of a batch.
92          // From a user's point of view, this means that all log events are
93          // _always_ available in the log file, without incurring the overhead
94          // of immediateFlush=true.
95          manager.setEndOfBatch(event.isEndOfBatch());
96          super.append(event);
97      }
98  
99      /**
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 }