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.zip.Deflater;
    23
    24  import org.apache.logging.log4j.core.Filter;
    25  import org.apache.logging.log4j.core.Layout;
    26  import org.apache.logging.log4j.core.LogEvent;
    27  import org.apache.logging.log4j.core.appender.rolling.DefaultRolloverStrategy;
    28  import org.apache.logging.log4j.core.appender.rolling.RollingFileManager;
    29  import org.apache.logging.log4j.core.appender.rolling.RollingRandomAccessFileManager;
    30  import org.apache.logging.log4j.core.appender.rolling.RolloverStrategy;
    31  import org.apache.logging.log4j.core.appender.rolling.TriggeringPolicy;
    32  import org.apache.logging.log4j.core.config.Configuration;
    33  import org.apache.logging.log4j.core.config.plugins.Plugin;
    34  import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
    35  import org.apache.logging.log4j.core.config.plugins.PluginConfiguration;
    36  import org.apache.logging.log4j.core.config.plugins.PluginElement;
    37  import org.apache.logging.log4j.core.config.plugins.PluginFactory;
    38  import org.apache.logging.log4j.core.layout.PatternLayout;
    39  import org.apache.logging.log4j.core.net.Advertiser;
    40  import org.apache.logging.log4j.core.util.Booleans;
    41  import org.apache.logging.log4j.core.util.Integers;
    42
    43  /**
    44   * An appender that writes to random access files and can roll over at
    45   * intervals.
    46   */
    47  @Plugin(name = "RollingRandomAccessFile", category = "Core", elementType = "appender", printObject = true)
    48  public final class RollingRandomAccessFileAppender extends AbstractOutputStreamAppender<RollingFileManager> {
    49
    50      private static final long serialVersionUID = 1L;
    51
    52      private final String fileName;
    53      private final String filePattern;
    54      private Object advertisement;
    55      private final Advertiser advertiser;
    56
    57      private RollingRandomAccessFileAppender(final String name, final Layout<? extends Serializable> layout,
    58              final Filter filter, final RollingFileManager manager, final String fileName,
    59              final String filePattern, final boolean ignoreExceptions,
    60              final boolean immediateFlush, final int bufferSize, final Advertiser advertiser) {
    61          super(name, layout, filter, ignoreExceptions, immediateFlush, manager);
    62          if (advertiser != null) {
    63              final Map<String, String> configuration = new HashMap<String, String>(layout.getContentFormat());
    64              configuration.put("contentType", layout.getContentType());
    65              configuration.put("name", name);
    66              advertisement = advertiser.advertise(configuration);
    67          }
    68          this.fileName = fileName;
    69          this.filePattern = filePattern;
    70          this.advertiser = advertiser;
    71      }
    72
    73      @Override
    74      public void stop() {
    75          super.stop();
    76          if (advertiser != null) {
    77              advertiser.unadvertise(advertisement);
    78          }
    79      }
    80
    81      /**
    82       * Write the log entry rolling over the file when required.
    83       *
    84       * @param event The LogEvent.
    85       */
    86      @Override
    87      public void append(final LogEvent event) {
    88          final RollingRandomAccessFileManager manager = (RollingRandomAccessFileManager) getManager();
    89          manager.checkRollover(event);
    90
    91          // Leverage the nice batching behaviour of async Loggers/Appenders:
    92          // we can signal the file manager that it needs to flush the buffer
    93          // to disk at the end of a batch.
    94          // From a user's point of view, this means that all log events are
    95          // _always_ available in the log file, without incurring the overhead
    96          // of immediateFlush=true.
    97          manager.setEndOfBatch(event.isEndOfBatch());
    98          super.append(event);
    99      }
    100
    101     /**
    102      * Returns the File name for the Appender.
    103      *
    104      * @return The file name.
    105      */
    106     public String getFileName() {
    107         return fileName;
    108     }
    109
    110     /**
    111      * Returns the file pattern used when rolling over.
    112      *
    113      * @return The file pattern.
    114      */
    115     public String getFilePattern() {
    116         return filePattern;
    117     }
    118
    119     /**
    120      * Returns the size of the file manager's buffer.
    121      * @return the buffer size
    122      */
    123     public int getBufferSize() {
    124         return ((RollingRandomAccessFileManager) getManager()).getBufferSize();
    125     }
    126
    127     /**
    128      * Create a RollingRandomAccessFileAppender.
    129      *
    130      * @param fileName The name of the file that is actively written to.
    131      *            (required).
    132      * @param filePattern The pattern of the file name to use on rollover.
    133      *            (required).
    134      * @param append If true, events are appended to the file. If false, the
    135      *            file is overwritten when opened. Defaults to "true"
    136      * @param name The name of the Appender (required).
    137      * @param immediateFlush When true, events are immediately flushed. Defaults
    138      *            to "true".
    139      * @param bufferSizeStr The buffer size, defaults to {@value RollingRandomAccessFileManager#DEFAULT_BUFFER_SIZE}.
    140      * @param policy The triggering policy. (required).
    141      * @param strategy The rollover strategy. Defaults to
    142      *            DefaultRolloverStrategy.
    143      * @param layout The layout to use (defaults to the default PatternLayout).
    144      * @param filter The Filter or null.
    145      * @param ignore If {@code "true"} (default) exceptions encountered when appending events are logged; otherwise
    146      *               they are propagated to the caller.
    147      * @param advertise "true" if the appender configuration should be
    148      *            advertised, "false" otherwise.
    149      * @param advertiseURI The advertised URI which can be used to retrieve the
    150      *            file contents.
    151      * @param config The Configuration.
    152      * @return A RollingRandomAccessFileAppender.
    153      */
    154     @PluginFactory
    155     public static RollingRandomAccessFileAppender createAppender(
    156             @PluginAttribute("fileName") final String fileName,
    157             @PluginAttribute("filePattern") final String filePattern,
    158             @PluginAttribute("append") final String append,
    159             @PluginAttribute("name") final String name,
    160             @PluginAttribute("immediateFlush") final String immediateFlush,
    161             @PluginAttribute("bufferSize") final String bufferSizeStr,
    162             @PluginElement("Policy") final TriggeringPolicy policy,
    163             @PluginElement("Strategy") RolloverStrategy strategy,
    164             @PluginElement("Layout") Layout<? extends Serializable> layout,
    165             @PluginElement("Filter") final Filter filter,
    166             @PluginAttribute("ignoreExceptions") final String ignore,
    167             @PluginAttribute("advertise") final String advertise,
    168             @PluginAttribute("advertiseURI") final String advertiseURI,
    169             @PluginConfiguration final Configuration config) {
    170
    171         final boolean isAppend = Booleans.parseBoolean(append, true);
    172         final boolean ignoreExceptions = Booleans.parseBoolean(ignore, true);
    173         final boolean isFlush = Booleans.parseBoolean(immediateFlush, true);
    174         final boolean isAdvertise = Boolean.parseBoolean(advertise);
    175         final int bufferSize = Integers.parseInt(bufferSizeStr, RollingRandomAccessFileManager.DEFAULT_BUFFER_SIZE);
    176
    177         if (name == null) {
    178             LOGGER.error("No name provided for FileAppender");
    179             return null;
    180         }
    181
    182         if (fileName == null) {
    183             LOGGER.error("No filename was provided for FileAppender with name " + name);
    184             return null;
    185         }
    186
    187         if (filePattern == null) {
    188             LOGGER.error("No filename pattern provided for FileAppender with name " + name);
    189             return null;
    190         }
    191
    192         if (policy == null) {
    193             LOGGER.error("A TriggeringPolicy must be provided");
    194             return null;
    195         }
    196
    197         if (strategy == null) {
    198             strategy = DefaultRolloverStrategy.createStrategy(null, null, null,
    199                     String.valueOf(Deflater.DEFAULT_COMPRESSION), config);
    200         }
    201
    202         if (layout == null) {
    203             layout = PatternLayout.createDefaultLayout();
    204         }
    205
    206         final RollingRandomAccessFileManager manager = RollingRandomAccessFileManager.getRollingRandomAccessFileManager(
    207                 fileName, filePattern, isAppend, isFlush, bufferSize, policy, strategy, advertiseURI, layout);
    208         if (manager == null) {
    209             return null;
    210         }
    211
    212         return new RollingRandomAccessFileAppender(name, layout, filter, manager,
    213                 fileName, filePattern, ignoreExceptions, isFlush, bufferSize,
    214                 isAdvertise ? config.getAdvertiser() : null);
    215     }
    216 }