Java 类org.apache.logging.log4j.core.appender.rolling.DefaultRolloverStrategy 实例源码

项目:logging-log4j2    文件:Log4j1ConfigurationFactoryTest.java   
private void testRollingFileAppender(final String configResource, final String name, final String filePattern) throws URISyntaxException {
    final Configuration configuration = getConfiguration(configResource);
    final Appender appender = configuration.getAppender(name);
    assertNotNull(appender);
    assertEquals(name, appender.getName());
    assertTrue(appender.getClass().getName(), appender instanceof RollingFileAppender);
    final RollingFileAppender rfa = (RollingFileAppender) appender;
    assertEquals("target/hadoop.log", rfa.getFileName());
    assertEquals(filePattern, rfa.getFilePattern());
    final TriggeringPolicy triggeringPolicy = rfa.getTriggeringPolicy();
    assertNotNull(triggeringPolicy);
    assertTrue(triggeringPolicy.getClass().getName(), triggeringPolicy instanceof CompositeTriggeringPolicy);
    final CompositeTriggeringPolicy ctp = (CompositeTriggeringPolicy) triggeringPolicy;
    final TriggeringPolicy[] triggeringPolicies = ctp.getTriggeringPolicies();
    assertEquals(1, triggeringPolicies.length);
    final TriggeringPolicy tp = triggeringPolicies[0];
    assertTrue(tp.getClass().getName(), tp instanceof SizeBasedTriggeringPolicy);
    final SizeBasedTriggeringPolicy sbtp = (SizeBasedTriggeringPolicy) tp;
    assertEquals(256 * 1024 * 1024, sbtp.getMaxFileSize());
    final RolloverStrategy rolloverStrategy = rfa.getManager().getRolloverStrategy();
    assertTrue(rolloverStrategy.getClass().getName(), rolloverStrategy instanceof DefaultRolloverStrategy);
    final DefaultRolloverStrategy drs = (DefaultRolloverStrategy) rolloverStrategy;
    assertEquals(20, drs.getMaxIndex());
    configuration.start();
    configuration.stop();
}
项目:logging-log4j2    文件:Log4j1ConfigurationFactoryTest.java   
private void testDailyRollingFileAppender(final String configResource, final String name, final String filePattern) throws URISyntaxException {
    final Configuration configuration = getConfiguration(configResource);
    final Appender appender = configuration.getAppender(name);
    assertNotNull(appender);
    assertEquals(name, appender.getName());
    assertTrue(appender.getClass().getName(), appender instanceof RollingFileAppender);
    final RollingFileAppender rfa = (RollingFileAppender) appender;
    assertEquals("target/hadoop.log", rfa.getFileName());
    assertEquals(filePattern, rfa.getFilePattern());
    final TriggeringPolicy triggeringPolicy = rfa.getTriggeringPolicy();
    assertNotNull(triggeringPolicy);
    assertTrue(triggeringPolicy.getClass().getName(), triggeringPolicy instanceof CompositeTriggeringPolicy);
    final CompositeTriggeringPolicy ctp = (CompositeTriggeringPolicy) triggeringPolicy;
    final TriggeringPolicy[] triggeringPolicies = ctp.getTriggeringPolicies();
    assertEquals(1, triggeringPolicies.length);
    final TriggeringPolicy tp = triggeringPolicies[0];
    assertTrue(tp.getClass().getName(), tp instanceof TimeBasedTriggeringPolicy);
    final TimeBasedTriggeringPolicy tbtp = (TimeBasedTriggeringPolicy) tp;
    assertEquals(1, tbtp.getInterval());
    final RolloverStrategy rolloverStrategy = rfa.getManager().getRolloverStrategy();
    assertTrue(rolloverStrategy.getClass().getName(), rolloverStrategy instanceof DefaultRolloverStrategy);
    final DefaultRolloverStrategy drs = (DefaultRolloverStrategy) rolloverStrategy;
    assertEquals(Integer.MAX_VALUE, drs.getMaxIndex());
    configuration.start();
    configuration.stop();
}
项目:incubator-servicecomb-java-chassis    文件:Log4J2MetricsFileWriter.java   
@SuppressWarnings("deprecation")
private RollingFileAppender initLogger(String loggerName, String filePrefix) {
  String fileName = Paths.get(rootPath, filePrefix + "." + loggerName + ".dat").toString();
  String filePattern = Paths.get(rootPath, filePrefix + "." + loggerName + "-%i.dat").toString();

  PatternLayout layout = PatternLayout.newBuilder().withPattern(PatternLayout.DEFAULT_CONVERSION_PATTERN).build();
  SizeBasedTriggeringPolicy policy = SizeBasedTriggeringPolicy.createPolicy(maxFileSize);
  DefaultRolloverStrategy strategy = DefaultRolloverStrategy.createStrategy(String.valueOf(maxFileCount),
      null,
      null,
      null,
      null,
      false,
      config);

  //TODO:use RollingFileAppender.newBuilder throw No such static method exception,will improve later!
  return RollingFileAppender
      .createAppender(fileName,
          filePattern,
          "true",
          loggerName,
          "true",
          null,
          "true",
          policy,
          strategy,
          layout,
          null,
          null,
          null,
          null,
          config);
}
项目:HeliosStreams    文件:LoggingWriter.java   
/**
 * Creates a new {@link RollingFileAppender}
 * @param fileName The log file
 * @param loggingConfig The logging config
 * @param layout The layout
 * @param strategy the rollover strategy
 * @param rolledFileFormat The log file roll pattern
 * @param trigger The roll trigger
 * @return the new appender
 */
