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

The following examples show how to use org.apache.logging.log4j.core.Appender. 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: PropertiesConfigurationTest.java    From logging-log4j2 with Apache License 2.0 8 votes vote down vote up
@Test
public void testListAppender() throws Exception {
    LoggerContext loggerContext = configure("target/test-classes/log4j1-list.properties");
    Logger logger = LogManager.getLogger("test");
    logger.debug("This is a test of the root logger");
    Configuration configuration = loggerContext.getConfiguration();
    Map<String, Appender> appenders = configuration.getAppenders();
    ListAppender eventAppender = null;
    ListAppender messageAppender = null;
    for (Map.Entry<String, Appender> entry : appenders.entrySet()) {
        if (entry.getKey().equals("list")) {
            messageAppender = (ListAppender) ((AppenderAdapter.Adapter) entry.getValue()).getAppender();
        } else if (entry.getKey().equals("events")) {
            eventAppender = (ListAppender) ((AppenderAdapter.Adapter) entry.getValue()).getAppender();
        }
    }
    assertNotNull("No Event Appender", eventAppender);
    assertNotNull("No Message Appender", messageAppender);
    List<LoggingEvent> events = eventAppender.getEvents();
    assertTrue("No events", events != null && events.size() > 0);
    List<String> messages = messageAppender.getMessages();
    assertTrue("No messages", messages != null && messages.size() > 0);
}
 
Example #2
Source File: Main.java    From homework_tester with MIT License 7 votes vote down vote up
private static Logger configureLog4j() {
    LoggerContext context = (LoggerContext) LogManager.getContext();
    Configuration config = context.getConfiguration();

    PatternLayout layout = PatternLayout.createLayout("%m%n", null, null, Charset.defaultCharset(), false, false, null, null);
    Appender appender = ConsoleAppender.createAppender(layout, null, null, "CONSOLE_APPENDER", null, null);
    appender.start();
    AppenderRef ref = AppenderRef.createAppenderRef("CONSOLE_APPENDER", null, null);
    AppenderRef[] refs = new AppenderRef[]{ref};
    LoggerConfig loggerConfig = LoggerConfig.createLogger("false", Level.INFO, "CONSOLE_LOGGER", "com", refs, null, null, null);
    loggerConfig.addAppender(appender, null, null);

    config.addAppender(appender);
    config.addLogger("Main.class", loggerConfig);
    context.updateLoggers(config);
    return LogManager.getContext().getLogger("Main.class");
}
 
Example #3
Source File: MissingRootLoggerTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
    public void testMissingRootLogger() throws Exception {
        final LoggerContext ctx = context.getLoggerContext();
        final Logger logger = ctx.getLogger("sample.Logger1");
        assertTrue("Logger should have the INFO level enabled", logger.isInfoEnabled());
        assertFalse("Logger should have the DEBUG level disabled", logger.isDebugEnabled());
        final Configuration config = ctx.getConfiguration();
        assertNotNull("Config not null", config);
//        final String MISSINGROOT = "MissingRootTest";
//        assertTrue("Incorrect Configuration. Expected " + MISSINGROOT + " but found " + config.getName(),
//                MISSINGROOT.equals(config.getName()));
        final Map<String, Appender> map = config.getAppenders();
        assertNotNull("Appenders not null", map);
        assertThat("There should only be two appenders", map, hasSize(2));
        assertThat(map, hasKey("List"));
        assertThat(map, hasKey("DefaultConsole-2"));

        final Map<String, LoggerConfig> loggerMap = config.getLoggers();
        assertNotNull("loggerMap not null", loggerMap);
        assertThat("There should only be one configured logger", loggerMap, hasSize(1));
        // only the sample logger, no root logger in loggerMap!
        assertThat("contains key=sample", loggerMap, hasKey("sample"));

        final LoggerConfig sample = loggerMap.get("sample");
        final Map<String, Appender> sampleAppenders = sample.getAppenders();
        assertThat("The sample logger should only have one appender", sampleAppenders, hasSize(1));
        // sample only has List appender, not Console!
        assertThat("The sample appender should be a ListAppender", sampleAppenders, hasKey("List"));
        assertThat(config, is(instanceOf(AbstractConfiguration.class)));
        final AbstractConfiguration baseConfig = (AbstractConfiguration) config;
        final LoggerConfig root = baseConfig.getRootLogger();
        final Map<String, Appender> rootAppenders = root.getAppenders();
        assertThat("The root logger should only have one appender", rootAppenders, hasSize(1));
        // root only has Console appender!
        assertThat("The root appender should be a ConsoleAppender", rootAppenders, hasKey("DefaultConsole-2"));
        assertEquals(Level.ERROR, root.getLevel());
    }
 
