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.RolloverStrategy;
30  import org.apache.logging.log4j.core.appender.rolling.TriggeringPolicy;
31  import org.apache.logging.log4j.core.config.Configuration;
32  import org.apache.logging.log4j.core.config.plugins.Plugin;
33  import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
34  import org.apache.logging.log4j.core.config.plugins.PluginConfiguration;
35  import org.apache.logging.log4j.core.config.plugins.PluginElement;
36  import org.apache.logging.log4j.core.config.plugins.PluginFactory;
37  import org.apache.logging.log4j.core.layout.PatternLayout;
38  import org.apache.logging.log4j.core.net.Advertiser;
39  import org.apache.logging.log4j.core.util.Booleans;
40  import org.apache.logging.log4j.core.util.Integers;
41  
42  /**
43   * An appender that writes to files and can roll over at intervals.
44   */
45  @Plugin(name = "RollingFile", category = "Core", elementType = "appender", printObject = true)
46  public final class RollingFileAppender extends AbstractOutputStreamAppender<RollingFileManager> {
47  
48      private static final int DEFAULT_BUFFER_SIZE = 8192;
49      private static final long serialVersionUID = 1L;
50  
51      private final String fileName;
52      private final String filePattern;
53      private Object advertisement;
54      private final Advertiser advertiser;
55  
56  
57      private RollingFileAppender(final String name, final Layout<? extends Serializable> layout, final Filter filter,
58              final RollingFileManager manager, final String fileName, final String filePattern,
59              final boolean ignoreExceptions, final boolean immediateFlush, final Advertiser advertiser) {
60          super(name, layout, filter, ignoreExceptions, immediateFlush, manager);
61          if (advertiser != null) {
62              final Map<String, String> configuration = new HashMap<>(layout.getContentFormat());
63              configuration.put("contentType", layout.getContentType());
64              configuration.put("name", name);
65              advertisement = advertiser.advertise(configuration);
66          }
67          this.fileName = fileName;
68          this.filePattern = filePattern;
69          this.advertiser = advertiser;
70      }
71  
72      @Override
73      public void stop() {
74          super.stop();
75          if (advertiser != null) {
76              advertiser.unadvertise(advertisement);
77          }
78      }
79  
80      /**
81       * Write the log entry rolling over the file when required.
82  
83       * @param event The LogEvent.
84       */
85      @Override
86      public void append(final LogEvent event) {
87          getManager().checkRollover(event);
88          super.append(event);
89      }
90  
91      /**
92       * Returns the File name for the Appender.
93       * @return The file name.
94       */
95      public String getFileName() {
96          return fileName;
97      }
98  
99      /**
100      * Returns the file pattern used when rolling over.
101      * @return The file pattern.
102      */
103     public String getFilePattern() {
104         return filePattern;
105     }
106 
107     /**
108      * Returns the triggering policy
109      * @return The TriggeringPolicy
110      */
111     public <T extends TriggeringPolicy> T getTriggeringPolicy() {
112         return getManager().getTriggeringPolicy();
113     }
114 
115     /**
116      * Create a RollingFileAppender.
117      * @param fileName The name of the file that is actively written to. (required).
118      * @param filePattern The pattern of the file name to use on rollover. (required).
119      * @param append If true, events are appended to the file. If false, the file
120      * is overwritten when opened. Defaults to "true"
121      * @param name The name of the Appender (required).
122      * @param bufferedIO When true, I/O will be buffered. Defaults to "true".
123      * @param bufferSizeStr buffer size for buffered IO (default is 8192).
124      * @param immediateFlush When true, events are immediately flushed. Defaults to "true".
125      * @param policy The triggering policy. (required).
126      * @param strategy The rollover strategy. Defaults to DefaultRolloverStrategy.
127      * @param layout The layout to use (defaults to the default PatternLayout).
128      * @param filter The Filter or null.
129      * @param ignore If {@code "true"} (default) exceptions encountered when appending events are logged; otherwise
130      *               they are propagated to the caller.
131      * @param advertise "true" if the appender configuration should be advertised, "false" otherwise.
132      * @param advertiseURI The advertised URI which can be used to retrieve the file contents.
133      * @param config The Configuration.
134      * @return A RollingFileAppender.
135      */
136     @PluginFactory
137     public static RollingFileAppender createAppender(
138             @PluginAttribute("fileName") final String fileName,
139             @PluginAttribute("filePattern") final String filePattern,
140             @PluginAttribute("append") final String append,
141             @PluginAttribute("name") final String name,
142             @PluginAttribute("bufferedIO") final String bufferedIO,
143             @PluginAttribute("bufferSize") final String bufferSizeStr,
144             @PluginAttribute("immediateFlush") final String immediateFlush,
145             @PluginElement("Policy") final TriggeringPolicy policy,
146             @PluginElement("Strategy") RolloverStrategy strategy,
147             @PluginElement("Layout") Layout<? extends Serializable> layout,
148             @PluginElement("Filter") final Filter filter,
149             @PluginAttribute("ignoreExceptions") final String ignore,
150             @PluginAttribute("advertise") final String advertise,
151             @PluginAttribute("advertiseURI") final String advertiseURI,
152             @PluginConfiguration final Configuration config) {
153 
154         final boolean isAppend = Booleans.parseBoolean(append, true);
155         final boolean ignoreExceptions = Booleans.parseBoolean(ignore, true);
156         final boolean isBuffered = Booleans.parseBoolean(bufferedIO, true);
157         final boolean isFlush = Booleans.parseBoolean(immediateFlush, true);
158         final boolean isAdvertise = Boolean.parseBoolean(advertise);
159         final int bufferSize = Integers.parseInt(bufferSizeStr, DEFAULT_BUFFER_SIZE);
160         if (!isBuffered && bufferSize > 0) {
161             LOGGER.warn("The bufferSize is set to {} but bufferedIO is not true: {}", bufferSize, bufferedIO);
162         }
163         if (name == null) {
164             LOGGER.error("No name provided for FileAppender");
165             return null;
166         }
167 
168         if (fileName == null) {
169             LOGGER.error("No filename was provided for FileAppender with name "  + name);
170             return null;
171         }
172 
173         if (filePattern == null) {
174             LOGGER.error("No filename pattern provided for FileAppender with name "  + name);
175             return null;
176         }
177 
178         if (policy == null) {
179             LOGGER.error("A TriggeringPolicy must be provided");
180             return null;
181         }
182 
183         if (strategy == null) {
184             strategy = DefaultRolloverStrategy.createStrategy(null, null, null,
185                     String.valueOf(Deflater.DEFAULT_COMPRESSION), config);
186         }
187 
188         if (layout == null) {
189             layout = PatternLayout.createDefaultLayout();
190         }
191 
192         final RollingFileManager manager = RollingFileManager.getFileManager(fileName, filePattern, isAppend,
193             isBuffered, policy, strategy, advertiseURI, layout, bufferSize);
194         if (manager == null) {
195             return null;
196         }
197 
198         return new RollingFileAppender(name, layout, filter, manager, fileName, filePattern,
199                 ignoreExceptions, isFlush, isAdvertise ? config.getAdvertiser() : null);
200     }
201 }