Java 类org.apache.logging.log4j.core.Appender 实例源码

项目:alog    文件:AlogBenchmark.java   
@Setup
public void start() {
    counter = 0;
    if (log == null) {
        System.setProperty(
                "Log4jContextSelector",
                "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector");
        LoggerContext context = LoggerContext.getContext();
        log = context.getLogger("Log4j2");
        log.setAdditive(false);
        ArrayList<Appender> list = new ArrayList<Appender>();
        list.addAll(log.getAppenders().values());
        for (Appender a : list) {
            log.removeAppender(a);
        }
    }
}
项目:cas-5.1.0    文件:LoggingOutputSocketMessagingController.java   
private void registerLogFileTailThreads() throws IOException {
    final Collection<String> outputFileNames = new HashSet<>();
    final Collection<Appender> loggerAppenders = this.loggerContext.getConfiguration().getAppenders().values();
    loggerAppenders.forEach(appender -> {
        if (appender instanceof FileAppender) {
            outputFileNames.add(((FileAppender) appender).getFileName());
        } else if (appender instanceof RandomAccessFileAppender) {
            outputFileNames.add(((RandomAccessFileAppender) appender).getFileName());
        } else if (appender instanceof RollingFileAppender) {
            outputFileNames.add(((RollingFileAppender) appender).getFileName());
        } else if (appender instanceof MemoryMappedFileAppender) {
            outputFileNames.add(((MemoryMappedFileAppender) appender).getFileName());
        } else if (appender instanceof RollingRandomAccessFileAppender) {
            outputFileNames.add(((RollingRandomAccessFileAppender) appender).getFileName());
        }
    });

    outputFileNames.forEach(s -> {
        final Tailer t = new Tailer(new File(s), new LogTailerListener(), 100, false, true);
        final Thread thread = new Thread(t);
        thread.setPriority(Thread.MIN_PRIORITY);
        thread.setName(s);
        thread.start();
    });
}
项目:dubbo2    文件:Log4j2LoggerAdapter.java   
public Log4j2LoggerAdapter() {
    try {
        org.apache.logging.log4j.Logger logger = LogManager.getLogger();
        if (logger != null) {
            Map<String, Appender> appenderMap = ((org.apache.logging.log4j.core.Logger) logger).getAppenders();
            for (Map.Entry<String, Appender> entry : appenderMap.entrySet()) {
                if (entry.getValue() instanceof FileAppender) {
                    String filename = ((FileAppender) entry.getValue()).getFileName();
                    file = new File(filename);
                    break;
                }
            }
        }
    } catch (Throwable t) {
    }
}
项目:datarouter    文件:BaseLog4j2Configuration.java   
protected final void registerParent(Class<? extends BaseLog4j2Configuration> clazz){
    BaseLog4j2Configuration configuration;
    try{
        configuration = clazz.newInstance();
    }catch(InstantiationException | IllegalAccessException e){
        throw new RuntimeException(e);
    }
    for(Appender appender : configuration.getAppenders()){
        addAppender(appender);
    }
    for(LoggerConfig loggerConfig : configuration.getLoggerConfigs()){
        addLoggerConfig(loggerConfig.getName(), loggerConfig.getLevel(), loggerConfig.isAdditive(), loggerConfig
                .getAppenders().values());
    }
    for(Filter filter : configuration.getFilters()){
        addFilter(filter);
    }
}
项目:ArchUnit    文件:LogTestRule.java   
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(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();
}
项目:monarch    文件:LogServiceIntegrationJUnitTest.java   
@Test
public void removeAndRestoreConsoleAppenderShouldAffectRootLogger() {
  LogService.reconfigure();

  assertThat(LogService.isUsingGemFireDefaultConfig()).as(LogService.getConfigInformation())
      .isTrue();

  final Logger rootLogger = (Logger) LogService.getRootLogger();

  // assert "Console" is present for ROOT
  Appender appender = rootLogger.getAppenders().get(LogService.STDOUT);
  assertThat(appender).isNotNull();

  LogService.removeConsoleAppender();

  // assert "Console" is not present for ROOT
  appender = rootLogger.getAppenders().get(LogService.STDOUT);
  assertThat(appender).isNull();

  LogService.restoreConsoleAppender();

  // assert "Console" is present for ROOT
  appender = rootLogger.getAppenders().get(LogService.STDOUT);
  assertThat(appender).isNotNull();
}
项目:xsharing-services-router    文件:LogFileRetriever.java   
/**
 * We cannot presume that the default file name/location setting won't be changed by the user.
 * Therefore, we should be able to retrieve that info from the underlying logging mechanism
 * by iterating over appenders.
 */