Example #4
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 #5
Source File: HttpAppenderTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testAppendHttps() throws Exception {
    wireMockRule.stubFor(post(urlEqualTo("/test/log4j/"))
        .willReturn(SUCCESS_RESPONSE));

    final Appender appender = HttpAppender.newBuilder()
        .setName("Http")
        .setLayout(JsonLayout.createDefaultLayout())
        .setConfiguration(ctx.getConfiguration())
        .setUrl(new URL("https://localhost:" + wireMockRule.httpsPort() + "/test/log4j/"))
        .setSslConfiguration(SslConfiguration.createSSLConfiguration(null,
            KeyStoreConfiguration.createKeyStoreConfiguration(TestConstants.KEYSTORE_FILE, TestConstants.KEYSTORE_PWD(), null, null, TestConstants.KEYSTORE_TYPE, null),
            TrustStoreConfiguration.createKeyStoreConfiguration(TestConstants.TRUSTSTORE_FILE, TestConstants.TRUSTSTORE_PWD(), null ,null, TestConstants.TRUSTSTORE_TYPE, null)))
        .setVerifyHostname(false)
        .build();
    appender.append(createLogEvent());

    wireMockRule.verify(postRequestedFor(urlEqualTo("/test/log4j/"))
        .withHeader("Host", containing("localhost"))
        .withHeader("Content-Type", containing("application/json"))
        .withRequestBody(containing("\"message\" : \"" + LOG_MESSAGE + "\"")));
}
 
Example #6
Source File: Log4j1ConfigurationFactoryTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #7
Source File: TestConfigurator.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testFromClassPathProperty() throws Exception {
    System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "classpath:log4j2-config.xml");
    ctx = Configurator.initialize("Test1", null);
    LogManager.getLogger("org.apache.test.TestConfigurator");
    Configuration config = ctx.getConfiguration();
    assertNotNull("No configuration", config);
    assertEquals("Incorrect Configuration.", CONFIG_NAME, config.getName());
    final Map<String, Appender> map = config.getAppenders();
    assertNotNull("Appenders map should not be null.", map);
    assertThat(map, hasSize(greaterThan(0)));
    assertThat("Wrong configuration", map, hasKey("List"));
    Configurator.shutdown(ctx);
    config = ctx.getConfiguration();
    assertEquals("Unexpected Configuration.", NullConfiguration.NULL_NAME, config.getName());
}
 
Example #8
Source File: Log4j2LoggingHelper.java    From herd with Apache License 2.0 6 votes vote down vote up
@Override
public StringWriter addLoggingWriterAppender(String appenderName)
{
    // Get the configuration
    final LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false);
    final Configuration configuration = loggerContext.getConfiguration();

    // Create a string writer as part of the appender so logging will be written to it.
    StringWriter stringWriter = new StringWriter();

    // Create and start the appender with the string writer.
    Appender appender = WriterAppender.createAppender(null, null, stringWriter, appenderName, false, true);
    appender.start();

    // Add the appender to the root logger.
    configuration.getRootLogger().addAppender(appender, null, null);

    // Return the string writer.
    return stringWriter;
}
 
Example #9
Source File: PulsarAppenderTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Test
public void testAppendWithKeyLookup() {
    final Appender appender = ctx.getConfiguration().getAppender("PulsarAppenderWithKeyLookup");
    final LogEvent logEvent = createLogEvent();
    Date date = new Date();
    SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
    appender.append(logEvent);
    Message<byte[]> item;
    synchronized (history) {
        assertEquals(1, history.size());
        item = history.get(0);
    }
    assertNotNull(item);
    String keyValue = format.format(date);
    assertEquals(item.getKey(), keyValue);
    assertEquals(LOG_MESSAGE, new String(item.getData(), StandardCharsets.UTF_8));
}
 
