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  
23  import org.apache.logging.log4j.core.Filter;
24  import org.apache.logging.log4j.core.Layout;
25  import org.apache.logging.log4j.core.LogEvent;
26  import org.apache.logging.log4j.core.config.Configuration;
27  import org.apache.logging.log4j.core.config.plugins.Plugin;
28  import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
29  import org.apache.logging.log4j.core.config.plugins.PluginConfiguration;
30  import org.apache.logging.log4j.core.config.plugins.PluginElement;
31  import org.apache.logging.log4j.core.config.plugins.PluginFactory;
32  import org.apache.logging.log4j.core.layout.PatternLayout;
33  import org.apache.logging.log4j.core.net.Advertiser;
34  import org.apache.logging.log4j.core.util.Booleans;
35  import org.apache.logging.log4j.core.util.Integers;
36  
37  /**
38   * File Appender.
39   */
40  @Plugin(name = "RandomAccessFile", category = "Core", elementType = "appender", printObject = true)
41  public final class RandomAccessFileAppender extends AbstractOutputStreamAppender<RandomAccessFileManager> {
42  
43      private static final long serialVersionUID = 1L;
44  
45      private final String fileName;
46      private Object advertisement;
47      private final Advertiser advertiser;
48  
49      private RandomAccessFileAppender(final String name, final Layout<? extends Serializable> layout, final Filter filter,
50              final RandomAccessFileManager manager, final String filename, final boolean ignoreExceptions,
51              final boolean immediateFlush, final Advertiser advertiser) {
52          super(name, layout, filter, ignoreExceptions, immediateFlush, manager);
53          if (advertiser != null) {
54              final Map<String, String> configuration = new HashMap<String, String>(
55                      layout.getContentFormat());
56              configuration.putAll(manager.getContentFormat());
57              configuration.put("contentType", layout.getContentType());
58              configuration.put("name", name);
59              advertisement = advertiser.advertise(configuration);
60          }
61          this.fileName = filename;
62          this.advertiser = advertiser;
63      }
64  
65      @Override
66      public void stop() {
67          super.stop();
68          if (advertiser != null) {
69              advertiser.unadvertise(advertisement);
70          }
71      }
72  
73      /**
74       * Write the log entry rolling over the file when required.
75       *
76       * @param event The LogEvent.
77       */
78      @Override
79      public void append(final LogEvent event) {
80  
81          // Leverage the nice batching behaviour of async Loggers/Appenders:
82          // we can signal the file manager that it needs to flush the buffer
83          // to disk at the end of a batch.
84          // From a user's point of view, this means that all log events are
85          // _always_ available in the log file, without incurring the overhead
86          // of immediateFlush=true.
87          getManager().setEndOfBatch(event.isEndOfBatch());
88          super.append(event);
89      }
90  
91      /**
92       * Returns the file name this appender is associated with.
93       *
94       * @return The File name.
95       */
96      public String getFileName() {
97          return this.fileName;
98      }
99      
100     /**
101      * Returns the size of the file manager's buffer.
102      * @return the buffer size
103      */
104     public int getBufferSize() {
105         return getManager().getBufferSize();
106     }
107 
108     // difference from standard File Appender:
109     // locking is not supported and buffering cannot be switched off
110     /**
111      * Create a File Appender.
112      *
113      * @param fileName The name and path of the file.
114      * @param append "True" if the file should be appended to, "false" if it
115      *            should be overwritten. The default is "true".
116      * @param name The name of the Appender.
117      * @param immediateFlush "true" if the contents should be flushed on every
118      *            write, "false" otherwise. The default is "true".
119      * @param bufferSizeStr The buffer size, defaults to {@value RandomAccessFileManager#DEFAULT_BUFFER_SIZE}.
120      * @param ignore If {@code "true"} (default) exceptions encountered when appending events are logged; otherwise
121      *               they are propagated to the caller.
122      * @param layout The layout to use to format the event. If no layout is
123      *            provided the default PatternLayout will be used.
124      * @param filter The filter, if any, to use.
125      * @param advertise "true" if the appender configuration should be
126      *            advertised, "false" otherwise.
127      * @param advertiseURI The advertised URI which can be used to retrieve the
128      *            file contents.
129      * @param config The Configuration.
130      * @return The FileAppender.
131      */
132     @PluginFactory
133     public static RandomAccessFileAppender createAppender(
134             @PluginAttribute("fileName") final String fileName,
135             @PluginAttribute("append") final String append,
136             @PluginAttribute("name") final String name,
137             @PluginAttribute("immediateFlush") final String immediateFlush,
138             @PluginAttribute("bufferSize") final String bufferSizeStr,
139             @PluginAttribute("ignoreExceptions") final String ignore,
140             @PluginElement("Layout") Layout<? extends Serializable> layout,
141             @PluginElement("Filter") final Filter filter,
142             @PluginAttribute("advertise") final String advertise,
143             @PluginAttribute("advertiseURI") final String advertiseURI,
144             @PluginConfiguration final Configuration config) {
145 
146         final boolean isAppend = Booleans.parseBoolean(append, true);
147         final boolean isFlush = Booleans.parseBoolean(immediateFlush, true);
148         final boolean ignoreExceptions = Booleans.parseBoolean(ignore, true);
149         final boolean isAdvertise = Boolean.parseBoolean(advertise);
150         final int bufferSize = Integers.parseInt(bufferSizeStr, RandomAccessFileManager.DEFAULT_BUFFER_SIZE);
151 
152         if (name == null) {
153             LOGGER.error("No name provided for FileAppender");
154             return null;
155         }
156 
157         if (fileName == null) {
158             LOGGER.error("No filename provided for FileAppender with name "
159                     + name);
160             return null;
161         }
162         if (layout == null) {
163             layout = PatternLayout.createDefaultLayout();
164         }
165         final RandomAccessFileManager manager = RandomAccessFileManager.getFileManager(
166                 fileName, isAppend, isFlush, bufferSize, advertiseURI, layout
167         );
168         if (manager == null) {
169             return null;
170         }
171 
172         return new RandomAccessFileAppender(
173                 name, layout, filter, manager, fileName, ignoreExceptions, isFlush,
174                 isAdvertise ? config.getAdvertiser() : null
175         );
176     }
177 }