org.apache.logging.log4j.core.Filter Java Examples

The following examples show how to use org.apache.logging.log4j.core.Filter. 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: AppenderAdapter.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor.
 */
public AppenderAdapter(Appender appender) {
    this.appender = appender;
    org.apache.logging.log4j.core.Filter appenderFilter = null;
    if (appender.getFilter() != null) {
        if (appender.getFilter().getNext() != null) {
            org.apache.log4j.spi.Filter filter = appender.getFilter();
            List<org.apache.logging.log4j.core.Filter> filters = new ArrayList<>();
            while (filter != null) {
                filters.add(new FilterAdapter(filter));
                filter = filter.getNext();
            }
            appenderFilter = CompositeFilter.createFilters(filters.toArray(new Filter[0]));
        } else {
            appenderFilter = new FilterAdapter(appender.getFilter());
        }
    }
    this.adapter = new Adapter(appender.getName(), appenderFilter, null, true, null);
}
 
Example #2
Source File: LevelRangeFilterTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testLevels() {
    final LevelRangeFilter filter = LevelRangeFilter.createFilter(Level.ERROR, Level.INFO, null, null);
    filter.start();
    assertTrue(filter.isStarted());
    assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (Object) null, (Throwable) null));
    assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.ERROR, null, (Object) null, (Throwable) null));
    LogEvent event = Log4jLogEvent.newBuilder() //
            .setLevel(Level.DEBUG) //
            .setMessage(new SimpleMessage("Test")) //
            .build();
    assertSame(Filter.Result.DENY, filter.filter(event));
    event = Log4jLogEvent.newBuilder() //
            .setLevel(Level.ERROR) //
            .setMessage(new SimpleMessage("Test")) //
            .build();
    assertSame(Filter.Result.NEUTRAL, filter.filter(event));
}
 
Example #3
Source File: RocketmqLog4j2Appender.java    From rocketmq-read with Apache License 2.0 6 votes vote down vote up
protected RocketmqLog4j2Appender(String name, Filter filter, Layout<? extends Serializable> layout,
    boolean ignoreExceptions, String nameServerAddress, String producerGroup,
    String topic, String tag) {
    super(name, filter, layout, ignoreExceptions);
    this.producer = producer;
    this.topic = topic;
    this.tag = tag;
    this.nameServerAddress = nameServerAddress;
    this.producerGroup = producerGroup;
    try {
        this.producer = ProducerInstance.getProducerInstance().getInstance(this.nameServerAddress, this.producerGroup);
    } catch (Exception e) {
        ErrorHandler handler = this.getHandler();
        if (handler != null) {
            handler.error("Starting RocketmqLog4j2Appender [" + this.getName()
                + "] nameServerAddress:" + nameServerAddress + " group:" + producerGroup + " " + e.getMessage());
        }
    }
}
 
Example #4
Source File: RocketmqLog4j2Appender.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
protected RocketmqLog4j2Appender(String name, Filter filter, Layout<? extends Serializable> layout,
    boolean ignoreExceptions, String nameServerAddress, String producerGroup,
    String topic, String tag) {
    super(name, filter, layout, ignoreExceptions);
    this.producer = producer;
    this.topic = topic;
    this.tag = tag;
    this.nameServerAddress = nameServerAddress;
    this.producerGroup = producerGroup;
    try {
        this.producer = ProducerInstance.getProducerInstance().getInstance(this.nameServerAddress, this.producerGroup);
    } catch (Exception e) {
        ErrorHandler handler = this.getHandler();
        if (handler != null) {
            handler.error("Starting RocketmqLog4j2Appender [" + this.getName()
                + "] nameServerAddress:" + nameServerAddress + " group:" + producerGroup + " " + e.getMessage());
        }
    }
}
 
Example #5
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 #6
Source File: UIAppender.java    From patchwork-patcher with GNU Lesser General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unused")
@PluginFactory
public static UIAppender createAppender(@PluginAttribute("name") String name, @PluginAttribute("maxLines") int maxLines,
			@PluginAttribute("ignoreExceptions") boolean ignoreExceptions,
			@PluginElement("Layout") Layout<?> layout, @PluginElement("Filters") Filter filter) {
	if (name == null) {
		LOGGER.error("No name provided for UIAppender");
		return null;
	}

	if (layout == null) {
		layout = JsonLayout.createDefaultLayout();
	}

	return new UIAppender(name, layout, filter, maxLines, ignoreExceptions);
}
 