Example #10
Source File: LoggingMixin.java    From picocli with Apache License 2.0 6 votes vote down vote up
/**
 * Configures the Log4j2 console appender(s), using the specified verbosity:
 * <ul>
 *   <li>{@code -vvv} : enable TRACE level</li>
 *   <li>{@code -vv} : enable DEBUG level</li>
 *   <li>{@code -v} : enable INFO level</li>
 *   <li>(not specified) : enable WARN level</li>
 * </ul>
 */
public void configureLoggers() {
    Level level = getTopLevelCommandLoggingMixin(mixee).calcLogLevel();

    LoggerContext loggerContext = LoggerContext.getContext(false);
    LoggerConfig rootConfig = loggerContext.getConfiguration().getRootLogger();
    for (Appender appender : rootConfig.getAppenders().values()) {
        if (appender instanceof ConsoleAppender) {
            rootConfig.removeAppender(appender.getName());
            rootConfig.addAppender(appender, level, null);
        }
    }
    if (rootConfig.getLevel().isMoreSpecificThan(level)) {
        rootConfig.setLevel(level);
    }
    loggerContext.updateLoggers(); // apply the changes
}
 
Example #11
Source File: RewriteAppenderTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testRewrite() throws Exception {
    Logger logger = LogManager.getLogger("test");
    ThreadContext.put("key1", "This is a test");
    ThreadContext.put("hello", "world");
    logger.debug("Say hello");
    LoggerContext context = (LoggerContext) org.apache.logging.log4j.LogManager.getContext(false);
    Configuration configuration = context.getConfiguration();
    Map<String, Appender> appenders = configuration.getAppenders();
    ListAppender eventAppender = null;
    for (Map.Entry<String, Appender> entry : appenders.entrySet()) {
        if (entry.getKey().equals("events")) {
            eventAppender = (ListAppender) ((AppenderAdapter.Adapter) entry.getValue()).getAppender();
        }
    }
    assertNotNull("No Event Appender", eventAppender);
    List<LoggingEvent> events = eventAppender.getEvents();
    assertTrue("No events", events != null && events.size() > 0);
    assertNotNull("No properties in the event", events.get(0).getProperties());
    assertTrue("Key was not inserted", events.get(0).getProperties().containsKey("key2"));
    assertEquals("Key value is incorrect", "Log4j", events.get(0).getProperties().get("key2"));
}
 
Example #12
Source File: XmlConfigurationTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testListAppender() throws Exception {
    LoggerContext loggerContext = configure("target/test-classes/log4j1-list.xml");
    Logger logger = LogManager.getLogger("test");
    logger.debug("This is a test of the root logger");
    Configuration configuration = loggerContext.getConfiguration();
    Map<String, Appender> appenders = configuration.getAppenders();
    ListAppender eventAppender = null;
    ListAppender messageAppender = null;
    for (Map.Entry<String, Appender> entry : appenders.entrySet()) {
        if (entry.getKey().equals("list")) {
            messageAppender = (ListAppender) ((AppenderAdapter.Adapter) entry.getValue()).getAppender();
        } else if (entry.getKey().equals("events")) {
            eventAppender = (ListAppender) ((AppenderAdapter.Adapter) entry.getValue()).getAppender();
        }
    }
    assertNotNull("No Event Appender", eventAppender);
    assertNotNull("No Message Appender", messageAppender);
    List<LoggingEvent> events = eventAppender.getEvents();
    assertTrue("No events", events != null && events.size() > 0);
    List<String> messages = messageAppender.getMessages();
    assertTrue("No messages", messages != null && messages.size() > 0);
}
 