private List<Path> getActiveLogFilePaths() {
    LoggerContextFactory factory = LogManager.getFactory();
    ContextSelector selector = ((Log4jContextFactory) factory).getSelector();

    List<Path> fileNameList = new ArrayList<>();
    for (LoggerContext ctx : selector.getLoggerContexts()) {
        for (Appender appender : ctx.getConfiguration().getAppenders().values()) {
            String fileName = extractFileName(appender);
            if (fileName != null) {
                fileNameList.add(Paths.get(fileName));
            }
        }
    }
    return fileNameList;
}
项目:xsharing-services-router    文件:LogFileRetriever.java   
/**
 * File appender types do not share a "write-to-file" superclass.
 */
private String extractFileName(Appender a) {
    if (a instanceof FileAppender) {
        return ((FileAppender) a).getFileName();

    } else if (a instanceof RollingFileAppender) {
        return ((RollingFileAppender) a).getFileName();

    } else if (a instanceof RollingRandomAccessFileAppender) {
        return ((RollingRandomAccessFileAppender) a).getFileName();

    } else if (a instanceof RandomAccessFileAppender) {
        return ((RandomAccessFileAppender) a).getFileName();

    } else if (a instanceof MemoryMappedFileAppender) {
        return ((MemoryMappedFileAppender) a).getFileName();

    } else {
        return null;
    }
}
项目:log4j2-elasticsearch    文件:AppenderRefFailoverPolicyTest.java   
@Test
public void deliversToAppenderRef() {

    // 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 = createTestFailoverPolicy(testAppenderRef, configuration);

    String failedMessage = "test failed message";

    // when
    failoverPolicy.deliver(failedMessage);

    // then
    verify(appender, times(1)).append(any(LogEvent.class));
}
项目:log4j2-elasticsearch    文件:AppenderRefFailoverPolicyTest.java   
@Test
public void resolvesAppenderRefOnlyOnce() {

    // 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 = createTestFailoverPolicy(testAppenderRef, configuration);

    String failedMessage = "test failed message";

    // when
    failoverPolicy.deliver(failedMessage);
    failoverPolicy.deliver(failedMessage);

    // then
    verify(configuration, times(1)).getAppender(anyString());
    verify(appender, times(2)).append(any(LogEvent.class));
}
项目:log4j2-elasticsearch    文件:AppenderRefFailoverPolicyTest.java   
@Test(expected = ConfigurationException.class)
public void throwsExceptionOnUnresolvedAppender() {

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

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

    String failedMessage = "test failed message";

    // when
    failoverPolicy.deliver(failedMessage);

}
项目:steve-plugsurfing    文件:LogFileRetriever.java   
/**
 * We cannot presume that the default file name/location setting won't be changed by the user.
 * Therefore, we should be able to retrieve that info from the underlying logging mechanism
 * by iterating over appenders.
 */
private List<Path> getActiveLogFilePaths() {
    LoggerContextFactory factory = LogManager.getFactory();
    ContextSelector selector = ((Log4jContextFactory) factory).getSelector();

    List<Path> fileNameList = new ArrayList<>();
    for (LoggerContext ctx : selector.getLoggerContexts()) {
        for (Appender appender : ctx.getConfiguration().getAppenders().values()) {
            String fileName = extractFileName(appender);
            if (fileName != null) {
                fileNameList.add(Paths.get(fileName));
            }
        }
    }
    return fileNameList;
}
项目:steve-plugsurfing    文件:LogFileRetriever.java   
/**
 * File appender types do not share a "write-to-file" superclass.
 */
private String extractFileName(Appender a) {
    if (a instanceof FileAppender) {
        return ((FileAppender) a).getFileName();

    } else if (a instanceof RollingFileAppender) {
        return ((RollingFileAppender) a).getFileName();

    } else if (a instanceof RollingRandomAccessFileAppender) {
        return ((RollingRandomAccessFileAppender) a).getFileName();

    } else if (a instanceof RandomAccessFileAppender) {
        return ((RandomAccessFileAppender) a).getFileName();

    } else if (a instanceof MemoryMappedFileAppender) {
        return ((MemoryMappedFileAppender) a).getFileName();

    } else {
        return null;
    }
}
项目:microservice-mock    文件:LogManagerTest.java   
/**
 * This test asserts that after re-configuration of the log engine the total appenders are
 * different. The 'comparison' will be done between:
 *
 * - default config (src/main/resources/log4j2.xml)
 * - alternative config (src/test/resources/xml/config-for-LogManagerTest.xml)
 */