protected Appender createRollingRandomAccessFileAppender(final String fileName, Configuration loggingConfig, PatternLayout layout,
        final DefaultRolloverStrategy strategy, final String rolledFileFormat, final TriggeringPolicy trigger) {

       RollingRandomAccessFileManager fileManager = RollingRandomAccessFileManager.getRollingRandomAccessFileManager(
            fileName, 
            rolledFileFormat, 
            true, 
            true,
            8192,
            trigger, 
            strategy, 
            null, 
            layout              
            );
       trigger.initialize(fileManager);

    return RollingRandomAccessFileAppender.createAppender(
            fileName,                       // file name
            rolledFileFormat,               // rolled file name pattern
            "true",                         // append
            getClass().getSimpleName(),     // appender name
            "true",                         // immediate flush
            "8192",                         // buffer size              
            trigger,                        // triggering policy
            strategy,                       // rollover strategy
            layout,                         // layout
            null,                           // filter
            "true",                         // ignore exceptions 
            null,                           // advertise
            null,                           // advertise uri
            loggingConfig);                 // config
}
项目:HeliosStreams    文件:LoggingWriter.java   
/**
 * Creates a new {@link RollingFileAppender}
 * @param fileName The log file
 * @param loggingConfig The logging config
 * @param layout The layout
 * @param strategy the rollover strategy
 * @param rolledFileFormat The log file roll pattern
 * @param trigger The roll trigger
 * @return the new appender
 */
protected Appender createRollingFileAppender(final String fileName, Configuration loggingConfig, PatternLayout layout,
        final DefaultRolloverStrategy strategy, final String rolledFileFormat, final TriggeringPolicy trigger) {
       RollingFileManager fileManager = RollingFileManager.getFileManager(
            fileName, 
            rolledFileFormat, 
            false, 
            true,
            trigger, 
            strategy, 
            null, 
            layout, 
            8192,
            true
            );
       trigger.initialize(fileManager);

    return RollingFileAppender.createAppender(
            fileName,                       // file name
            rolledFileFormat,               // rolled file name pattern
            "true",                         // append
            getClass().getSimpleName(),     // appender name
            "true",                         // buffered io
            "8192",                         // buffer size
            "true",                         // immediate flush  
            trigger,                        // triggering policy
            strategy,                       // rollover strategy
            layout,                         // layout
            null,                           // filter
            "true",                         // ignore exceptions 
            null,                           // advertise
            null,                           // advertise uri
            loggingConfig);                 // config
}
项目:log4j-configuration-builder    文件:ConfigurationBuilder.java   
/**
 * Creates a {@link FileAppender}.
 * 
 * @param configuration the owner configuration
 * @param fileName the name of log file
 * @param fileNamePattern the pattern of the name of the log
 *        file
 * @param appenderName the name of the appender
 * @param layout the {@link PatternLayout} to use for the
 *        appender
 * @param rolloverInterval how often the log files should be
 *        rolled over (in DAYS)
 * @param maximumFilesToKeep the maximum number of file to
 *        keep after every roll-over
 * @return an instance of {@link Appender}
 */
