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.RollingRandomAccessFileManager;
29  import org.apache.logging.log4j.core.appender.rolling.RollingFileManager;
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.helpers.Booleans;
39  import org.apache.logging.log4j.core.layout.PatternLayout;
40  import org.apache.logging.log4j.core.net.Advertiser;
41  
42  /**
43   * An appender that writes to random access files and can roll over at
44   * intervals.
45   */
46  @Plugin(name = "RollingRandomAccessFile", category = "Core", elementType = "appender", printObject = true)
47  public final class RollingRandomAccessFileAppender extends AbstractOutputStreamAppender<RollingFileManager> {
48  
49      private final String fileName;
50      private final String filePattern;
51      private Object advertisement;
52      private final Advertiser advertiser;
53  
54      private RollingRandomAccessFileAppender(final String name, final Layout<? extends Serializable> layout,
55              final Filter filter, final RollingFileManager manager, final String fileName,
56              final String filePattern, final boolean ignoreExceptions,
57              final boolean immediateFlush, final Advertiser advertiser) {
58          super(name, layout, filter, ignoreExceptions, immediateFlush, manager);
59          if (advertiser != null) {
60              final Map<String, String> configuration = new HashMap<String, String>(
61                      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      * Create a RollingRandomAccessFileAppender.
119      *
120      * @param fileName The name of the file that is actively written to.
121      *            (required).
122      * @param filePattern The pattern of the file name to use on rollover.
123      *            (required).
124      * @param append If true, events are appended to the file. If false, the
125      *            file is overwritten when opened. Defaults to "true"
126      * @param name The name of the Appender (required).
127      * @param immediateFlush When true, events are immediately flushed. Defaults
128      *            to "true".
129      * @param policy The triggering policy. (required).
130      * @param strategy The rollover strategy. Defaults to
131      *            DefaultRolloverStrategy.
132      * @param layout The layout to use (defaults to the default PatternLayout).
133      * @param filter The Filter or null.
134      * @param ignore If {@code "true"} (default) exceptions encountered when appending events are logged; otherwise
135      *               they are propagated to the caller.
136      * @param advertise "true" if the appender configuration should be
137      *            advertised, "false" otherwise.
138      * @param advertiseURI The advertised URI which can be used to retrieve the
139      *            file contents.
140      * @param config The Configuration.
141      * @return A RollingRandomAccessFileAppender.
142      */
143     @PluginFactory
144     public static RollingRandomAccessFileAppender createAppender(
145             @PluginAttribute("fileName") final String fileName,
146             @PluginAttribute("filePattern") final String filePattern,
147             @PluginAttribute("append") final String append,
148             @PluginAttribute("name") final String name,
149             @PluginAttribute("immediateFlush") final String immediateFlush,
150             @PluginElement("Policy") final TriggeringPolicy policy,
151             @PluginElement("Strategy") RolloverStrategy strategy,
152             @PluginElement("Layout") Layout<? extends Serializable> layout,
153             @PluginElement("Filter") final Filter filter,
154             @PluginAttribute("ignoreExceptions") final String ignore,
155             @PluginAttribute("advertise") final String advertise,
156             @PluginAttribute("advertiseURI") final String advertiseURI,
157             @PluginConfiguration final Configuration config) {
158 
159         final boolean isAppend = Booleans.parseBoolean(append, true);
160         final boolean ignoreExceptions = Booleans.parseBoolean(ignore, true);
161         final boolean isFlush = Booleans.parseBoolean(immediateFlush, true);
162         final boolean isAdvertise = Boolean.parseBoolean(advertise);
163 
164         if (name == null) {
165             LOGGER.error("No name provided for FileAppender");
166             return null;
167         }
168 
169         if (fileName == null) {
170             LOGGER.error("No filename was provided for FileAppender with name "
171                     + name);
172             return null;
173         }
174 
175         if (filePattern == null) {
176             LOGGER.error("No filename pattern provided for FileAppender with name "
177                     + name);
178             return null;
179         }
180 
181         if (policy == null) {
182             LOGGER.error("A TriggeringPolicy must be provided");
183             return null;
184         }
185 
186         if (strategy == null) {
187             strategy = DefaultRolloverStrategy.createStrategy(null, null, null,
188                     String.valueOf(Deflater.DEFAULT_COMPRESSION), config);
189         }
190 
191         if (layout == null) {
192             layout = PatternLayout.createLayout(null, null, null, null, null, null);
193         }
194 
195 
196         final RollingRandomAccessFileManager manager = RollingRandomAccessFileManager.getRollingRandomAccessFileManager(fileName, filePattern,
197             isAppend, isFlush, policy, strategy, advertiseURI, layout);
198         if (manager == null) {
199             return null;
200         }
201 
202         return new RollingRandomAccessFileAppender(name, layout, filter, manager,
203                 fileName, filePattern, ignoreExceptions, isFlush,
204                 isAdvertise ? config.getAdvertiser() : null);
205     }
206 }