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(); }
/** * 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); }
/** * {@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); } }
@SuppressWarnings({ "rawtypes", "unchecked" }) public static synchronized void init() { final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); Layout layout = PatternLayout.newBuilder().withPattern("%d{yyyy-MM-dd HH:mm:ss}:%p %t %c - %m%n") .withConfiguration(config).withRegexReplacement(null).withCharset(null).withAlwaysWriteExceptions(true) .withNoConsoleNoAnsi(false).withHeader(null).withFooter(null).build(); // file info Filter fileInfoFilter = ThresholdFilter.createFilter(Level.ERROR, Result.DENY, Result.ACCEPT); Appender fileInfoAppender = RollingFileAppender.createAppender(LOG_ROOT + "/zebra.log", LOG_ROOT + "/zebra.log.%d{yyyy-MM-dd}.gz", "true", "FileInfo", "true", "4000", "true", TimeBasedTriggeringPolicy.createPolicy("1", "true"), ZebraRolloverStrategy.createStrategy("30", "1", null, Deflater.DEFAULT_COMPRESSION + "", config), layout, fileInfoFilter, "false", null, null, config); config.addAppender(fileInfoAppender); fileInfoAppender.start(); AppenderRef fileInfoRef = AppenderRef.createAppenderRef("FileInfo", null, fileInfoFilter); // console error Appender consoleErrorAppender = ConsoleAppender.createAppender(layout, null, "SYSTEM_ERR", "ConsoleError", "false", "false"); config.addAppender(consoleErrorAppender); consoleErrorAppender.start(); // console info Filter consoleWarnFilter = ThresholdFilter.createFilter(Level.ERROR, Result.DENY, Result.NEUTRAL); Appender consoleWarnAppender = ConsoleAppender.createAppender(layout, consoleWarnFilter, "SYSTEM_OUT", "ConsoleWarn", "false", "false"); config.addAppender(consoleWarnAppender); consoleWarnAppender.start(); AppenderRef consoleWarnAppenderRef = AppenderRef.createAppenderRef("ConsoleWarn", Level.WARN, consoleWarnFilter); AppenderRef consoleErrorAppenderRef = AppenderRef.createAppenderRef("ConsoleError", Level.WARN, null); AppenderRef[] refs = new AppenderRef[] { consoleErrorAppenderRef, consoleWarnAppenderRef, fileInfoRef }; LoggerConfig loggerConfig = LoggerConfig.createLogger("false", Level.INFO, "com.dianping.zebra", "true", refs, null, config, null); loggerConfig.addAppender(consoleErrorAppender, Level.ERROR, null); loggerConfig.addAppender(consoleWarnAppender, Level.INFO, null); loggerConfig.addAppender(fileInfoAppender, Level.INFO, null); config.addLogger("com.dianping.zebra", loggerConfig); ctx.updateLoggers(); context = ctx; }