Example #7
Source File: ConfigurationBuilderTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private void addTestFixtures(final String name, final ConfigurationBuilder<BuiltConfiguration> builder) {
    builder.setConfigurationName(name);
    builder.setStatusLevel(Level.ERROR);
    builder.setShutdownTimeout(5000, TimeUnit.MILLISECONDS);
    builder.add(builder.newScriptFile("target/test-classes/scripts/filter.groovy").addIsWatched(true));
    builder.add(builder.newFilter("ThresholdFilter", Filter.Result.ACCEPT, Filter.Result.NEUTRAL)
            .addAttribute("level", Level.DEBUG));

    final AppenderComponentBuilder appenderBuilder = builder.newAppender("Stdout", "CONSOLE").addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT);
    appenderBuilder.add(builder.newLayout("PatternLayout").
            addAttribute("pattern", "%d [%t] %-5level: %msg%n%throwable"));
    appenderBuilder.add(builder.newFilter("MarkerFilter", Filter.Result.DENY,
            Filter.Result.NEUTRAL).addAttribute("marker", "FLOW"));
    builder.add(appenderBuilder);

    builder.add(builder.newLogger("org.apache.logging.log4j", Level.DEBUG, true).
                add(builder.newAppenderRef("Stdout")).
                addAttribute("additivity", false));
    builder.add(builder.newLogger("org.apache.logging.log4j.core").
                add(builder.newAppenderRef("Stdout")));
    builder.add(builder.newRootLogger(Level.ERROR).add(builder.newAppenderRef("Stdout")));

    builder.addProperty("MyKey", "MyValue");
    builder.add(builder.newCustomLevel("Panic", 17));
    builder.setPackages("foo,bar");
}
 
Example #8
Source File: RegexFilterTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testThresholds() throws Exception {
    RegexFilter filter = RegexFilter.createFilter(".* test .*", null, false, null, null);
    filter.start();
    assertTrue(filter.isStarted());
    assertSame(Filter.Result.NEUTRAL,
            filter.filter(null, Level.DEBUG, null, (Object) "This is a test message", (Throwable) null));
    assertSame(Filter.Result.DENY, filter.filter(null, Level.ERROR, null, (Object) "This is not a test",
            (Throwable) null));
    LogEvent event = Log4jLogEvent.newBuilder() //
            .setLevel(Level.DEBUG) //
            .setMessage(new SimpleMessage("Another test message")) //
            .build();
    assertSame(Filter.Result.NEUTRAL, filter.filter(event));
    event = Log4jLogEvent.newBuilder() //
            .setLevel(Level.ERROR) //
            .setMessage(new SimpleMessage("test")) //
            .build();
    assertSame(Filter.Result.DENY, filter.filter(event));
    filter = RegexFilter.createFilter(null, null, false, null, null);
    assertNull(filter);
}
 
Example #9
Source File: SystemdJournalAppender.java    From log4j-systemd-journal-appender with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
SystemdJournalAppender(String name, Filter filter, Layout<?> layout, boolean ignoreExceptions,
                       SystemdJournalLibrary journalLibrary, boolean logSource, boolean logStacktrace, boolean logThreadName,
                       boolean logLoggerName, boolean logAppenderName, boolean logThreadContext, String threadContextPrefix, String syslogIdentifier, String syslogFacility) {
    super(name, filter, layout, ignoreExceptions);
    this.journalLibrary = journalLibrary;
    this.logSource = logSource;
    this.logStacktrace = logStacktrace;
    this.logThreadName = logThreadName;
    this.logLoggerName = logLoggerName;
    this.logAppenderName = logAppenderName;
    this.logThreadContext = logThreadContext;
    if (threadContextPrefix == null) {
        this.threadContextPrefix = "THREAD_CONTEXT_";
    } else {
        this.threadContextPrefix = normalizeKey(threadContextPrefix);
    }
    this.syslogIdentifier = syslogIdentifier;
    this.syslogFacility = syslogFacility;
}
 
Example #10
Source File: LoggerConfig.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
protected LoggerConfig(final String name, final List<AppenderRef> appenders, final Filter filter,
        final Level level, final boolean additive, final Property[] properties, final Configuration config,
        final boolean includeLocation) {
    super(filter, null);
    this.logEventFactory = LOG_EVENT_FACTORY;
    this.name = name;
    this.appenderRefs = appenders;
    this.level = level;
    this.additive = additive;
    this.includeLocation = includeLocation;
    this.config = config;
    if (properties != null && properties.length > 0) {
        this.properties = Collections.unmodifiableList(Arrays.asList(Arrays.copyOf(
                properties, properties.length)));
    } else {
        this.properties = null;
    }
    this.propertiesRequireLookup = containsPropertyRequiringLookup(properties);
    this.reliabilityStrategy = config.getReliabilityStrategy(this);
}
 
