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