protected static Appender createFileAppender(final Configuration configuration,
    final String fileName, final String fileNamePattern, final String appenderName,
    final PatternLayout layout, String rolloverInterval, String maximumFilesToKeep) {
  final String append = Boolean.TRUE.toString();
  final String bufferedIO = Boolean.TRUE.toString();
  final String bufferSizeStr = null;
  final String immediateFlush = Boolean.TRUE.toString();
  final Filter filter = null;
  final String ignore = null;
  final String advertise = null;
  final String advertiseURI = null;

  // Trigger Policy
  final String modulate = Boolean.TRUE.toString();
  final TriggeringPolicy policy =
      TimeBasedTriggeringPolicy.createPolicy(rolloverInterval, modulate);

  // Rollover strategy
  final String minFilesToKeep = "1";
  final String fileIndex = null;
  final String compressionLevelStr = Integer.toString(Deflater.DEFAULT_COMPRESSION);
  final RolloverStrategy rolloverStrategy = DefaultRolloverStrategy.createStrategy(
      maximumFilesToKeep, minFilesToKeep, fileIndex, compressionLevelStr, configuration);

  return RollingFileAppender.createAppender(fileName, fileNamePattern, append, appenderName,
      bufferedIO, bufferSizeStr, immediateFlush, policy, rolloverStrategy, layout, filter, ignore,
      advertise, advertiseURI, configuration);
}
项目:NoMoreOversleeps    文件:Logging.java   
public static void initialize()
{
    // REDIRECT JAVA UTIL LOGGER TO LOG4J2 (MUST BE BEFORE ALL LOG4J2 CALLS)
    System.setProperty("java.util.logging.manager", "org.apache.logging.log4j.jul.LogManager");

    // STARTING CONFIGURATION
    final LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false);
    org.apache.logging.log4j.core.config.Configuration configuration = loggerContext.getConfiguration();
    LoggerConfig rootLogger = configuration.getLoggerConfig("");
    rootLogger.setLevel(Level.ALL);

    // PATTERNS
    PatternLayout consolePattern = PatternLayout.createLayout("%d{yyyy-MM-dd HH:mm:ss} [%level] [%logger{1}]: %msg%n", configuration, null, null, true, false, null, null);
    PatternLayout logfilePattern = PatternLayout.createLayout("%d{yyyy-MM-dd HH:mm:ss} [%level] [%logger]: %msg%n", configuration, null, null, true, false, null, null);

    // LOG FILE STRINGS
    String logName = "NoMoreOversleeps";
    String logFilePrefix = PlatformData.installationDirectory.getAbsolutePath().replace("\\", "/") + "/logs/" + WordUtils.capitalizeFully(logName, new char[] { '_', '-', ' ' }).replaceAll("_", "").replaceAll("_", "").replaceAll("-", "").replaceAll(" ", "");

    // CLIENT LOG FILE APPENDER (ROLLING)
    RollingRandomAccessFileAppender clientInfoLogFile = RollingRandomAccessFileAppender.createAppender(logFilePrefix + "-0.log", logFilePrefix + "-%i.log", null, "InfoFile", null, null, OnStartupTriggeringPolicy.createPolicy(), DefaultRolloverStrategy.createStrategy("2", "1", "min", null, configuration), logfilePattern, null, null, null, null, configuration);
    clientInfoLogFile.start();
    configuration.addAppender(clientInfoLogFile);
    rootLogger.addAppender(clientInfoLogFile, Level.INFO, null);

    /*
    // FINER DETAIL LOG FILE (REPLACED ON EACH RUN)
    RandomAccessFileAppender detailLogFile = RandomAccessFileAppender.createAppender(logFilePrefix + "-latest-fine.log", "false", "DetailFile", null, null, null, logfilePattern, null, null, null, configuration);
    detailLogFile.start();
    configuration.addAppender(detailLogFile);
    rootLogger.addAppender(detailLogFile, Level.ALL, null);
    */

    // CONSOLE APPENDER
    ConsoleAppender console = ConsoleAppender.createAppender(consolePattern, null, "SYSTEM_OUT", "Console", null, null); // must be named "Console" to work correctly
    console.start();
    configuration.addAppender(console);
    rootLogger.addAppender(console, Level.INFO, null);

    // UPDATE LOGGERS
    loggerContext.updateLoggers();

    // REDIRECT STDOUT AND STDERR TO LOG4J2
    System.setOut(new PrintStream(new StdOutErrOutputStream(LogManager.getLogger("java.lang.System.out"), Level.INFO)));
    System.setErr(new PrintStream(new StdOutErrOutputStream(LogManager.getLogger("java.lang.System.err"), Level.ERROR)));

    // set main engine log
    log = LogManager.getLogger();

    // print opening header
    log.info("===============================================================================================================");
    log.info(" NoMoreOversleeps v" + Main.VERSION);
    log.info(" (c) Robert James Dennington, " + Math.max(Calendar.getInstance().get(Calendar.YEAR), minCopyrightYear));
    log.info("===============================================================================================================");
    log.debug("The system log manager is " + System.getProperty("java.util.logging.manager"));
    log.info("Install path: " + PlatformData.installationDirectory.getAbsolutePath());
    log.info("Computer name: " + PlatformData.computerName);
    log.info("Platform: " + PlatformData.platformName);
}
项目:NapBot    文件:Logging.java   
public static void initialize(Application application)
{
    // STORE APPLICATION FOR LATER USE
    Logging.application = application;

    // REDIRECT JAVA UTIL LOGGER TO LOG4J2 (MUST BE BEFORE ALL LOG4J2 CALLS)
    System.setProperty("java.util.logging.manager", "org.apache.logging.log4j.jul.LogManager");

    // STARTING CONFIGURATION
    final LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false);
    org.apache.logging.log4j.core.config.Configuration configuration = loggerContext.getConfiguration();
    LoggerConfig rootLogger = configuration.getLoggerConfig("");
    rootLogger.setLevel(Level.ALL);

    // PATTERNS
    PatternLayout consolePattern = PatternLayout.createLayout("%d{yyyy-MM-dd HH:mm:ss} [%level] [%logger{1}]: %msg%n", null, configuration, null, null, true, false, null, null);
    PatternLayout logfilePattern = PatternLayout.createLayout("%d{yyyy-MM-dd HH:mm:ss} [%level] [%logger]: %msg%n", null, configuration, null, null, true, false, null, null);

    // LOG FILE STRINGS
    String logFilePrefix = PlatformData.installationDirectory.getAbsolutePath().replace("\\", "/") + "/logs/" + WordUtils.capitalizeFully(application.getName(), new char[] { '_', '-', ' ' }).replaceAll("_", "").replaceAll("_", "").replaceAll("-", "").replaceAll(" ", "");

    // CLIENT LOG FILE APPENDER (ROLLING)
    RollingRandomAccessFileAppender clientInfoLogFile = RollingRandomAccessFileAppender.createAppender(logFilePrefix + "-0.log", logFilePrefix + "-%i.log", null, "InfoFile", null, null, OnStartupTriggeringPolicy.createPolicy(), DefaultRolloverStrategy.createStrategy("2", "1", "min", null, null, false, configuration), logfilePattern, null, null, null, null, configuration);
    clientInfoLogFile.start();
    configuration.addAppender(clientInfoLogFile);
    rootLogger.addAppender(clientInfoLogFile, Level.INFO, null);

    // FINER DETAIL LOG FILE (REPLACED ON EACH RUN)
    RandomAccessFileAppender detailLogFile = RandomAccessFileAppender.createAppender(logFilePrefix + "-latest-fine.log", "false", "DetailFile", null, null, null, logfilePattern, null, null, null, configuration);
    detailLogFile.start();
    configuration.addAppender(detailLogFile);
    rootLogger.addAppender(detailLogFile, Level.ALL, null);

    // CONSOLE APPENDER
    ConsoleAppender console = ConsoleAppender.createAppender(consolePattern, null, Target.SYSTEM_OUT, "Console", false, true); // must be named "Console" to work correctly
    console.start();
    configuration.addAppender(console);
    rootLogger.addAppender(console, Level.INFO, null);

    // UPDATE LOGGERS
    loggerContext.updateLoggers();

    // REDIRECT STDOUT AND STDERR TO LOG4J2
    System.setOut(new PrintStream(new StdOutErrOutputStream(LogManager.getLogger("java.lang.System.out"), Level.INFO)));
    System.setErr(new PrintStream(new StdOutErrOutputStream(LogManager.getLogger("java.lang.System.err"), Level.ERROR)));

    // set main engine log
    log = LogManager.getLogger();

    // print opening header
    log.info("===============================================================================================================");
    log.info(" " + application.getName() + " v" + application.getVersion());
    log.info(" (c) Robert James Dennington, " + Math.max(Calendar.getInstance().get(Calendar.YEAR), minCopyrightYear));
    log.info("===============================================================================================================");
    log.debug("The system log manager is " + System.getProperty("java.util.logging.manager"));
    log.info("Install path: " + PlatformData.installationDirectory.getAbsolutePath());
    log.info("Computer name: " + PlatformData.computerName);
    log.info("Platform: " + PlatformData.platformName);
}
项目:HeliosStreams    文件:LoggingWriter.java   
/**
     * {@inheritDoc}
     * @see com.heliosapm.streams.tracing.AbstractMetricWriter#configure(java.util.Properties)
     */
    @Override
    public void configure(final Properties config) {                
        super.configure(config);
        final String loggerName = ConfigurationHelper.getSystemThenEnvProperty(CONFIG_LOGGER_NAME, null, config);

        if(loggerName==null || !LogManager.getContext(true).hasLogger(loggerName)) {
            /* 
             * ===================================================
             * FIXME:  this is super ugly
             * ===================================================
             * TODO:
             *  - log4j2 async appender
             *  - low gc message objects
             */
            final String entryPrefix = ConfigurationHelper.getSystemThenEnvProperty(CONFIG_ENTRY_PREFIX, DEFAULT_ENTRY_PREFIX, config);
            this.config.put("entryPrefix", entryPrefix);
            final String entrySuffix = ConfigurationHelper.getSystemThenEnvProperty(CONFIG_ENTRY_SUFFIX, DEFAULT_ENTRY_SUFFIX, config);
            this.config.put("entrySuffix", entrySuffix);
            final boolean randomAccessFile = ConfigurationHelper.getBooleanSystemThenEnvProperty(CONFIG_RA_FILE, DEFAULT_RA_FILE, config);
            this.config.put("randomAccessFile", randomAccessFile);
            final String fileName = ConfigurationHelper.getSystemThenEnvProperty(CONFIG_FILE_NAME, DEFAULT_FILE_NAME, config);
            this.config.put("fileName", fileName);
            final File file = new File(fileName);
            final File dir = file.getParentFile();
            if(dir.exists()) {
                if(!dir.isDirectory()) throw new IllegalArgumentException("The logging directory is a file [" + dir + "]");
            } else {
                if(!dir.mkdirs()) throw new IllegalArgumentException("Cannot create the logging directory [" + dir + "]");
            }
            LoggerContext context= (LoggerContext) LogManager.getContext();
            Configuration loggingConfig = context.getConfiguration();
            PatternLayout layout= PatternLayout.createLayout(entryPrefix + "%m" + entrySuffix + "%n" , null, loggingConfig, null, UTF8, false, false, null, null);


            final DefaultRolloverStrategy strategy = DefaultRolloverStrategy.createStrategy("10", "1", null, null, null, true, loggingConfig);
//          final int lastIndex = fileName.lastIndexOf('.');
            final String format = ConfigurationHelper.getSystemThenEnvProperty(CONFIG_ROLL_PATTERN, DEFAULT_ROLL_PATTERN, config);
            this.config.put("format", format);
            final StringBuilder b = new StringBuilder(fileName).append(format);
//          if(lastIndex==-1) {
//              b.append(".").append(format);
//          } else {
//              b.insert(lastIndex, format);
//          }
            final String rolledFileFormat = b.toString();
            final TriggeringPolicy trigger = TimeBasedTriggeringPolicy.createPolicy("1", "true");

            if(randomAccessFile) {
                appender = createRollingRandomAccessFileAppender(fileName, loggingConfig, layout, strategy, rolledFileFormat, trigger);
            } else {
                appender = createRollingFileAppender(fileName, loggingConfig, layout, strategy, rolledFileFormat, trigger);
            }
            loggingConfig.addAppender(appender);
            AppenderRef ref = AppenderRef.createAppenderRef(getClass().getSimpleName(), Level.INFO, null);
            AppenderRef[] refs = new AppenderRef[] { ref };
            LoggerConfig loggerConfig = LoggerConfig.createLogger(
                    false, 
                    Level.INFO, 
                    getClass().getSimpleName() + "Logger",  
                    "false", refs, null, loggingConfig, null);
            loggerConfig.addAppender(appender, Level.INFO, null);
            loggingConfig.addLogger(getClass().getSimpleName() + "Logger", loggerConfig);
            context.updateLoggers();            
            org.apache.logging.log4j.core.Logger xlogger =  context.getLogger(getClass().getName() + "Logger");
            for(Appender app: xlogger.getAppenders().values()) {
                xlogger.removeAppender(app);
            }
            xlogger.addAppender(appender);
            metricLog = context.getLogger(getClass().getName() + "Logger");
        } else {
            metricLog = LogManager.getLogger(loggerName);
        }
    }
