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