Example #11
Source File: CompositeFilter.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
public CompositeFilter removeFilter(final Filter filter) {
    if (filter == null) {
        // null does nothing
        return this;
    }
    // This is not a great implementation but simpler than copying Apache Commons
    // Lang ArrayUtils.removeElement() and associated bits (MutableInt),
    // which is OK since removing a filter should not be on the critical path.
    final List<Filter> filterList = new ArrayList<>(Arrays.asList(this.filters));
    if (filter instanceof CompositeFilter) {
        for (final Filter currentFilter : ((CompositeFilter) filter).filters) {
            filterList.remove(currentFilter);
        }
    } else {
        filterList.remove(filter);
    }
    return new CompositeFilter(filterList.toArray(new Filter[this.filters.length - 1]));
}
 
Example #12
Source File: LoggerConfig.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@PluginFactory
public static LoggerConfig createLogger(
        // @formatter:off
        @PluginAttribute final String additivity,
        @PluginAttribute final Level level,
        @PluginAttribute final String includeLocation,
        @PluginElement final AppenderRef[] refs,
        @PluginElement final Property[] properties,
        @PluginConfiguration final Configuration config,
        @PluginElement final Filter filter) {
        // @formatter:on
    final List<AppenderRef> appenderRefs = Arrays.asList(refs);
    final Level actualLevel = level == null ? Level.ERROR : level;
    final boolean additive = Booleans.parseBoolean(additivity, true);

    return new LoggerConfig(LogManager.ROOT_LOGGER_NAME, appenderRefs, filter, actualLevel, additive,
            properties, config, includeLocation(includeLocation, config));
}
 
Example #13
Source File: AsyncLoggerConfig.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * @since 3.0
 */
@PluginFactory
public static LoggerConfig createLogger(
        @PluginAttribute final String additivity,
        @PluginAttribute final Level level,
        @PluginAttribute final String includeLocation,
        @PluginElement final AppenderRef[] refs,
        @PluginElement final Property[] properties,
        @PluginConfiguration final Configuration config,
        @PluginElement final Filter filter) {
    final List<AppenderRef> appenderRefs = Arrays.asList(refs);
    final Level actualLevel = level == null ? Level.ERROR : level;
    final boolean additive = Booleans.parseBoolean(additivity, true);
    return new AsyncLoggerConfig(LogManager.ROOT_LOGGER_NAME, appenderRefs, filter, actualLevel, additive,
            properties, config, AsyncLoggerConfig.includeLocation(includeLocation));
}
 
Example #14
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 #15
Source File: XIncludeTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testLogger() throws Exception {
    final Logger logger = this.ctx.getLogger(LOGGER_NAME);
    assertThat(logger, is(instanceOf(org.apache.logging.log4j.core.Logger.class)));
    final org.apache.logging.log4j.core.Logger l = (org.apache.logging.log4j.core.Logger) logger;
    assertThat(l.getLevel(), is(equalTo(Level.DEBUG)));
    assertThat(l.filterCount(), is(equalTo(1)));
    final Iterator<Filter> iterator = l.getFilters();
    assertThat(iterator.hasNext(), is(true));
    final Filter filter = iterator.next();
    assertThat(filter, is(instanceOf(ThreadContextMapFilter.class)));
    final Map<String, Appender> appenders = l.getAppenders();
    assertThat(appenders, is(notNullValue()));
    assertThat(appenders, hasSize(1));
    final Appender appender = appenders.get(APPENDER_NAME);
    assertThat(appender, is(notNullValue()));
    assertThat(appender.getName(), is(equalTo("STDOUT")));
}
 
