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 org.apache.logging.log4j.core.Filter;
20  import org.apache.logging.log4j.core.Layout;
21  import org.apache.logging.log4j.core.LogEvent;
22  import org.apache.logging.log4j.core.appender.rolling.DefaultRolloverStrategy;
23  import org.apache.logging.log4j.core.appender.rolling.FastRollingFileManager;
24  import org.apache.logging.log4j.core.appender.rolling.RollingFileManager;
25  import org.apache.logging.log4j.core.appender.rolling.RolloverStrategy;
26  import org.apache.logging.log4j.core.appender.rolling.TriggeringPolicy;
27  import org.apache.logging.log4j.core.config.Configuration;
28  import org.apache.logging.log4j.core.config.plugins.Plugin;
29  import org.apache.logging.log4j.core.config.plugins.PluginAttr;
30  import org.apache.logging.log4j.core.config.plugins.PluginConfiguration;
31  import org.apache.logging.log4j.core.config.plugins.PluginElement;
32  import org.apache.logging.log4j.core.config.plugins.PluginFactory;
33  import org.apache.logging.log4j.core.layout.PatternLayout;
34  import org.apache.logging.log4j.core.net.Advertiser;
35  
36  import java.io.Serializable;
37  import java.util.HashMap;
38  import java.util.Map;
39  
40  /**
41   * An appender that writes to random access files and can roll over at
42   * intervals.
43   */
44  @Plugin(name = "FastRollingFile", category = "Core", elementType = "appender", printObject = true)
45  public final class FastRollingFileAppender<T extends Serializable> extends AbstractOutputStreamAppender<T> {
46  
47      private final String fileName;
48      private final String filePattern;
49      private Object advertisement;
50      private final Advertiser advertiser;
51  
52      private FastRollingFileAppender(String name, Layout<T> layout,
53              Filter filter, RollingFileManager manager, String fileName,
54              String filePattern, boolean handleException,
55              boolean immediateFlush, Advertiser advertiser) {
56          super(name, layout, filter, handleException, immediateFlush, manager);
57          if (advertiser != null) {
58              Map<String, String> configuration = new HashMap<String, String>(
59                      layout.getContentFormat());
60              configuration.put("contentType", layout.getContentType());
61              configuration.put("name", name);
62              advertisement = advertiser.advertise(configuration);
63          }
64          this.fileName = fileName;
65          this.filePattern = filePattern;
66          this.advertiser = advertiser;
67      }
68  
69      @Override
70      public void stop() {
71          super.stop();
72          if (advertiser != null) {
73              advertiser.unadvertise(advertisement);
74          }
75      }
76  
77      /**
78       * Write the log entry rolling over the file when required.
79       *
80       * @param event The LogEvent.
81       */
82      @Override
83      public void append(final LogEvent event) {
84          FastRollingFileManager manager = (FastRollingFileManager) getManager();
85          manager.checkRollover(event);
86  
87          // Leverage the nice batching behaviour of async Loggers/Appenders:
88          // we can signal the file manager that it needs to flush the buffer
89          // to disk at the end of a batch.
90          // From a user's point of view, this means that all log events are
91          // _always_ available in the log file, without incurring the overhead
92          // of immediateFlush=true.
93          manager.setEndOfBatch(event.isEndOfBatch());
94          super.append(event);
95      }
96  
97      /**
98       * Returns the File name for the Appender.
99       *
100      * @return The file name.
101      */
102     public String getFileName() {
103         return fileName;
104     }
105 
106     /**
107      * Returns the file pattern used when rolling over.
108      *
109      * @return The file pattern.
110      */
111     public String getFilePattern() {
112         return filePattern;
113     }
114 
115     /**
116      * Create a FastRollingFileAppender.
117      *
118      * @param fileName The name of the file that is actively written to.
119      *            (required).
120      * @param filePattern The pattern of the file name to use on rollover.
121      *            (required).
122      * @param append If true, events are appended to the file. If false, the
123      *            file is overwritten when opened. Defaults to "true"
124      * @param name The name of the Appender (required).
125      * @param immediateFlush When true, events are immediately flushed. Defaults
126      *            to "true".
127      * @param policy The triggering policy. (required).
128      * @param strategy The rollover strategy. Defaults to
129      *            DefaultRolloverStrategy.
130      * @param layout The layout to use (defaults to the default PatternLayout).
131      * @param filter The Filter or null.
132      * @param suppress "true" if exceptions should be hidden from the
133      *            application, "false" otherwise. The default is "true".
134      * @param advertise "true" if the appender configuration should be
135      *            advertised, "false" otherwise.
136      * @param advertiseURI The advertised URI which can be used to retrieve the
137      *            file contents.
138      * @param config The Configuration.
139      * @return A FastRollingFileAppender.
140      */
141     @PluginFactory
142     public static <S extends Serializable> FastRollingFileAppender<S> createAppender(
143             @PluginAttr("fileName") final String fileName,
144             @PluginAttr("filePattern") final String filePattern,
145             @PluginAttr("append") final String append,
146             @PluginAttr("name") final String name,
147             @PluginAttr("immediateFlush") final String immediateFlush,
148             @PluginElement("policy") final TriggeringPolicy policy,
149             @PluginElement("strategy") RolloverStrategy strategy,
150             @PluginElement("layout") Layout<S> layout,
151             @PluginElement("filter") final Filter filter,
152             @PluginAttr("suppressExceptions") final String suppress,
153             @PluginAttr("advertise") final String advertise,
154             @PluginAttr("advertiseURI") final String advertiseURI,
155             @PluginConfiguration final Configuration config) {
156 
157         final boolean isAppend = append == null ? true : Boolean
158                 .valueOf(append);
159         final boolean handleExceptions = suppress == null ? true : Boolean
160                 .valueOf(suppress);
161         final boolean isFlush = immediateFlush == null ? true : Boolean
162                 .valueOf(immediateFlush);
163         boolean isAdvertise = advertise == null ? false : Boolean
164                 .valueOf(advertise);
165 
166         if (name == null) {
167             LOGGER.error("No name provided for FileAppender");
168             return null;
169         }
170 
171         if (fileName == null) {
172             LOGGER.error("No filename was provided for FileAppender with name "
173                     + name);
174             return null;
175         }
176 
177         if (filePattern == null) {
178             LOGGER.error("No filename pattern provided for FileAppender with name "
179                     + name);
180             return null;
181         }
182 
183         if (policy == null) {
184             LOGGER.error("A TriggeringPolicy must be provided");
185             return null;
186         }
187 
188         if (strategy == null) {
189             strategy = DefaultRolloverStrategy.createStrategy(null, null,
190                     "true", config);
191         }
192 
193         final FastRollingFileManager manager = FastRollingFileManager
194                 .getFastRollingFileManager(fileName, filePattern, isAppend,
195                         isFlush, policy, strategy, advertiseURI);
196         if (manager == null) {
197             return null;
198         }
199 
200         if (layout == null) {
201             @SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"})
202             Layout<S> l = (Layout<S>)PatternLayout.createLayout(null, null, null, null);
203             layout = l;
204         }
205 
206         return new FastRollingFileAppender<S>(name, layout, filter, manager,
207                 fileName, filePattern, handleExceptions, isFlush,
208                 isAdvertise ? config.getAdvertiser() : null);
209     }
210 }