@Test (groups = { GROUP_CHANGE_CONFIG }, description = "Validate the numbers of Appenders associated with the LoggerContext")
public void testLogReconfiguration() {
    LOGGER.debug("About to test re-configuration of the logger context");
    final String pathToAlternativeLogConfig = "src/test/resources/config/log/config-for-LogManagerTest.xml";
    LoggerContext loggerContext = LoggerContext.getContext(false);
    Configuration configuration = loggerContext.getConfiguration();
    Map<String, Appender> appenderMap = configuration.getAppenders();
    Assert.assertTrue(appenderMap.size() == 1, "Expected 1 appender");
    Assert.assertTrue(appenderMap.containsKey("console"));

    LogManager.initializeLogging(pathToAlternativeLogConfig);
    // Refresh reference of configuration as it changed
    configuration = loggerContext.getConfiguration();
    appenderMap = configuration.getAppenders();
    Assert.assertTrue(appenderMap.size() == 2, "Expected 2 appenders");
    Assert.assertTrue(appenderMap.containsKey("console"));
    Assert.assertTrue(appenderMap.containsKey("filterAppender"));
}
项目:ColorConsole    文件:ColorConsoleBukkit.java   
@Override
public void onDisable() {
    //restore the old format
    Appender terminalAppender = CommonLogInstaller.getTerminalAppender(TERMINAL_NAME);
    Logger rootLogger = ((Logger) LogManager.getRootLogger());

    ColorPluginAppender colorPluginAppender = null;
    for (Appender value : rootLogger.getAppenders().values()) {
        if (value instanceof ColorPluginAppender) {
            colorPluginAppender = (ColorPluginAppender) value;
            break;
        }
    }

    if (colorPluginAppender != null) {
        rootLogger.removeAppender(terminalAppender);
        rootLogger.addAppender(colorPluginAppender.getOldAppender());
    }

    try {
        CommonLogInstaller.setLayout(oldLayout, terminalAppender);
    } catch (ReflectiveOperationException ex) {
        getLogger().log(Level.WARNING, "Cannot revert log format", ex);
    }
}
项目:camel-standalone    文件:StandaloneLoggerConfiguration.java   
/**
 * Constructor to create the default configuration.
 */
public StandaloneLoggerConfiguration(ConfigurationSource source) {
    super(source);

    setName(CONFIG_NAME);
    final Appender appender = StandaloneLogEventAppender.createAppender("StandaloneLogAppender", 1000);
    appender.start();
    addAppender(appender);
    final LoggerConfig root = getRootLogger();
    root.addAppender(appender, null, null);

    final String levelName = PropertiesUtil.getProperties().getStringProperty(DEFAULT_LEVEL);
    final Level level = levelName != null && Level.valueOf(levelName) != null ?
            Level.valueOf(levelName) : Level.ALL;
    root.setLevel(level);
}
项目:camel-standalone    文件:Standalone.java   
protected void configureLogging() {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = ctx.getConfiguration();
    Layout layout = PatternLayout.createLayout(PatternLayout.SIMPLE_CONVERSION_PATTERN, null, config, null, null,
            true, false, null, null);
    Appender appender = FileAppender.createAppender(workDir + "/logs/camel-standalone.log", "false", "false", "File", "true",
            "false", "false", "4000", layout, null, "false", null, config);
    appender.start();
    config.addAppender(appender);
    AppenderRef ref = AppenderRef.createAppenderRef("File", null, null);
    AppenderRef[] refs = new AppenderRef[] {ref};
    LoggerConfig loggerConfig = LoggerConfig.createLogger("false", Level.INFO, "StandaloneFileLoggerConfig",
            "true", refs, null, config, null );
    loggerConfig.addAppender(appender, null, null);
    config.addLogger("StandaloneFileLoggerConfig", loggerConfig);
    ctx.updateLoggers();
}
项目:herd    文件:Log4j2LoggingHelper.java   
@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;
}
项目:homework_tester    文件:Main.java   
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");
}
项目:homework_tester    文件:Main.java   
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");
}
项目:core-ng-project    文件:ESLoggerConfigFactory.java   
public static void bindLogger() {
    LoggerContext context = (LoggerContext) LogManager.getContext(false);
    Configuration config = context.getConfiguration();

    Map<String, ESLogger> loggers = Maps.newConcurrentHashMap();
    Appender appender = new AbstractAppender("", null, null) {
        @Override
        public void append(LogEvent event) {
            String name = event.getLoggerName();
            ESLogger logger = loggers.computeIfAbsent(name, key -> new ESLogger(key, null, (LoggerImpl) LoggerFactory.getLogger(key)));
            logger.log(event.getLevel(), event.getMarker(), event.getMessage(), event.getThrown());
        }
    };
    appender.start();
    config.addAppender(appender);

    LoggerConfig loggerConfig = new LoggerConfig("", Level.ALL, false);
    loggerConfig.addAppender(appender, null, null);
    config.addLogger("", loggerConfig);
    context.updateLoggers();
}
项目:log4j-configuration-builder    文件:ConfigurationBuilder.java   
/**
 * Ctor. The configuration is built using instance of
 * {@link Spec}:
 * 
 * <ul>
 * <li>The name is set to {@link Spec#getName()}.
 * <li>Appenders from the parent object are cleared.
 * <li>{@link Appender}s are created
 * {@link #buildAppenders(Spec)}.
 * <li>{@link LoggerConfig}s are created using
 * {@link #buildLoggerConfigs(Spec)}.
 * <li>Every {@link LoggerConfig} is configured with its
 * {@link Appender} using
 * {@link #configureLoggerAppenders(Spec, Map, Map)}.
 * <li>Root loggers are configured.
 * </ul>
 * 
 * @param spec
 */