Example #16
Source File: TimeFilterTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void overnight() {
    final TimeFilter filter = new TimeFilter(LocalTime.of(23,0), LocalTime.of(1,0),
            ZoneId.of("America/Los_Angeles"), null, null, LocalDate.of(2020, 3, 10));
    filter.start();
    assertTrue(filter.isStarted());
    ZonedDateTime date = ZonedDateTime.of(2020, 3, 10, 23, 30, 30, 0, ZoneId.of("America/Los_Angeles")).withEarlierOffsetAtOverlap();
    CLOCKTIME = date.toInstant().toEpochMilli();
    LogEvent event = Log4jLogEvent.newBuilder().setTimeMillis(CLOCKTIME).build();
    assertSame("Time " + CLOCKTIME + " is not within range: " + filter.toString(), Filter.Result.NEUTRAL, filter.filter(event));
    date = date.plusHours(1);
    CLOCKTIME = date.toInstant().toEpochMilli();
    event = Log4jLogEvent.newBuilder().setTimeMillis(CLOCKTIME).build();
    assertSame("Time " + CLOCKTIME + " is not within range: " + filter.toString(), Filter.Result.NEUTRAL, filter.filter(event));
    date = date.plusHours(1);
    CLOCKTIME = date.toInstant().toEpochMilli();
    event = Log4jLogEvent.newBuilder().setTimeMillis(CLOCKTIME).build();
    assertSame("Time " + CLOCKTIME + " is within range: " + filter.toString(), Filter.Result.DENY, filter.filter(event));
    date = date.plusDays(1).withHour(0);
    CLOCKTIME = date.toInstant().toEpochMilli();
    event = Log4jLogEvent.newBuilder().setTimeMillis(CLOCKTIME).build();
    assertSame("Time " + CLOCKTIME + " is not within range: " + filter.toString(), Filter.Result.NEUTRAL, filter.filter(event));
}
 
Example #17
Source File: StructuredDataFilterTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testConfig() {
    final Configuration config = context.getConfiguration();
    final Filter filter = config.getFilter();
    assertNotNull("No StructuredDataFilter", filter);
    assertTrue("Not a StructuredDataFilter", filter instanceof  StructuredDataFilter);
    final StructuredDataFilter sdFilter = (StructuredDataFilter) filter;
    assertFalse("Should not be And filter", sdFilter.isAnd());
    final IndexedReadOnlyStringMap map = sdFilter.getStringMap();
    assertNotNull("No Map", map);
    assertFalse("No elements in Map", map.isEmpty());
    assertEquals("Incorrect number of elements in Map", 1, map.size());
    assertTrue("Map does not contain key eventId", map.containsKey("eventId"));
    assertEquals("List does not contain 2 elements", 2, map.<Collection<?>>getValue("eventId").size());
}
 
Example #18
Source File: ConfigurationBuilderTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private void addTestFixtures(final String name, final ConfigurationBuilder<BuiltConfiguration> builder) {
    builder.setConfigurationName(name);
    builder.setStatusLevel(Level.ERROR);
    builder.setShutdownTimeout(5000, TimeUnit.MILLISECONDS);
    builder.add(builder.newScriptFile("target/test-classes/scripts/filter.groovy").addIsWatched(true));
    builder.add(builder.newFilter("ThresholdFilter", Filter.Result.ACCEPT, Filter.Result.NEUTRAL)
            .addAttribute("level", Level.DEBUG));

    final AppenderComponentBuilder appenderBuilder = builder.newAppender("Stdout", "CONSOLE").addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT);
    appenderBuilder.add(builder.newLayout("PatternLayout").
            addAttribute("pattern", "%d [%t] %-5level: %msg%n%throwable"));
    appenderBuilder.add(builder.newFilter("MarkerFilter", Filter.Result.DENY,
            Filter.Result.NEUTRAL).addAttribute("marker", "FLOW"));
    builder.add(appenderBuilder);

    final AppenderComponentBuilder appenderBuilder2 = builder.newAppender("Kafka", "Kafka").addAttribute("topic", "my-topic");
    appenderBuilder2.addComponent(builder.newProperty("bootstrap.servers", "localhost:9092"));
    appenderBuilder2.add(builder.newLayout("GelfLayout").
        addAttribute("host", "my-host").
        addComponent(builder.newKeyValuePair("extraField", "extraValue")));
    builder.add(appenderBuilder2);

    builder.add(builder.newLogger("org.apache.logging.log4j", Level.DEBUG, true).
                add(builder.newAppenderRef("Stdout")).
                addAttribute("additivity", false));
    builder.add(builder.newLogger("org.apache.logging.log4j.core").
                add(builder.newAppenderRef("Stdout")));
    builder.add(builder.newRootLogger(Level.ERROR).add(builder.newAppenderRef("Stdout")));

    builder.addProperty("MyKey", "MyValue");
    builder.add(builder.newCustomLevel("Panic", 17));
    builder.setPackages("foo,bar");
}
 
