org.apache.logging.log4j.core.filter.ThresholdFilter Java Examples

The following examples show how to use org.apache.logging.log4j.core.filter.ThresholdFilter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Log4j2Watcher.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public void registerListener(ListenerConfig cfg) {
  if (history != null)
    throw new IllegalStateException("History already registered");

  history = new CircularList<LogEvent>(cfg.size);

  Level threshold = (cfg.threshold != null) ? Level.toLevel(cfg.threshold) : Level.WARN;
  ThresholdFilter filter = ThresholdFilter.createFilter(threshold, Filter.Result.ACCEPT, Filter.Result.DENY);

  // If there's already an appender like this, remove it
  LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
  LoggerConfig config = getLoggerConfig(ctx, LoggerInfo.ROOT_NAME);

  appender = new Log4j2Appender(this, filter, threshold); // "Log4j2WatcherAppender"

  config.removeAppender(appender.getName());

  if (!appender.isStarted())
    appender.start();

  config.addAppender(appender, threshold, filter);
  ctx.updateLoggers();
}
 
Example #2
Source File: CustomLevelsWithFiltersTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testConfiguration() {
    final Configuration configuration = context.getConfiguration();
    assertNotNull(configuration);
    final FileAppender appender = configuration.getAppender("info");
    assertNotNull(appender);
    final CompositeFilter compFilter = (CompositeFilter) appender.getFilter();
    assertNotNull(compFilter);
    final Filter[] filters = compFilter.getFiltersArray();
    assertNotNull(filters);
    boolean foundLevel = false;
    for (final Filter filter : filters) {
        final ThresholdFilter tFilter = (ThresholdFilter) filter;
        if (infom1Level.equals(tFilter.getLevel())) {
            foundLevel = true;
            break;
        }
    }
    Assert.assertTrue("Level not found: " + infom1Level, foundLevel);
}
 
Example #3
Source File: PropertiesConfigurationTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testPropertiesConfiguration() {
    final Configuration config = context.getConfiguration();
    assertNotNull("No configuration created", config);
    assertEquals("Incorrect State: " + config.getState(), config.getState(), LifeCycle.State.STARTED);
    final Map<String, Appender> appenders = config.getAppenders();
    assertNotNull(appenders);
    assertTrue("Incorrect number of Appenders: " + appenders.size(), appenders.size() == 1);
    final Map<String, LoggerConfig> loggers = config.getLoggers();
    assertNotNull(loggers);
    assertTrue("Incorrect number of LoggerConfigs: " + loggers.size(), loggers.size() == 2);
    final Filter filter = config.getFilter();
    assertNotNull("No Filter", filter);
    assertTrue("Not a Threshold Filter", filter instanceof ThresholdFilter);
    final Logger logger = LogManager.getLogger(getClass());
    logger.info("Welcome to Log4j!");
}
 
Example #4
Source File: PropertiesConfigurationRootLoggerOnlyTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testPropertiesConfiguration() {
    final Configuration config = context.getConfiguration();
    assertNotNull("No configuration created", config);
    assertEquals("Incorrect State: " + config.getState(), config.getState(), LifeCycle.State.STARTED);
    final Map<String, Appender> appenders = config.getAppenders();
    assertNotNull(appenders);
    assertTrue("Incorrect number of Appenders: " + appenders.size(), appenders.size() == 1);
    final Map<String, LoggerConfig> loggers = config.getLoggers();
    assertNotNull(loggers);
    assertTrue("Incorrect number of LoggerConfigs: " + loggers.size(), loggers.size() == 1);
    final Filter filter = config.getFilter();
    assertNotNull("No Filter", filter);
    assertTrue("Not a Threshold Filter", filter instanceof ThresholdFilter);
    final Logger logger = LogManager.getLogger(getClass());
    logger.info("Welcome to Log4j!");
}
 
Example #5
Source File: PropertiesConfigurationTrailingSpaceOnLevelTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testPropertiesConfiguration() {
    final Configuration config = context.getConfiguration();
    assertNotNull("No configuration created", config);
    assertEquals("Incorrect State: " + config.getState(), config.getState(), LifeCycle.State.STARTED);
    final Map<String, Appender> appenders = config.getAppenders();
    assertNotNull(appenders);
    assertTrue("Incorrect number of Appenders: " + appenders.size(), appenders.size() == 1);
    final Map<String, LoggerConfig> loggers = config.getLoggers();
    assertNotNull(loggers);
    assertTrue("Incorrect number of LoggerConfigs: " + loggers.size(), loggers.size() == 2);
    final Filter filter = config.getFilter();
    assertNotNull("No Filter", filter);
    assertTrue("Not a Threshold Filter", filter instanceof ThresholdFilter);
    final Logger logger = LogManager.getLogger(getClass());

    assertEquals("Incorrect level " + logger.getLevel(), Level.DEBUG, logger.getLevel());

    logger.debug("Welcome to Log4j!");
}
 