EmbeddedConfiguration(Spec spec) {
  super(ConfigurationSource.NULL_SOURCE);
  setName(spec.getName());

  // Clean up first
  getAppenders().clear();
  getRootLogger().getAppenders().clear();

  // Build Appenders
  final Map<String, Appender> appenders = buildAppenders(spec);
  final Map<String, SyslogAppender> syslogAppenders = buildSyslogAppenders(spec);

  // Build Logger Configs
  final Map<String, LoggerConfig> loggers = buildLoggerConfigs(spec);

  // Configure loggers with appenders
  configureLoggerAppenders(spec, appenders, loggers);

  // Configure root logger appenders
  configureRootLogger(spec, appenders, syslogAppenders);
}
项目:syncope    文件:LoggerLoader.java   
public void addAppenderToContext(
        final LoggerContext ctx,
        final AuditAppender auditAppender,
        final LoggerConfig eventLogConf) {

    Appender targetAppender = ctx.getConfiguration().getAppender(auditAppender.getTargetAppenderName());
    if (targetAppender == null) {
        targetAppender = auditAppender.getTargetAppender();
    }
    targetAppender.start();
    ctx.getConfiguration().addAppender(targetAppender);
    if (auditAppender.isRewriteEnabled()) {
        RewriteAppender rewriteAppender = ctx.getConfiguration().getAppender(auditAppender.
                getTargetAppenderName() + "_rewrite");
        if (rewriteAppender == null) {
            rewriteAppender = auditAppender.getRewriteAppender();
        }
        rewriteAppender.start();
        ctx.getConfiguration().addAppender(rewriteAppender);
        eventLogConf.addAppender(rewriteAppender, Level.DEBUG, null);
    } else {
        eventLogConf.addAppender(targetAppender, Level.DEBUG, null);
    }
}
项目:elasticsearch-support-diagnostics    文件:Diagnostic.java   
private void createFileAppender(DiagnosticContext ctx) {

      String logDir = ctx.getTempDir() + SystemProperties.fileSeparator + "diagnostics.log";

      final LoggerContext context = (LoggerContext) LogManager.getContext(false);
      final Configuration config = context.getConfiguration();
      Layout layout = PatternLayout.createLayout("%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n", null, config, null,
         null,true, true, null, null );
      Appender appender = FileAppender.createAppender(logDir, "false", "false", "File", "true",
         "false", "false", "0", layout, null, "false", null, config);
      appender.start();
      config.addAppender(appender);
      AppenderRef ref = AppenderRef.createAppenderRef("File", null, null);
      AppenderRef[] refs = new AppenderRef[] {ref};

      config.getRootLogger().addAppender(appender, null, null);
      context.updateLoggers();
      Logger testLog = LogManager.getLogger();
      testLog.error("Testing");
   }