Example #19
Source File: Log4jLogger_impl.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param level a log4j level that's equal or above (ERROR is highest) the level being tested
 * @param marker - the marker that needs to be there to allow this
 * @return - the result of running the logger filter test if there is one, else NEUTRAL
 */
private Result filterTest(org.apache.logging.log4j.Level level, org.apache.logging.log4j.Marker marker) {
  Filter filter = coreLogger.get().getFilter();
  if (null != filter) {
    return filter.filter(coreLogger, level, marker, (String) null, (Object[])null);
  }
  return Result.NEUTRAL;
}
 
Example #20
Source File: UsesLoggingAppender.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@PluginFactory
public static UsesLoggingAppender createAppender(
    @PluginAttribute @Required(message = "A name for the Appender must be specified") final String name,
    @PluginAttribute("ignoreExceptions") final boolean ignore,
    @PluginElement final Layout<?> layout,
    @PluginElement final Filter filter) {
    return new UsesLoggingAppender(name, filter, layout, ignore);
}
 
Example #21
Source File: AbstractFilterableTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoveCompositeFilterFromCompositeFilter() {
    final Filter filter1 = ThresholdFilter.createFilter(Level.ERROR, null, null);
    final Filter filter2 = ThresholdFilter.createFilter(Level.ERROR, null, null);
    final Filter compositeFilter = CompositeFilter.createFilters(new Filter[]{filter1, filter2});

    filterable.addFilter(compositeFilter);
    filterable.removeFilter(compositeFilter);
    assertNull(filterable.getFilter());
}
 
Example #22
Source File: TestConfigurator.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testBuilderWithScripts() throws Exception {
    final String script = "if (logEvent.getLoggerName().equals(\"NoLocation\")) {\n" +
            "                return \"NoLocation\";\n" +
            "            } else if (logEvent.getMarker() != null && logEvent.getMarker().isInstanceOf(\"FLOW\")) {\n" +
            "                return \"Flow\";\n" +
            "            } else {\n" +
            "                return null;\n" +
            "            }";
    final ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
    builder.setStatusLevel(Level.ERROR);
    builder.setConfigurationName("BuilderTest");
    builder.add(builder.newScriptFile("filter.groovy", "target/test-classes/scripts/filter.groovy").addIsWatched(true));
    final AppenderComponentBuilder appenderBuilder = builder.newAppender("Stdout", "CONSOLE").addAttribute("target",
            ConsoleAppender.Target.SYSTEM_OUT);
    appenderBuilder.add(builder.newLayout("PatternLayout").
            addComponent(builder.newComponent("ScriptPatternSelector")
                    .addAttribute("defaultPattern", "[%-5level] %c{1.} %C{1.}.%M.%L %msg%n")
                    .addComponent(builder.newComponent("PatternMatch").addAttribute("key", "NoLocation")
                            .addAttribute("pattern", "[%-5level] %c{1.} %msg%n"))
                    .addComponent(builder.newComponent("PatternMatch").addAttribute("key", "FLOW")
                            .addAttribute("pattern", "[%-5level] %c{1.} ====== %C{1.}.%M:%L %msg ======%n"))
                    .addComponent(builder.newComponent("selectorScript", "Script", script).addAttribute("language", "beanshell"))));
    appenderBuilder.add(builder.newFilter("ScriptFilter", Filter.Result.DENY,
            Filter.Result.NEUTRAL).addComponent(builder.newComponent("ScriptRef").addAttribute("ref", "filter.groovy")));
    builder.add(appenderBuilder);
    builder.add(builder.newLogger("org.apache.logging.log4j", Level.DEBUG).
            add(builder.newAppenderRef("Stdout")).
            addAttribute("additivity", false));
    builder.add(builder.newRootLogger(Level.ERROR).add(builder.newAppenderRef("Stdout")));
    ctx = Configurator.initialize(builder.build());
    final Configuration config = ctx.getConfiguration();
    assertNotNull("No configuration", config);
    assertEquals("Unexpected Configuration", "BuilderTest", config.getName());
    assertThat(config.getAppenders(), hasSize(equalTo(1)));
    assertNotNull("Filter script not found", config.getScriptManager().getScript("filter.groovy"));
    assertNotNull("pattern selector script not found", config.getScriptManager().getScript("selectorScript"));
}
 