Example #13
Source File: AppenderRefFailoverPolicyTest.java    From log4j2-elasticsearch with Apache License 2.0 6 votes vote down vote up
@Test
public void deliverItemSourceDelegates() {

    // given
    Appender appender = mock(Appender.class);
    when(appender.isStarted()).thenReturn(true);
    Configuration configuration = mock(Configuration.class);
    String testAppenderRef = "testAppenderRef";
    when(configuration.getAppender(testAppenderRef)).thenReturn(appender);

    FailoverPolicy<String> failoverPolicy = spy(createTestFailoverPolicy(testAppenderRef, configuration));

    String failedMessage = UUID.randomUUID().toString();
    ItemSource<String> itemSource = new StringItemSource(failedMessage);

    // when
    failoverPolicy.deliver(itemSource);

    // then
    verify(failoverPolicy).deliver(eq(failedMessage));
}
 
Example #14
Source File: HttpAppenderTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testAppend() throws Exception {
    wireMockRule.stubFor(post(urlEqualTo("/test/log4j/"))
        .willReturn(SUCCESS_RESPONSE));

    final Appender appender = HttpAppender.newBuilder()
        .setName("Http")
        .setLayout(JsonLayout.createDefaultLayout())
        .setConfiguration(ctx.getConfiguration())
        .setUrl(new URL("http://localhost:" + wireMockRule.port() + "/test/log4j/"))
        .build();
    appender.append(createLogEvent());

    wireMockRule.verify(postRequestedFor(urlEqualTo("/test/log4j/"))
        .withHeader("Host", containing("localhost"))
        .withHeader("Content-Type", containing("application/json"))
        .withRequestBody(containing("\"message\" : \"" + LOG_MESSAGE + "\"")));
}
 
Example #15
Source File: KafkaAppenderTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testAppendWithKeyLookup() throws Exception {
    final Appender appender = ctx.getRequiredAppender("KafkaAppenderWithKeyLookup");
    final LogEvent logEvent = createLogEvent();
    Date date = new Date();
    SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
    appender.append(logEvent);
    final List<ProducerRecord<byte[], byte[]>> history = kafka.history();
    assertEquals(1, history.size());
    final ProducerRecord<byte[], byte[]> item = history.get(0);
    assertNotNull(item);
    assertEquals(TOPIC_NAME, item.topic());
    byte[] keyValue = format.format(date).getBytes(StandardCharsets.UTF_8);
    assertEquals(Long.valueOf(logEvent.getTimeMillis()), item.timestamp());
    assertArrayEquals(item.key(), keyValue);
    assertEquals(LOG_MESSAGE, new String(item.value(), StandardCharsets.UTF_8));
}
 
Example #16
Source File: StartupLoggingUtils.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Disables all log4j2 ConsoleAppender's by modifying log4j configuration dynamically.
 * Must only be used during early startup
 * @return true if ok or else false if something happened, e.g. log4j2 classes were not in classpath
 */
@SuppressForbidden(reason = "Legitimate log4j2 access")
public static boolean muteConsole() {
  try {
    if (!isLog4jActive()) {
      logNotSupported("Could not mute logging to console.");
      return false;
    }
    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    Configuration config = ctx.getConfiguration();
    LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
    Map<String, Appender> appenders = loggerConfig.getAppenders();
    appenders.forEach((name, appender) -> {
      if (appender instanceof ConsoleAppender) {
        loggerConfig.removeAppender(name);
        ctx.updateLoggers();
      }
    });
    return true;
  } catch (Exception e) {
    logNotSupported("Could not mute logging to console.");
    return false;
  }
}
 
Example #17
Source File: LogTestRule.java    From ArchUnit with Apache License 2.0 6 votes vote down vote up
public void watch(Class<?> loggerClass, Level level) {
    this.loggerClass = loggerClass;
    Appender appender = new AbstractAppender(APPENDER_NAME, null, PatternLayout.createDefaultLayout()) {
        @Override
        public void append(LogEvent event) {
            logEvents.add(new RecordedLogEvent(event));
        }
    };
    appender.start();
    final LoggerContext ctx = getLoggerContext();
    LoggerConfig loggerConfig = ctx.getConfiguration().getLoggerConfig(loggerClass.getName());
    oldLevel = loggerConfig.getLevel();
    loggerConfig.setLevel(level);
    loggerConfig.addAppender(appender, level, null);
    ctx.updateLoggers();
}
 