项目:log4j2    文件:CatchingTagTest.java   
private void verify(final String expected) {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Map<String, Appender> list = ctx.getConfiguration().getAppenders();
    final Appender listApp = list.get("List");
    assertNotNull("Missing Appender", listApp);
    assertTrue("Not a ListAppender", listApp instanceof ListAppender);
    final List<String> events = ((ListAppender) listApp).getMessages();
    try
    {
        assertEquals("Incorrect number of messages.", 1, events.size());
        assertEquals("Incorrect message.", "o.a.l.l.t.CatchingTagTest " + expected, events.get(0));
    }
    finally
    {
        ((ListAppender) listApp).clear();
    }
}
项目:logging-log4j2    文件:TestConfigurator.java   
@Test
public void testInitialize_NullClassLoader_ConfigurationSourceWithInputStream_NoId() throws Exception {
    final InputStream is = new FileInputStream("target/test-classes/log4j2-config.xml");
    final ConfigurationSource source =
        new ConfigurationSource(is);
    ctx = Configurator.initialize(null, source);
    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());
}
项目:logging-log4j2    文件:HttpAppenderTest.java   
@Test
public void testAppend() throws Exception {
    wireMockRule.stubFor(post(urlEqualTo("/test/log4j/"))
        .willReturn(SUCCESS_RESPONSE));

    final Appender appender = HttpAppender.newBuilder()
        .withName("Http")
        .withLayout(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 + "\"")));
}
项目:logging-log4j2    文件:ConfigurationTest.java   
@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.size(), is(equalTo(1)));
    final Appender appender = appenders.get(APPENDER_NAME);
    assertThat(appender, is(notNullValue()));
    assertThat(appender.getName(), is(equalTo("STDOUT")));
}
项目:log4j2    文件:BaseConfiguration.java   
/**
 * Tear down the configuration.
 */
@Override
public void stop() {
    // Stop the appenders in reverse order in case they still have activity.
    final Appender[] array = appenders.values().toArray(new Appender[appenders.size()]);
    for (int i = array.length - 1; i >= 0; --i) {
        array[i].stop();
    }
    for (final LoggerConfig logger : loggers.values()) {
        logger.clearAppenders();
        logger.stopFilter();
    }
    root.stopFilter();
    stopFilter();
    if (advertiser != null && advertisement != null)
    {
        advertiser.unadvertise(advertisement);
    }
}
项目:log4j2    文件:BaseConfiguration.java   
private void setToDefault() {
    setName(DefaultConfiguration.DEFAULT_NAME);
    final Layout<? extends Serializable> layout =
            PatternLayout.createLayout("%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n",
                    null, null, null, null);
    final Appender appender = ConsoleAppender.createAppender(layout, null, "SYSTEM_OUT", "Console", "false",
        "true");
    appender.start();
    addAppender(appender);
    final LoggerConfig root = getRootLogger();
    root.addAppender(appender, null, null);

    final String levelName = PropertiesUtil.getProperties().getStringProperty(DefaultConfiguration.DEFAULT_LEVEL);
    final Level level = levelName != null && Level.valueOf(levelName) != null ?
        Level.valueOf(levelName) : Level.ERROR;
    root.setLevel(level);
}
项目:logging-log4j2    文件:TestConfigurator.java   
@Test
public void testEnvironment() throws Exception {
    ctx = Configurator.initialize("-config", null);
    LogManager.getLogger("org.apache.test.TestConfigurator");
    final 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("No ListAppender named List2", map, hasKey("List2"));
    final Appender app = map.get("List2");
    final Layout<? extends Serializable> layout = app.getLayout();
    assertNotNull("Appender List2 does not have a Layout", layout);
    assertThat("Appender List2 is not configured with a PatternLayout", layout, instanceOf(PatternLayout.class));
    final String pattern = ((PatternLayout) layout).getConversionPattern();
    assertNotNull("No conversion pattern for List2 PatternLayout", pattern);
    assertFalse("Environment variable was not substituted", pattern.startsWith("${env:PATH}"));
}
项目:logging-log4j2    文件:AppenderSet.java   
public Appender createAppender(final String appenderName, final String actualName) {
    final Node node = nodeMap.get(appenderName);
    if (node == null) {
        LOGGER.error("No node named {} in {}", appenderName, this);
        return null;
    }
    node.getAttributes().put("name", actualName);
    if (node.getType().getElementName().equals(Appender.ELEMENT_TYPE)) {
        final Node appNode = new Node(node);
        configuration.createConfiguration(appNode, null);
        if (appNode.getObject() instanceof Appender) {
            final Appender app = appNode.getObject();
            app.start();
            return app;
        }
        LOGGER.error("Unable to create Appender of type " + node.getName());
        return null;
    }
    LOGGER.error("No Appender was configured for name {} " + appenderName);
    return null;
}
项目:logging-log4j2    文件:RollingFilePropertiesTest.java   
@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!");
}
项目:log4j2    文件:DefaultConfiguration.java   
/**
 * Constructor to create the default configuration.
 */
