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