Example #18
Source File: LoggerFactory.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public static void initGuiLogging(String logFile) {
  ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
  builder.add(builder.newRootLogger(Level.INFO));
  LoggerContext context = Configurator.initialize(builder.build());

  PatternLayout layout = PatternLayout.newBuilder()
      .withPattern("[%d{ISO8601}] %5p (%F:%L) - %m%n")
      .withCharset(StandardCharsets.UTF_8)
      .build();

  Appender fileAppender = FileAppender.newBuilder()
      .setName("File")
      .setLayout(layout)
      .withFileName(logFile)
      .withAppend(false)
        .build();
  fileAppender.start();

  Appender textAreaAppender = TextAreaAppender.newBuilder()
      .setName("TextArea")
      .setLayout(layout)
      .build();
  textAreaAppender.start();

  context.getRootLogger().addAppender(fileAppender);
  context.getRootLogger().addAppender(textAreaAppender);
  context.updateLoggers();
}
 
Example #19
Source File: AbstractConfiguration.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Associates an Appender with a LoggerConfig. This method is synchronized in case a Logger with the same name is
 * being updated at the same time.
 *
 * Note: This method is not used when configuring via configuration. It is primarily used by unit tests.
 *
 * @param logger The Logger the Appender will be associated with.
 * @param appender The Appender.
 */
@Override
public synchronized void addLoggerAppender(final org.apache.logging.log4j.core.Logger logger,
        final Appender appender) {
    if (appender == null || logger == null) {
        return;
    }
    final String loggerName = logger.getName();
    appenders.putIfAbsent(appender.getName(), appender);
    final LoggerConfig lc = getLoggerConfig(loggerName);
    if (lc.getName().equals(loggerName)) {
        lc.addAppender(appender, null, null);
    } else {
        final LoggerConfig nlc = new LoggerConfig(loggerName, lc.getLevel(), lc.isAdditive());
        nlc.addAppender(appender, null, null);
        nlc.setParent(lc);
        loggerConfigs.putIfAbsent(loggerName, nlc);
        setParents();
        logger.getContext().updateLoggers();
    }
}
 
Example #20
Source File: Loggers.java    From jetlinks-community with Apache License 2.0 5 votes vote down vote up
public static void addAppender(final Logger logger, final Appender appender) {
//        final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
//        final Configuration config = ctx.getConfiguration();
//        config.addAppender(appender);
//        LoggerConfig loggerConfig = config.getLoggerConfig(logger.getName());
//        if (!logger.getName().equals(loggerConfig.getName())) {
//            loggerConfig = new LoggerConfig(logger.getName(), logger.getLevel(), true);
//            config.addLogger(logger.getName(), loggerConfig);
//        }
//        loggerConfig.addAppender(appender, null, null);
//        ctx.updateLoggers();
    }
 
Example #21
Source File: KafkaAppenderTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testAsyncAppend() throws Exception {
    final Appender appender = ctx.getRequiredAppender("AsyncKafkaAppender");
    appender.append(createLogEvent());
    final List<ProducerRecord<byte[], byte[]>> history = kafka.history();
    assertEquals(1, history.size());
    final ProducerRecord<byte[], byte[]> item = history.get(0);
    assertNotNull(item);
    assertEquals(TOPIC_NAME, item.topic());
    assertNull(item.key());
    assertEquals(LOG_MESSAGE, new String(item.value(), StandardCharsets.UTF_8));
}
 
Example #22
Source File: SpectatorAppender.java    From spectator with Apache License 2.0 5 votes vote down vote up
/**
 * Add the spectator appender to the root logger. This method is intended to be called once
 * as part of the applications initialization process.
 *
 * @param registry
 *     Spectator registry to use for the appender.
 * @param name
 *     Name for the appender.
 * @param ignoreExceptions
 *     If set to true then the stack trace metrics are disabled.
 */
public static void addToRootLogger(
    Registry registry,
    String name,
    boolean ignoreExceptions) {
  final Appender appender = new SpectatorAppender(
      registry, name, null, null, ignoreExceptions, Property.EMPTY_ARRAY);
  appender.start();

  LoggerContext context = (LoggerContext) LogManager.getContext(false);
  Configuration config = context.getConfiguration();

  addToRootLogger(appender);
  config.addListener(reconfigurable -> addToRootLogger(appender));
}
 
