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   * Memory Mapped File Appender.
39   * 
40   * @since 2.1
41   */
42  @Plugin(name = "MemoryMappedFile", category = "Core", elementType = "appender", printObject = true)
43  public final class MemoryMappedFileAppender extends AbstractOutputStreamAppender<MemoryMappedFileManager> {
44  
45      private static final long serialVersionUID = 1L;
46  
47      private static final int BIT_POSITION_1GB = 30; // 2^30 ~= 1GB
48      private static final int MAX_REGION_LENGTH = 1 << BIT_POSITION_1GB;
49      private static final int MIN_REGION_LENGTH = 256;
50  
51      private final String fileName;
52      private Object advertisement;
53      private final Advertiser advertiser;
54  
55      private MemoryMappedFileAppender(final String name, final Layout<? extends Serializable> layout,
56              final Filter filter, final MemoryMappedFileManager manager, final String filename,
57              final boolean ignoreExceptions, final boolean immediateFlush, final Advertiser advertiser) {
58          super(name, layout, filter, ignoreExceptions, immediateFlush, manager);
59          if (advertiser != null) {
60              final Map<String, String> configuration = new HashMap<>(layout.getContentFormat());
61              configuration.putAll(manager.getContentFormat());
62              configuration.put("contentType", layout.getContentType());
63              configuration.put("name", name);
64              advertisement = advertiser.advertise(configuration);
65          }
66          this.fileName = filename;
67          this.advertiser = advertiser;
68      }
69  
70      @Override
71      public void stop() {
72          super.stop();
73          if (advertiser != null) {
74              advertiser.unadvertise(advertisement);
75          }
76      }
77  
78      /**
79       * Write the log entry rolling over the file when required.
80       *
81       * @param event The LogEvent.
82       */
83      @Override
84      public void append(final LogEvent event) {
85  
86          // Leverage the nice batching behaviour of async Loggers/Appenders:
87          // we can signal the file manager that it needs to flush the buffer
88          // to disk at the end of a batch.
89          // From a user's point of view, this means that all log events are
90          // _always_ available in the log file, without incurring the overhead
91          // of immediateFlush=true.
92          getManager().setEndOfBatch(event.isEndOfBatch());
93          super.append(event);
94      }
95  
96      /**
97       * Returns the file name this appender is associated with.
98       *
99       * @return The File name.
100      */
101     public String getFileName() {
102         return this.fileName;
103     }
104 
105     /**
106      * Returns the length of the memory mapped region.
107      * 
108      * @return the length of the memory mapped region
109      */
110     public int getRegionLength() {
111         return getManager().getRegionLength();
112     }
113 
114     /**
115      * Create a Memory Mapped File Appender.
116      *
117      * @param fileName The name and path of the file.
118      * @param append "True" if the file should be appended to, "false" if it should be overwritten. The default is
119      *            "true".
120      * @param name The name of the Appender.
121      * @param immediateFlush "true" if the contents should be flushed on every write, "false" otherwise. The default is
122      *            "true".
123      * @param regionLengthStr The buffer size, defaults to {@value MemoryMappedFileManager#DEFAULT_REGION_LENGTH}.
124      * @param ignore If {@code "true"} (default) exceptions encountered when appending events are logged; otherwise they
125      *            are propagated to the caller.
126      * @param layout The layout to use to format the event. If no layout is provided the default PatternLayout will be
127      *            used.
128      * @param filter The filter, if any, to use.
129      * @param advertise "true" if the appender configuration should be advertised, "false" otherwise.
130      * @param advertiseURI The advertised URI which can be used to retrieve the file contents.
131      * @param config The Configuration.
132      * @return The FileAppender.
133      */
134     @PluginFactory
135     public static MemoryMappedFileAppender createAppender(
136 // @formatter:off
137             @PluginAttribute("fileName") final String fileName, //
138             @PluginAttribute("append") final String append, //
139             @PluginAttribute("name") final String name, //
140             @PluginAttribute("immediateFlush") final String immediateFlush, //
141             @PluginAttribute("regionLength") final String regionLengthStr, //
142             @PluginAttribute("ignoreExceptions") final String ignore, //
143             @PluginElement("Layout") Layout<? extends Serializable> layout, //
144             @PluginElement("Filter") final Filter filter, //
145             @PluginAttribute("advertise") final String advertise, //
146             @PluginAttribute("advertiseURI") final String advertiseURI, //
147             @PluginConfiguration final Configuration config) {
148         // @formatter:on
149 
150         final boolean isAppend = Booleans.parseBoolean(append, true);
151         final boolean isForce = Booleans.parseBoolean(immediateFlush, false);
152         final boolean ignoreExceptions = Booleans.parseBoolean(ignore, true);
153         final boolean isAdvertise = Boolean.parseBoolean(advertise);
154         final int regionLength = Integers.parseInt(regionLengthStr, MemoryMappedFileManager.DEFAULT_REGION_LENGTH);
155         final int actualRegionLength = determineValidRegionLength(name, regionLength);
156 
157         if (name == null) {
158             LOGGER.error("No name provided for MemoryMappedFileAppender");
159             return null;
160         }
161 
162         if (fileName == null) {
163             LOGGER.error("No filename provided for MemoryMappedFileAppender with name " + name);
164             return null;
165         }
166         if (layout == null) {
167             layout = PatternLayout.createDefaultLayout();
168         }
169         final MemoryMappedFileManager manager = MemoryMappedFileManager.getFileManager(fileName, isAppend, isForce,
170                 actualRegionLength, advertiseURI, layout);
171         if (manager == null) {
172             return null;
173         }
174 
175         return new MemoryMappedFileAppender(name, layout, filter, manager, fileName, ignoreExceptions, isForce,
176                 isAdvertise ? config.getAdvertiser() : null);
177     }
178 
179     /**
180      * Converts the specified region length to a valid value.
181      */
182     private static int determineValidRegionLength(final String name, final int regionLength) {
183         if (regionLength > MAX_REGION_LENGTH) {
184             LOGGER.info("MemoryMappedAppender[{}] Reduced region length from {} to max length: {}", name, regionLength,
185                     MAX_REGION_LENGTH);
186             return MAX_REGION_LENGTH;
187         }
188         if (regionLength < MIN_REGION_LENGTH) {
189             LOGGER.info("MemoryMappedAppender[{}] Expanded region length from {} to min length: {}", name, regionLength,
190                     MIN_REGION_LENGTH);
191             return MIN_REGION_LENGTH;
192         }
193         final int result = Integers.ceilingNextPowerOfTwo(regionLength);
194         if (regionLength != result) {
195             LOGGER.info("MemoryMappedAppender[{}] Rounded up region length from {} to next power of two: {}", name,
196                     regionLength, result);
197         }
198         return result;
199     }
200 }