Example #6
Source File: RollingFilePropertiesTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testPropertiesConfiguration() {
    final Configuration config = context.getConfiguration();
    assertNotNull("No configuration created", config);
    assertEquals("Incorrect State: " + config.getState(), config.getState(), LifeCycle.State.STARTED);
    final Map<String, Appender> appenders = config.getAppenders();
    assertNotNull(appenders);
    assertTrue("Incorrect number of Appenders: " + appenders.size(), appenders.size() == 3);
    final Map<String, LoggerConfig> loggers = config.getLoggers();
    assertNotNull(loggers);
    assertTrue("Incorrect number of LoggerConfigs: " + loggers.size(), loggers.size() == 2);
    final Filter filter = config.getFilter();
    assertNotNull("No Filter", filter);
    assertTrue("Not a Threshold Filter", filter instanceof ThresholdFilter);
    final Logger logger = LogManager.getLogger(getClass());
    logger.info("Welcome to Log4j!");
}
 
Example #7
Source File: ElasticsearchAppenderTest.java    From log4j2-elasticsearch with Apache License 2.0 5 votes vote down vote up
public static Builder createTestElasticsearchAppenderBuilder(AbstractLayout layout) {
    Builder builder = ElasticsearchAppender.newBuilder()
            .withName(TEST_APPENDER_NAME)
            .withFilter(ThresholdFilter.createFilter(Level.INFO, Filter.Result.ACCEPT, Filter.Result.DENY))
            .withIgnoreExceptions(false)
            .withBatchDelivery(mock(AsyncBatchDelivery.class))
            .withMessageOnly(false)
            .withLayout(layout);

    IndexNameFormatter indexNameFormatter = mock(IndexNameFormatter.class);
    when(indexNameFormatter.format(any(LogEvent.class))).thenReturn("testIndexName");
    builder.withIndexNameFormatter(indexNameFormatter);
    return builder;
}
 
Example #8
Source File: ConfigurationAssemblerTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
private void validate(final Configuration config) {
    assertNotNull(config);
    assertNotNull(config.getName());
    assertFalse(config.getName().isEmpty());
    assertNotNull(config, "No configuration created");
    assertEquals("Incorrect State: " + config.getState(), config.getState(), LifeCycle.State.STARTED);
    final Map<String, Appender> appenders = config.getAppenders();
    assertNotNull(appenders);
    assertEquals("Incorrect number of Appenders: " + appenders.size(), appenders.size(), 2);
    final PulsarAppender pulsarAppender = (PulsarAppender) appenders.get("Pulsar");
    final GelfLayout gelfLayout = (GelfLayout) pulsarAppender.getLayout();
    final Map<String, LoggerConfig> loggers = config.getLoggers();
    assertNotNull(loggers);
    assertEquals("Incorrect number of LoggerConfigs: " + loggers.size(), loggers.size(), 2);
    final LoggerConfig rootLoggerConfig = loggers.get("");
    assertEquals(Level.ERROR, rootLoggerConfig.getLevel());
    assertFalse(rootLoggerConfig.isIncludeLocation());
    final LoggerConfig loggerConfig = loggers.get("org.apache.logging.log4j");
    assertEquals(Level.DEBUG, loggerConfig.getLevel());
    assertTrue(loggerConfig.isIncludeLocation());
    final Filter filter = config.getFilter();
    assertNotNull(filter, "No Filter");
    assertTrue("Not a Threshold Filter", filter instanceof ThresholdFilter);
    final List<CustomLevelConfig> customLevels = config.getCustomLevels();
    assertNotNull(filter, "No CustomLevels");
    assertEquals(1, customLevels.size());
    final CustomLevelConfig customLevel = customLevels.get(0);
    assertEquals("Panic", customLevel.getLevelName());
    assertEquals(17, customLevel.getIntLevel());
    final Logger logger = LogManager.getLogger(getClass());
    logger.info("Welcome to Log4j!");
}
 