public DefaultConfiguration() {

    setName(DEFAULT_NAME);
    final Layout<? extends Serializable> layout =
            PatternLayout.createLayout("%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n", null, null, null, null);
    final Appender appender =
            ConsoleAppender.createAppender(layout, null, "SYSTEM_OUT", "Console", "false", "true");
    appender.start();
    addAppender(appender);
    final LoggerConfig root = getRootLogger();
    root.addAppender(appender, null, null);

    final String levelName = PropertiesUtil.getProperties().getStringProperty(DEFAULT_LEVEL);
    final Level level = levelName != null && Level.valueOf(levelName) != null ?
        Level.valueOf(levelName) : Level.ERROR;
    root.setLevel(level);
}
项目:log4j2    文件:RewriteAppender.java   
@Override
public void start() {
    final Map<String, Appender> map = config.getAppenders();
    for (final AppenderRef ref : appenderRefs) {
        final String name = ref.getRef();
        final Appender appender = map.get(name);
        if (appender != null) {
            final Filter filter = appender instanceof AbstractAppender ?
                ((AbstractAppender) appender).getFilter() : null;
            appenders.put(name, new AppenderControl(appender, ref.getLevel(), filter));
        } else {
            LOGGER.error("Appender " + ref + " cannot be located. Reference ignored");
        }
    }
    super.start();
}
项目:logging-log4j2    文件:RoutingAppender.java   
@Override
public boolean stop(final long timeout, final TimeUnit timeUnit) {
    setStopping();
    super.stop(timeout, timeUnit, false);
    final Map<String, Appender> map = configuration.getAppenders();
    for (final Map.Entry<String, AppenderControl> entry : appenders.entrySet()) {
        final Appender appender = entry.getValue().getAppender();
        if (!map.containsKey(appender.getName())) {
            if (appender instanceof LifeCycle2) {
                ((LifeCycle2) appender).stop(timeout, timeUnit);
            } else {
                appender.stop();
            }
        }
    }
    setStopped();
    return true;
}
项目:log4j2    文件:FailoverAppender.java   
@Override
public void start() {
    final Map<String, Appender> map = config.getAppenders();
    int errors = 0;
    if (map.containsKey(primaryRef)) {
        primary = new AppenderControl(map.get(primaryRef), null, null);
    } else {
        LOGGER.error("Unable to locate primary Appender " + primaryRef);
        ++errors;
    }
    for (final String name : failovers) {
        if (map.containsKey(name)) {
            failoverAppenders.add(new AppenderControl(map.get(name), null, null));
        } else {
            LOGGER.error("Failover appender " + name + " is not configured");
        }
    }
    if (failoverAppenders.size() == 0) {
        LOGGER.error("No failover appenders are available");
        ++errors;
    }
    if (errors == 0) {
        super.start();
    }
}
项目:logging-log4j2    文件:AbstractConfiguration.java   
/**
 * 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) {
    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();
    }
}
项目:logging-log4j2    文件:PropertiesConfigurationRootLoggerOnlyTest.java   
@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!");
}
项目:logging-log4j2    文件:HttpAppenderTest.java   
@Test
public void testAppendHttps() throws Exception {
    wireMockRule.stubFor(post(urlEqualTo("/test/log4j/"))
        .willReturn(SUCCESS_RESPONSE));

    final Appender appender = HttpAppender.newBuilder()
        .withName("Http")
        .withLayout(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(), TestConstants.KEYSTORE_TYPE, null),
            TrustStoreConfiguration.createKeyStoreConfiguration(TestConstants.TRUSTSTORE_FILE, TestConstants.TRUSTSTORE_PWD(), 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 + "\"")));
}