Example #23
Source File: StringBuilderAppender.java    From Flashtool with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Factory method. Log4j will parse the configuration and call this factory 
 * method to construct the appender with
 * the configured attributes.
 *
 * @param name   Name of appender
 * @param layout Log layout of appender
 * @param filter Filter for appender
 * @return The TextAreaAppender
 */
@PluginFactory
public static StringBuilderAppender createAppender(
    @PluginAttribute("name") String name,
    @PluginElement("Layout") Layout<? extends Serializable> layout,
    @PluginElement("Filter") final Filter filter) {
  if (name == null) {
    LOGGER.error("No name provided for TextAreaAppender2");
    return null;
  }
  if (layout == null) {
    layout = PatternLayout.createDefaultLayout();
  }
  return new StringBuilderAppender(name, filter, layout, true);
}
 
Example #24
Source File: RewriteAppender.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private RewriteAppender(final String name, final Filter filter, final boolean ignoreExceptions,
                        final AppenderRef[] appenderRefs, final RewritePolicy rewritePolicy,
                        final Configuration config, Property[] properties) {
    super(name, filter, null, ignoreExceptions, properties);
    this.config = config;
    this.rewritePolicy = rewritePolicy;
    this.appenderRefs = appenderRefs;
}
 
Example #25
Source File: RegexFilterTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDotAllPattern() throws Exception {
    final String singleLine = "test single line matches";
    final String multiLine = "test multi line matches\nsome more lines";
    final RegexFilter filter = RegexFilter.createFilter(".*line.*", new String[] { "DOTALL", "COMMENTS" }, false,
            Filter.Result.DENY, Filter.Result.ACCEPT);
    final Result singleLineResult = filter.filter(null, null, null, (Object) singleLine, (Throwable) null);
    final Result multiLineResult = filter.filter(null, null, null, (Object) multiLine, (Throwable) null);
    assertThat(singleLineResult, equalTo(Result.DENY));
    assertThat(multiLineResult, equalTo(Result.DENY));
}
 
Example #26
Source File: JSwingAppender.java    From collect-earth with MIT License 5 votes vote down vote up
@PluginFactory
public static JSwingAppender createAppender(@PluginAttribute("name") String name,
		@PluginElement("Layout") Layout<?> layout, @PluginElement("Filters") Filter filter,
		@PluginAttribute("ignoreExceptions") boolean ignoreExceptions) {

	if (name == null) {
		LoggerFactory.getLogger( JSwingAppender.class ).error("No name provided for JTextAreaAppender");
		return null;
	}

	if (layout == null) {
		layout = PatternLayout.createDefaultLayout();
	}
	return new JSwingAppender(name, filter, layout, ignoreExceptions);
}
 
Example #27
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 #28
Source File: AbstractFilterableTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddMultipleCompositeFilters() throws Exception {
    final Filter filter1 = ThresholdFilter.createFilter(Level.ERROR, null, null);
    final Filter filter2 = ThresholdFilter.createFilter(Level.ERROR, null, null);
    final Filter filter3 = ThresholdFilter.createFilter(Level.ERROR, null, null);
    final Filter compositeFilter = CompositeFilter.createFilters(new Filter[]{filter1, filter2, filter3});

    filterable.addFilter(compositeFilter);
    assertSame(compositeFilter, filterable.getFilter());
    // adding a second filter converts the filter
    // into a CompositeFilter.class
    filterable.addFilter(compositeFilter);
    assertTrue(filterable.getFilter() instanceof CompositeFilter);
    assertEquals(6, ((CompositeFilter) filterable.getFilter()).getFiltersArray().length);
}
 
Example #29
Source File: AbstractFilterableTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoveSimpleFilterFromSimpleFilter() throws Exception {
    final Filter filter = ThresholdFilter.createFilter(Level.ERROR, null, null);

    filterable.addFilter(filter);
    filterable.removeFilter(filter);
    assertNull(filterable.getFilter());
}
 
Example #30
Source File: TestConfigurator.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testBadFilterParam() throws Exception {
    ctx = Configurator.initialize("Test1", "bad/log4j-badfilterparam.xml");
    LogManager.getLogger("org.apache.test.TestConfigurator");
    final Configuration config = ctx.getConfiguration();
    assertNotNull("No configuration", config);
    assertEquals("Unexpected Configuration", "XMLConfigTest", config.getName());
    final LoggerConfig lcfg = config.getLoggerConfig("org.apache.logging.log4j.test1");
    assertNotNull("No Logger", lcfg);
    final Filter filter = lcfg.getFilter();
    assertNull("Unexpected Filter", filter);
}