Example #23
Source File: FailoverAppender.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public void start() {
    final Map<String, Appender> map = config.getAppenders();
    int errors = 0;
    final Appender appender = map.get(primaryRef);
    if (appender != null) {
        primary = new AppenderControl(appender, null, null);
    } else {
        LOGGER.error("Unable to locate primary Appender " + primaryRef);
        ++errors;
    }
    for (final String name : failovers) {
        final Appender foAppender = map.get(name);
        if (foAppender != null) {
            failoverAppenders.add(new AppenderControl(foAppender, null, null));
        } else {
            LOGGER.error("Failover appender " + name + " is not configured");
        }
    }
    if (failoverAppenders.isEmpty()) {
        LOGGER.error("No failover appenders are available");
        ++errors;
    }
    if (errors == 0) {
        super.start();
    }
}
 
Example #24
Source File: JdbcAuditAppender.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
protected void initTargetAppender() {
    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);

    ColumnMapping[] columnMappings = {
        ColumnMapping.newBuilder().
        setConfiguration(ctx.getConfiguration()).setName("EVENT_DATE").setType(Timestamp.class).build(),
        ColumnMapping.newBuilder().
        setConfiguration(ctx.getConfiguration()).setName("LOGGER_LEVEL").setPattern("%level").build(),
        ColumnMapping.newBuilder().
        setConfiguration(ctx.getConfiguration()).setName("LOGGER").setPattern("%logger").build(),
        ColumnMapping.newBuilder().
        setConfiguration(ctx.getConfiguration()).
        setName(LoggerDAO.AUDIT_MESSAGE_COLUMN).setPattern("%message").build(),
        ColumnMapping.newBuilder().
        setConfiguration(ctx.getConfiguration()).setName("THROWABLE").setPattern("%ex{full}").build()
    };

    Appender appender = ctx.getConfiguration().getAppender("audit_for_" + domain);
    if (appender == null) {
        appender = JdbcAppender.newBuilder().
                setName("audit_for_" + domain).
                setIgnoreExceptions(false).
                setConnectionSource(new DataSourceConnectionSource(domain, domainHolder.getDomains().get(domain))).
                setBufferSize(0).
                setTableName(LoggerDAO.AUDIT_TABLE).
                setColumnMappings(columnMappings).
                build();
        appender.start();
        ctx.getConfiguration().addAppender(appender);
    }
    targetAppender = appender;
}
 
Example #25
Source File: WebLookupTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testLookup2() throws Exception {
    ContextAnchor.THREAD_CONTEXT.remove();
    final ServletContext servletContext = new MockServletContext();
    ((MockServletContext) servletContext).setContextPath("/");
    servletContext.setAttribute("TestAttr", "AttrValue");
    servletContext.setInitParameter("myapp.logdir", "target");
    servletContext.setAttribute("Name1", "Ben");
    servletContext.setInitParameter("Name2", "Jerry");
    servletContext.setInitParameter("log4jConfiguration", "WEB-INF/classes/log4j-webvar.xml");
    final Log4jWebLifeCycle initializer = WebLoggerContextUtils.getWebLifeCycle(servletContext);
    initializer.start();
    initializer.setLoggerContext();
    final LoggerContext ctx = ContextAnchor.THREAD_CONTEXT.get();
    assertNotNull("No LoggerContext", ctx);
    assertNotNull("No ServletContext", ctx.getExternalContext());
    final Configuration config = ctx.getConfiguration();
    assertNotNull("No Configuration", config);
    final Map<String, Appender> appenders = config.getAppenders();
    for (final Map.Entry<String, Appender> entry : appenders.entrySet()) {
        if (entry.getKey().equals("file")) {
            final FileAppender fa = (FileAppender) entry.getValue();
            assertEquals("target/myapp.log", fa.getFileName());
        }
    }
    final StrSubstitutor substitutor = config.getStrSubstitutor();
    String value = substitutor.replace("${web:contextPathName:-default}");
    assertNotNull("No value for context name", value);
    assertEquals("Incorrect value for context name", "default", value);
    initializer.stop();
    ContextAnchor.THREAD_CONTEXT.remove();
}
 