Example #9
Source File: SmtpAppender.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public SmtpAppender build() {
    if (getLayout() == null) {
        setLayout(HtmlLayout.createDefaultLayout());
    }
    if (getFilter() == null) {
        setFilter(ThresholdFilter.createFilter(null, null, null));
    }
    final SmtpManager smtpManager = SmtpManager.getSmtpManager(getConfiguration(), to, cc, bcc, from, replyTo,
            subject, smtpProtocol, smtpHost, smtpPort, smtpUsername, smtpPassword, smtpDebug,
            getFilter().toString(), bufferSize, sslConfiguration);
    return new SmtpAppender(getName(), getFilter(), getLayout(), isIgnoreExceptions(), getPropertyArray(), smtpManager);
}
 
Example #10
Source File: SmtpAppender.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Create a SmtpAppender.
 * @deprecated Use {@link #newBuilder()} to create and configure a {@link Builder} instance.
 * @see Builder
 */
public static SmtpAppender createAppender(final Configuration config, final String name, final String to,
                                          final String cc, final String bcc, final String from,
                                          final String replyTo, final String subject, final String smtpProtocol,
                                          final String smtpHost, final String smtpPortStr,
                                          final String smtpUsername, final String smtpPassword,
                                          final String smtpDebug, final String bufferSizeStr,
                                          Layout<? extends Serializable> layout, Filter filter,
                                          final String ignore) {
    if (name == null) {
        LOGGER.error("No name provided for SmtpAppender");
        return null;
    }

    final boolean ignoreExceptions = Booleans.parseBoolean(ignore, true);
    final int smtpPort = AbstractAppender.parseInt(smtpPortStr, 0);
    final boolean isSmtpDebug = Boolean.parseBoolean(smtpDebug);
    final int bufferSize = bufferSizeStr == null ? DEFAULT_BUFFER_SIZE : Integer.parseInt(bufferSizeStr);

    if (layout == null) {
        layout = HtmlLayout.createDefaultLayout();
    }
    if (filter == null) {
        filter = ThresholdFilter.createFilter(null, null, null);
    }
    final Configuration configuration = config != null ? config : new DefaultConfiguration();

    final SmtpManager manager = SmtpManager.getSmtpManager(configuration, to, cc, bcc, from, replyTo, subject, smtpProtocol,
        smtpHost, smtpPort, smtpUsername, smtpPassword, isSmtpDebug, filter.toString(),  bufferSize, null);
    if (manager == null) {
        return null;
    }

    return new SmtpAppender(name, filter, layout, ignoreExceptions, Property.EMPTY_ARRAY, manager);
}
 
Example #11
Source File: AbstractBuilder.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
protected org.apache.logging.log4j.core.Filter buildFilters(String level, Filter filter) {
    if (level != null && filter != null) {
        List<org.apache.logging.log4j.core.Filter> filterList = new ArrayList<>();
        org.apache.logging.log4j.core.Filter thresholdFilter =
                ThresholdFilter.createFilter(OptionConverter.convertLevel(level, Level.TRACE),
                        org.apache.logging.log4j.core.Filter.Result.NEUTRAL,
                        org.apache.logging.log4j.core.Filter.Result.DENY);
        filterList.add(thresholdFilter);
        Filter f = filter;
        while (f != null) {
            if (filter instanceof FilterWrapper) {
                filterList.add(((FilterWrapper) f).getFilter());
            } else {
                filterList.add(new FilterAdapter(f));
            }
            f = f.next;
        }
        return CompositeFilter.createFilters(filterList.toArray(new org.apache.logging.log4j.core.Filter[0]));
    } else if (level != null) {
        return ThresholdFilter.createFilter(OptionConverter.convertLevel(level, Level.TRACE),
                org.apache.logging.log4j.core.Filter.Result.NEUTRAL,
                org.apache.logging.log4j.core.Filter.Result.DENY);
    } else if (filter != null) {
        if (filter instanceof FilterWrapper) {
            return ((FilterWrapper) filter).getFilter();
        } else {
            return new FilterAdapter(filter);
        }
    }
    return null;
}
 
Example #12
Source File: ConfigurationAssemblerTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private void validate(final Configuration config) {
    assertNotNull(config);
    assertNotNull(config.getName());
    assertFalse(config.getName().isEmpty());
    assertNotNull("No configuration created", config);
    assertEquals("Incorrect State: " + config.getState(), config.getState(), LifeCycle.State.STARTED);
    final Map<String, Appender> appenders = config.getAppenders();
    assertNotNull(appenders);
    assertTrue("Incorrect number of Appenders: " + appenders.size(), appenders.size() == 2);
    final KafkaAppender kafkaAppender = (KafkaAppender) appenders.get("Kafka");
    final GelfLayout gelfLayout = (GelfLayout) kafkaAppender.getLayout();
    final Map<String, LoggerConfig> loggers = config.getLoggers();
    assertNotNull(loggers);
    assertTrue("Incorrect number of LoggerConfigs: " + loggers.size(), loggers.size() == 2);
    final LoggerConfig rootLoggerConfig = loggers.get("");
    assertEquals(Level.ERROR, rootLoggerConfig.getLevel());
    assertFalse(rootLoggerConfig.isIncludeLocation());
    final LoggerConfig loggerConfig = loggers.get("org.apache.logging.log4j");
    assertEquals(Level.DEBUG, loggerConfig.getLevel());
    assertTrue(loggerConfig.isIncludeLocation());
    final Filter filter = config.getFilter();
    assertNotNull("No Filter", filter);
    assertTrue("Not a Threshold Filter", filter instanceof ThresholdFilter);
    final List<CustomLevelConfig> customLevels = config.getCustomLevels();
    assertNotNull("No CustomLevels", filter);
    assertEquals(1, customLevels.size());
    final CustomLevelConfig customLevel = customLevels.get(0);
    assertEquals("Panic", customLevel.getLevelName());
    assertEquals(17, customLevel.getIntLevel());
    final Logger logger = LogManager.getLogger(getClass());
    logger.info("Welcome to Log4j!");
}
 
Example #13
Source File: ConfigurationAssemblerTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private void validate(final Configuration config) {
    assertNotNull(config);
    assertNotNull(config.getName());
    assertFalse(config.getName().isEmpty());
    assertNotNull("No configuration created", config);
    assertEquals("Incorrect State: " + config.getState(), config.getState(), LifeCycle.State.STARTED);
    final Map<String, Appender> appenders = config.getAppenders();
    assertNotNull(appenders);
    assertTrue("Incorrect number of Appenders: " + appenders.size(), appenders.size() == 1);
    final ConsoleAppender consoleAppender = (ConsoleAppender)appenders.get("Stdout");
    final PatternLayout gelfLayout = (PatternLayout)consoleAppender.getLayout();
    final Map<String, LoggerConfig> loggers = config.getLoggers();
    assertNotNull(loggers);
    assertTrue("Incorrect number of LoggerConfigs: " + loggers.size(), loggers.size() == 2);
    final LoggerConfig rootLoggerConfig = loggers.get("");
    assertEquals(Level.ERROR, rootLoggerConfig.getLevel());
    assertFalse(rootLoggerConfig.isIncludeLocation());
    final LoggerConfig loggerConfig = loggers.get("org.apache.logging.log4j");
    assertEquals(Level.DEBUG, loggerConfig.getLevel());
    assertTrue(loggerConfig.isIncludeLocation());
    final Filter filter = config.getFilter();
    assertNotNull("No Filter", filter);
    assertTrue("Not a Threshold Filter", filter instanceof ThresholdFilter);
    final List<CustomLevelConfig> customLevels = config.getCustomLevels();
    assertNotNull("No CustomLevels", filter);
    assertEquals(1, customLevels.size());
    final CustomLevelConfig customLevel = customLevels.get(0);
    assertEquals("Panic", customLevel.getLevelName());
    assertEquals(17, customLevel.getIntLevel());
    final Logger logger = LogManager.getLogger(getClass());
    logger.info("Welcome to Log4j!");
}
 
Example #14
Source File: Log4j2Watcher.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
Log4j2Appender(Log4j2Watcher watcher, ThresholdFilter filter, Level threshold) {
  super(LOG4J2_WATCHER_APPENDER, filter, null);
  this.watcher = watcher;
  this.filter = filter;
  this.threshold = threshold;
}
 
Example #15
Source File: Log4j2Watcher.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
public void setThreshold(Level threshold) {
  this.threshold = threshold;
  removeFilter(filter);
  filter = ThresholdFilter.createFilter(threshold, Filter.Result.ACCEPT, Filter.Result.DENY);
  addFilter(filter);
}
 
Example #16
Source File: LoggerLoader.java    From Zebra with Apache License 2.0 4 votes vote down vote up
@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;
}