项目:log4j2    文件:RollingFileAppender.java   
/**
 * Create a RollingFileAppender.
 * @param fileName The name of the file that is actively written to. (required).
 * @param filePattern The pattern of the file name to use on rollover. (required).
 * @param append If true, events are appended to the file. If false, the file
 * is overwritten when opened. Defaults to "true"
 * @param name The name of the Appender (required).
 * @param bufferedIO When true, I/O will be buffered. Defaults to "true".
 * @param immediateFlush When true, events are immediately flushed. Defaults to "true".
 * @param policy The triggering policy. (required).
 * @param strategy The rollover strategy. Defaults to DefaultRolloverStrategy.
 * @param layout The layout to use (defaults to the default PatternLayout).
 * @param filter The Filter or null.
 * @param ignore If {@code "true"} (default) exceptions encountered when appending events are logged; otherwise
 *               they are propagated to the caller.
 * @param advertise "true" if the appender configuration should be advertised, "false" otherwise.
 * @param advertiseURI The advertised URI which can be used to retrieve the file contents.
 * @param config The Configuration.
 * @return A RollingFileAppender.
 */
@PluginFactory
public static RollingFileAppender createAppender(
        @PluginAttribute("fileName") final String fileName,
        @PluginAttribute("filePattern") final String filePattern,
        @PluginAttribute("append") final String append,
        @PluginAttribute("name") final String name,
        @PluginAttribute("bufferedIO") final String bufferedIO,
        @PluginAttribute("immediateFlush") final String immediateFlush,
        @PluginElement("Policy") final TriggeringPolicy policy,
        @PluginElement("Strategy") RolloverStrategy strategy,
        @PluginElement("Layout") Layout<? extends Serializable> layout,
        @PluginElement("Filter") final Filter filter,
        @PluginAttribute("ignoreExceptions") final String ignore,
        @PluginAttribute("advertise") final String advertise,
        @PluginAttribute("advertiseURI") final String advertiseURI,
        @PluginConfiguration final Configuration config) {

    final boolean isAppend = Booleans.parseBoolean(append, true);
    final boolean ignoreExceptions = Booleans.parseBoolean(ignore, true);
    final boolean isBuffered = Booleans.parseBoolean(bufferedIO, true);
    final boolean isFlush = Booleans.parseBoolean(immediateFlush, true);
    final boolean isAdvertise = Boolean.parseBoolean(advertise);
    if (name == null) {
        LOGGER.error("No name provided for FileAppender");
        return null;
    }

    if (fileName == null) {
        LOGGER.error("No filename was provided for FileAppender with name "  + name);
        return null;
    }

    if (filePattern == null) {
        LOGGER.error("No filename pattern provided for FileAppender with name "  + name);
        return null;
    }

    if (policy == null) {
        LOGGER.error("A TriggeringPolicy must be provided");
        return null;
    }

    if (strategy == null) {
        strategy = DefaultRolloverStrategy.createStrategy(null, null, null,
                String.valueOf(Deflater.DEFAULT_COMPRESSION), config);
    }

    if (layout == null) {
        layout = PatternLayout.createLayout(null, null, null, null, null);
    }

    final RollingFileManager manager = RollingFileManager.getFileManager(fileName, filePattern, isAppend,
        isBuffered, policy, strategy, advertiseURI, layout);
    if (manager == null) {
        return null;
    }

    return new RollingFileAppender(name, layout, filter, manager, fileName, filePattern,
            ignoreExceptions, isFlush, isAdvertise ? config.getAdvertiser() : null);
}
项目:logging-log4j2    文件:RollingFileAppender.java   
@Override
public RollingFileAppender build() {
    // Even though some variables may be annotated with @Required, we must still perform validation here for
    // call sites that build builders programmatically.
    final boolean isBufferedIo = isBufferedIo();
    final int bufferSize = getBufferSize();
    if (getName() == null) {
        LOGGER.error("RollingFileAppender '{}': No name provided.", getName());
        return null;
    }

    if (!isBufferedIo && bufferSize > 0) {
        LOGGER.warn("RollingFileAppender '{}': The bufferSize is set to {} but bufferedIO is not true", getName(), bufferSize);
    }

    if (filePattern == null) {
        LOGGER.error("RollingFileAppender '{}': No file name pattern provided.", getName());
        return null;
    }

    if (policy == null) {
        LOGGER.error("RollingFileAppender '{}': No TriggeringPolicy provided.", getName());
        return null;
    }

    if (strategy == null) {
        if (fileName != null) {
            strategy = DefaultRolloverStrategy.newBuilder()
                                .withCompressionLevelStr(String.valueOf(Deflater.DEFAULT_COMPRESSION))
                                .withConfig(getConfiguration())
                                .build();
        } else {
            strategy = DirectWriteRolloverStrategy.newBuilder()
                                .withCompressionLevelStr(String.valueOf(Deflater.DEFAULT_COMPRESSION))
                                .withConfig(getConfiguration())
                                .build();
        }
    } else if (fileName == null && !(strategy instanceof DirectFileRolloverStrategy)) {
        LOGGER.error("RollingFileAppender '{}': When no file name is provided a DirectFilenameRolloverStrategy must be configured");
        return null;
    }

    final Layout<? extends Serializable> layout = getOrCreateLayout();
    final RollingFileManager manager = RollingFileManager.getFileManager(fileName, filePattern, append,
            isBufferedIo, policy, strategy, advertiseUri, layout, bufferSize, isImmediateFlush(),
            createOnDemand, filePermissions, fileOwner, fileGroup, getConfiguration());
    if (manager == null) {
        return null;
    }

    manager.initialize();

    return new RollingFileAppender(getName(), layout, getFilter(), manager, fileName, filePattern,
            isIgnoreExceptions(), isImmediateFlush(), advertise ? getConfiguration().getAdvertiser() : null);
}
项目:logging-log4j2    文件:RollingRandomAccessFileAppender.java   
@Override
public RollingRandomAccessFileAppender build() {
    final String name = getName();
    if (name == null) {
        LOGGER.error("No name provided for FileAppender");
        return null;
    }

    if (strategy == null) {
        if (fileName != null) {
            strategy = DefaultRolloverStrategy.newBuilder()
                    .withCompressionLevelStr(String.valueOf(Deflater.DEFAULT_COMPRESSION))
                    .withConfig(getConfiguration())
                    .build();
        } else {
            strategy = DirectWriteRolloverStrategy.newBuilder()
                    .withCompressionLevelStr(String.valueOf(Deflater.DEFAULT_COMPRESSION))
                    .withConfig(getConfiguration())
                    .build();
        }
    } else if (fileName == null && !(strategy instanceof DirectFileRolloverStrategy)) {
        LOGGER.error("RollingFileAppender '{}': When no file name is provided a DirectFilenameRolloverStrategy must be configured");
        return null;
    }

    if (filePattern == null) {
        LOGGER.error("No filename pattern provided for FileAppender with name " + name);
        return null;
    }

    if (policy == null) {
        LOGGER.error("A TriggeringPolicy must be provided");
        return null;
    }

    final Layout<? extends Serializable> layout = getOrCreateLayout();

    final boolean immediateFlush = isImmediateFlush();
    final int bufferSize = getBufferSize();
    final RollingRandomAccessFileManager manager = RollingRandomAccessFileManager
            .getRollingRandomAccessFileManager(fileName, filePattern, append, immediateFlush, bufferSize, policy,
                    strategy, advertiseURI, layout,
                    filePermissions, fileOwner, fileGroup, getConfiguration());
    if (manager == null) {
        return null;
    }

    manager.initialize();

    return new RollingRandomAccessFileAppender(name, layout,getFilter(), manager, fileName, filePattern,
            isIgnoreExceptions(), immediateFlush, bufferSize, advertise ? getConfiguration().getAdvertiser() : null);
}