Example #26
Source File: AbstractConfiguration.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Start the configuration.
 */
@Override
public void start() {
    // Preserve the prior behavior of initializing during start if not initialized.
    if (getState().equals(State.INITIALIZING)) {
        initialize();
    }
    LOGGER.debug("Starting configuration {}", this);
    this.setStarting();
    if (watchManager.getIntervalSeconds() >= 0) {
        watchManager.start();
    }
    if (hasAsyncLoggers()) {
        asyncLoggerConfigDisruptor.start();
    }
    final Set<LoggerConfig> alreadyStarted = new HashSet<>();
    for (final LoggerConfig logger : loggerConfigs.values()) {
        logger.start();
        alreadyStarted.add(logger);
    }
    for (final Appender appender : appenders.values()) {
        appender.start();
    }
    if (!alreadyStarted.contains(root)) { // LOG4J2-392
        root.start(); // LOG4J2-336
    }
    super.start();
    LOGGER.debug("Started configuration {} OK.", this);
}
 
Example #27
Source File: LogUtil.java    From ldbc_graphalytics with Apache License 2.0 5 votes vote down vote up
public static void appendSimplifiedConsoleLogger(Level level) {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = ctx.getConfiguration();
    Layout layout = PatternLayout.createLayout("%msg%n", null, config, null, null, true, false, null, null);
    Appender appender = ConsoleAppender.createAppender(layout, null, ConsoleAppender.Target.SYSTEM_OUT, "stdout", true, true);
    appender.start();

    config.getRootLogger().addAppender(appender, level, null);
    ctx.updateLoggers();
}
 
Example #28
Source File: LogUtil.java    From ldbc_graphalytics with Apache License 2.0 5 votes vote down vote up
public static void appendConsoleLogger(Level level) {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = ctx.getConfiguration();
    Layout layout = PatternLayout.createLayout("%highlight{%d{HH:mm} [%-5p] %msg%n}{STYLE=Logback}", null, config, null, null, true, true, null, null);
    Appender appender = ConsoleAppender.createAppender(layout, null, ConsoleAppender.Target.SYSTEM_OUT, "stdout", true, true);
    appender.start();

    config.getRootLogger().addAppender(appender, level, null);
    ctx.updateLoggers();
}
 
Example #29
Source File: RoutingAppender.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private synchronized RouteAppenderControl getControl(final String key, final LogEvent event) {
    RouteAppenderControl control = getAppender(key);
    if (control != null) {
        control.checkout();
        return control;
    }
    Route route = null;
    for (final Route r : routes.getRoutes()) {
        if (r.getAppenderRef() == null && key.equals(r.getKey())) {
            route = r;
            break;
        }
    }
    if (route == null) {
        route = defaultRoute;
        control = getAppender(DEFAULT_KEY);
        if (control != null) {
            control.checkout();
            return control;
        }
    }
    if (route != null) {
        final Appender app = createAppender(route, event);
        if (app == null) {
            return null;
        }
        CreatedRouteAppenderControl created = new CreatedRouteAppenderControl(app);
        control = created;
        createdAppenders.put(key, created);
    }

    if (control != null) {
        control.checkout();
    }
    return control;
}
 
Example #30
Source File: TestConfigurator.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testInitialize_Name_PathName() throws Exception {
    ctx = Configurator.initialize("Test1", "target/test-classes/log4j2-config.xml");
    LogManager.getLogger("org.apache.test.TestConfigurator");
    Configuration config = ctx.getConfiguration();
    assertNotNull("No configuration", config);
    assertEquals("Incorrect Configuration.", CONFIG_NAME, config.getName());
    final Map<String, Appender> map = config.getAppenders();
    assertNotNull("Appenders map should not be null.", map);
    assertThat(map, hasSize(greaterThan(0)));
    assertThat("Wrong configuration", map, hasKey("List"));
    Configurator.shutdown(ctx);
    config = ctx.getConfiguration();
    assertEquals("Unexpected Configuration.", NullConfiguration.NULL_NAME, config.getName());
}