org.apache.logging.log4j.core.appender.ConsoleAppender Java Examples

The following examples show how to use org.apache.logging.log4j.core.appender.ConsoleAppender. 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: 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 #2
Source File: CustomConfiguration.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor to create the default configuration.
 */
public CustomConfiguration(final LoggerContext loggerContext, final ConfigurationSource source) {
    super(loggerContext, source);

    setName(CONFIG_NAME);
    final Layout<? extends Serializable> layout = PatternLayout.newBuilder()
            .setPattern(DEFAULT_PATTERN)
            .setConfiguration(this)
            .build();
    final Appender appender = ConsoleAppender.createDefaultAppenderForLayout(layout);
    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);
}
 
Example #3
Source File: SimpleConfiguratorIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenDefaultLog4j2Environment_whenProgrammaticallyConfigured_thenLogsCorrectly() {
    ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
    AppenderComponentBuilder console = builder.newAppender("Stdout", "CONSOLE")
            .addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT);
    console.add(builder.newLayout("PatternLayout")
            .addAttribute("pattern", "%d [%t] %-5level: %msg%n%throwable"));
    builder.add(console);
    builder.add(builder.newLogger("com", Level.DEBUG)
            .add(builder.newAppenderRef("Stdout"))
            .addAttribute("additivity", false));
    builder.add(builder.newRootLogger(Level.ERROR)
            .add(builder.newAppenderRef("Stdout")));
    Configurator.initialize(builder.build());
    LogPrinter logPrinter = new LogPrinter();
    logPrinter.printlog();
}
 
Example #4
Source File: ConsoleAppenderBuilder.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private <T extends Log4j1Configuration> Appender createAppender(String name, Layout layout, Filter filter,
        String level, String target, T configuration) {
    org.apache.logging.log4j.core.Layout<?> consoleLayout = null;

    if (layout instanceof LayoutWrapper) {
        consoleLayout = ((LayoutWrapper) layout).getLayout();
    } else if (layout != null) {
        consoleLayout = new LayoutAdapter(layout);
    }
    org.apache.logging.log4j.core.Filter consoleFilter = buildFilters(level, filter);
    ConsoleAppender.Target consoleTarget = SYSTEM_ERR.equals(target)
            ? ConsoleAppender.Target.SYSTEM_ERR : ConsoleAppender.Target.SYSTEM_OUT;
    return new AppenderWrapper(ConsoleAppender.newBuilder()
            .setName(name)
            .setTarget(consoleTarget)
            .setLayout(consoleLayout)
            .setFilter(consoleFilter)
            .setConfiguration(configuration)
            .build());
}
 
Example #5
Source File: Main.java    From homework_tester with MIT License 6 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 #6
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 #7
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 #8
Source File: AbstractConfiguration.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
protected void setToDefault() {
    // LOG4J2-1176 facilitate memory leak investigation
    setName(DefaultConfiguration.DEFAULT_NAME + "@" + Integer.toHexString(hashCode()));
    final Layout<? extends Serializable> layout = PatternLayout.newBuilder()
            .setPattern(DefaultConfiguration.DEFAULT_PATTERN)
            .setConfiguration(this)
            .build();
    final Appender appender = ConsoleAppender.createDefaultAppenderForLayout(layout);
    appender.start();
    addAppender(appender);
    final LoggerConfig rootLoggerConfig = getRootLogger();
    rootLoggerConfig.addAppender(appender, null, null);

    final Level defaultLevel = Level.ERROR;
    final String levelName = PropertiesUtil.getProperties().getStringProperty(DefaultConfiguration.DEFAULT_LEVEL,
            defaultLevel.name());
    final Level level = Level.valueOf(levelName);
    rootLoggerConfig.setLevel(level != null ? level : defaultLevel);
}
 
Example #9
Source File: TestConfigurator.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuilder() throws Exception {
    final ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
    builder.setStatusLevel(Level.ERROR);
    builder.setConfigurationName("BuilderTest");
    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).
            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)));
}
 
Example #10
Source File: Log4j2ConfigurationFactoryTest.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@Test
void testSoutJsonTempJson() {
    Configuration configuration = getLogConfig(Map.of("log_format_sout", "json"));

    assertThat(configuration.getAppenders().values()).hasSize(2);
    Optional<ConsoleAppender> consoleAppender = configuration.getAppenders().values().stream()
        .filter(ConsoleAppender.class::isInstance)
        .map(ConsoleAppender.class::cast)
        .findAny();
    assertThat(consoleAppender).isNotEmpty();
    assertThat(consoleAppender.get().getLayout()).isInstanceOf(EcsLayout.class);

    Optional<RollingFileAppender> fileAppender = configuration.getAppenders().values().stream()
        .filter(RollingFileAppender.class::isInstance)
        .map(RollingFileAppender.class::cast)
        .findAny();
    assertThat(fileAppender).isNotEmpty();
    assertThat(fileAppender.get().getLayout()).isInstanceOf(EcsLayout.class);
}
 
Example #11
Source File: Log4j2ConfigurationFactoryTest.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@Test
void testSoutPlainTextTempJson() {
    Configuration configuration = getLogConfig(Map.of());

    assertThat(configuration.getAppenders().values()).hasSize(2);
    Optional<ConsoleAppender> consoleAppender = configuration.getAppenders().values().stream()
        .filter(ConsoleAppender.class::isInstance)
        .map(ConsoleAppender.class::cast)
        .findAny();
    assertThat(consoleAppender).isNotEmpty();
    assertThat(consoleAppender.get().getLayout()).isInstanceOf(PatternLayout.class);

    Optional<RollingFileAppender> fileAppender = configuration.getAppenders().values().stream()
        .filter(RollingFileAppender.class::isInstance)
        .map(RollingFileAppender.class::cast)
        .findAny();
    assertThat(fileAppender).isNotEmpty();
    assertThat(fileAppender.get().getLayout()).isInstanceOf(EcsLayout.class);
}
 
Example #12
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 #13
Source File: RollingFileAppenderUpdateDataTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private ConfigurationBuilder<BuiltConfiguration> buildConfigurationBuilder(final String filePattern) {
    final ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
    builder.setConfigurationName("LOG4J2-1964 demo");
    builder.setStatusLevel(Level.ERROR);
    // @formatter:off
    builder.add(builder.newAppender("consoleLog", "Console")
        .addAttribute("target", ConsoleAppender.Target.SYSTEM_ERR));
    builder.add(builder.newAppender("fooAppender", "RollingFile")
            .addAttribute("fileName", "target/rolling-update-date/foo.log")
            .addAttribute("filePattern", filePattern)
            .addComponent(builder.newComponent("SizeBasedTriggeringPolicy")
                    .addAttribute("size", "10MB")));
    builder.add(builder.newRootLogger(Level.INFO)
            .add(builder.newAppenderRef("consoleLog"))
            .add(builder.newAppenderRef("fooAppender")));
    // @formatter:on
    return builder;
}
 
Example #14
Source File: CustomConfigurationFactory.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
public static Configuration addTestFixtures(final String name, final ConfigurationBuilder<BuiltConfiguration> builder) {
    builder.setConfigurationName(name);
    builder.setStatusLevel(Level.ERROR);
    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.newRootLogger(Level.ERROR).add(builder.newAppenderRef("Stdout")));

    builder.add(builder.newCustomLevel("Panic", 17));

    return builder.build();
}
 
Example #15
Source File: Log4j1ConfigurationFactoryTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private Layout<?> testConsole(final String configResource) throws Exception {
    final Configuration configuration = getConfiguration(configResource);
    final String name = "Console";
    final ConsoleAppender appender = configuration.getAppender(name);
    assertNotNull("Missing appender '" + name + "' in configuration " + configResource + " → " + configuration,
            appender);
    assertEquals(Target.SYSTEM_ERR, appender.getTarget());
    //
    final LoggerConfig loggerConfig = configuration.getLoggerConfig("com.example.foo");
    assertNotNull(loggerConfig);
    assertEquals(Level.DEBUG, loggerConfig.getLevel());
    configuration.start();
    configuration.stop();
    return appender.getLayout();
}
 
Example #16
Source File: LookupTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testHostname() {
    final ConsoleAppender app = context.getRequiredAppender("console", ConsoleAppender.class);
    final Layout<?> layout = app.getLayout();
    assertNotNull("No Layout", layout);
    assertTrue("Layout is not a PatternLayout", layout instanceof PatternLayout);
    final String pattern = ((PatternLayout) layout).getConversionPattern();
    assertNotNull("No conversion pattern", pattern);
    assertTrue("No filters", pattern.contains("org.junit,org.apache.maven,org.eclipse,sun.reflect,java.lang.reflect"));
}
 
Example #17
Source File: LoggingConfigurator.java    From jmeter-plugins with Apache License 2.0 5 votes vote down vote up
public void configure() {
    PatternLayout.Builder patternBuilder = PatternLayout.newBuilder();
    patternBuilder.withPattern("%d %p %c{1.}: %m%n");
    PatternLayout layout = patternBuilder.build();

    ConsoleAppender consoleAppender = ConsoleAppender.createDefaultAppenderForLayout(layout);
    consoleAppender.start();

    Configuration configuration = ((LoggerContext) LogManager.getContext(false)).getConfiguration();

    LoggerConfig rootLogger = configuration.getRootLogger();
    rootLogger.setLevel(Level.INFO);
    rootLogger.addAppender(consoleAppender, Level.INFO, null);
}
 
Example #18
Source File: Log4j1ConfigurationParser.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private void buildConsoleAppender(final String appenderName) {
    final AppenderComponentBuilder appenderBuilder = builder.newAppender(appenderName, ConsoleAppender.PLUGIN_NAME);
    final String targetValue = getLog4jAppenderValue(appenderName, "Target", "System.out");
    if (targetValue != null) {
        final ConsoleAppender.Target target;
        switch (targetValue) {
        case "System.out":
            target = ConsoleAppender.Target.SYSTEM_OUT;
            break;
        case "System.err":
            target = ConsoleAppender.Target.SYSTEM_ERR;
            break;
        default:
            reportWarning("Unknown value for console Target: " + targetValue);
            target = null;
        }
        if (target != null) {
            appenderBuilder.addAttribute("target", target);
        }
    }
    buildAttribute(appenderName, appenderBuilder, "Follow", "follow");
    if (FALSE.equalsIgnoreCase(getLog4jAppenderValue(appenderName, "ImmediateFlush"))) {
        reportWarning("ImmediateFlush=false is not supported on Console appender");
    }
    buildAppenderLayout(appenderName, appenderBuilder);
    builder.add(appenderBuilder);
}
 
Example #19
Source File: ConfigurationAssemblerTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private void validate(final Configuration config) {
    assertNotNull(config);
    assertNotNull(config.getName());
    assertFalse(config.getName().isEmpty());
    assertNotNull("No configuration created", config);
    assertEquals("Incorrect State: " + config.getState(), config.getState(), LifeCycle.State.STARTED);
    final Map<String, Appender> appenders = config.getAppenders();
    assertNotNull(appenders);
    assertTrue("Incorrect number of Appenders: " + appenders.size(), appenders.size() == 1);
    final ConsoleAppender consoleAppender = (ConsoleAppender)appenders.get("Stdout");
    final PatternLayout gelfLayout = (PatternLayout)consoleAppender.getLayout();
    final Map<String, LoggerConfig> loggers = config.getLoggers();
    assertNotNull(loggers);
    assertTrue("Incorrect number of LoggerConfigs: " + loggers.size(), loggers.size() == 2);
    final LoggerConfig rootLoggerConfig = loggers.get("");
    assertEquals(Level.ERROR, rootLoggerConfig.getLevel());
    assertFalse(rootLoggerConfig.isIncludeLocation());
    final LoggerConfig loggerConfig = loggers.get("org.apache.logging.log4j");
    assertEquals(Level.DEBUG, loggerConfig.getLevel());
    assertTrue(loggerConfig.isIncludeLocation());
    final Filter filter = config.getFilter();
    assertNotNull("No Filter", filter);
    assertTrue("Not a Threshold Filter", filter instanceof ThresholdFilter);
    final List<CustomLevelConfig> customLevels = config.getCustomLevels();
    assertNotNull("No CustomLevels", filter);
    assertEquals(1, customLevels.size());
    final CustomLevelConfig customLevel = customLevels.get(0);
    assertEquals("Panic", customLevel.getLevelName());
    assertEquals(17, customLevel.getIntLevel());
    final Logger logger = LogManager.getLogger(getClass());
    logger.info("Welcome to Log4j!");
}
 
Example #20
Source File: Log4j1ConfigurationParser.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private void buildConsoleAppender(final String appenderName) {
    final AppenderComponentBuilder appenderBuilder = builder.newAppender(appenderName, ConsoleAppender.PLUGIN_NAME);
    final String targetValue = getLog4jAppenderValue(appenderName, "Target", "System.out");
    if (targetValue != null) {
        final ConsoleAppender.Target target;
        switch (targetValue) {
        case "System.out":
            target = ConsoleAppender.Target.SYSTEM_OUT;
            break;
        case "System.err":
            target = ConsoleAppender.Target.SYSTEM_ERR;
            break;
        default:
            reportWarning("Unknown value for console Target: " + targetValue);
            target = null;
        }
        if (target != null) {
            appenderBuilder.addAttribute("target", target);
        }
    }
    buildAttribute(appenderName, appenderBuilder, "Follow", "follow");
    if (FALSE.equalsIgnoreCase(getLog4jAppenderValue(appenderName, "ImmediateFlush"))) {
        reportWarning("ImmediateFlush=false is not supported on Console appender");
    }
    buildAppenderLayout(appenderName, appenderBuilder);
    builder.add(appenderBuilder);
}
 
Example #21
Source File: Log4j1ConfigurationFactoryTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private Layout<?> testConsole(final String configResource) throws Exception {
    final Configuration configuration = getConfiguration(configResource);
    final String name = "Console";
    final ConsoleAppender appender = configuration.getAppender(name);
    assertNotNull("Missing appender '" + name + "' in configuration " + configResource + " → " + configuration,
            appender);
    assertEquals(Target.SYSTEM_ERR, appender.getTarget());
    //
    final LoggerConfig loggerConfig = configuration.getLoggerConfig("com.example.foo");
    assertNotNull(loggerConfig);
    assertEquals(Level.DEBUG, loggerConfig.getLevel());
    configuration.start();
    configuration.stop();
    return appender.getLayout();
}
 
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: 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 #24
Source File: CustomConfigurationFactory.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
static Configuration addTestFixtures(final String name, final ConfigurationBuilder<BuiltConfiguration> builder) {
    builder.setConfigurationName(name);
    builder.setStatusLevel(Level.ERROR);
    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.newRootLogger(Level.ERROR).add(builder.newAppenderRef("Stdout")));

    builder.add(builder.newCustomLevel("Panic", 17));

    return builder.build();
}
 
Example #25
Source File: ActorLogger.java    From actor4j-core with Apache License 2.0 5 votes vote down vote up
private ActorLogger() {
	loggerContext = (LoggerContext) LogManager.getContext(LogManager.class.getClassLoader(), false);
	Configuration config = loggerContext.getConfiguration();

	Appender systemConsoleAppender = ConsoleAppender.newBuilder()
		.setName(SYSTEM_CONSOLE_APPENDER_NAME)
		.setLayout(PatternLayout.newBuilder().withPattern(LAYOUT_CONSOLE_SYSTEM).build())
		.setConfiguration(config)
		.build();
	systemConsoleAppender.start();
    AppenderRef[] systemAppenderRefs = new AppenderRef[]{AppenderRef.createAppenderRef(SYSTEM_CONSOLE_APPENDER_NAME, null, null)};
    systemLoggerConfig = LoggerConfig.createLogger(false, Level.DEBUG, SYSTEM_LOGGER_NAME, "true", systemAppenderRefs, null, config, null);
    systemLoggerConfig.addAppender(systemConsoleAppender, null, null);
    
    Appender userConsoleAppender = ConsoleAppender.newBuilder()
		.setName(USER_CONSOLE_APPENDER_NAME)
		.setLayout(PatternLayout.newBuilder().withPattern(LAYOUT_CONSOLE_USER).build())
		.setConfiguration(config)
		.build();
	userConsoleAppender.start();
	AppenderRef[] userAppenderRefs = new AppenderRef[]{AppenderRef.createAppenderRef(USER_CONSOLE_APPENDER_NAME, null, null)};
	userLoggerConfig = LoggerConfig.createLogger(false, Level.DEBUG, USER_LOGGER_NAME, "true", userAppenderRefs, null, config, null);
	userLoggerConfig.addAppender(userConsoleAppender, null, null);

    config.addAppender(systemConsoleAppender);
    config.addAppender(userConsoleAppender);
    config.addLogger(SYSTEM_LOGGER_NAME, systemLoggerConfig);
    config.addLogger(USER_LOGGER_NAME, userLoggerConfig);
	loggerContext.updateLoggers(config);
}
 
Example #26
Source File: CompositeConfigurationTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void compositeLogger() {
    final LoggerContextRule lcr = new LoggerContextRule("classpath:log4j-comp-logger.xml,log4j-comp-logger.json");
    final Statement test = new Statement() {
        @Override
        public void evaluate() throws Throwable {
            final CompositeConfiguration config = (CompositeConfiguration) lcr.getConfiguration();
            Map<String, Appender> appendersMap = config.getLogger("cat1").getAppenders();
            assertEquals("Expected 2 Appender references for cat1 but got " + appendersMap.size(), 2,
                    appendersMap.size());
            assertTrue(appendersMap.get("STDOUT") instanceof ConsoleAppender);

            Filter loggerFilter = config.getLogger("cat1").getFilter();
            assertTrue(loggerFilter instanceof RegexFilter);
            assertEquals(loggerFilter.getOnMatch(), Filter.Result.DENY);

            appendersMap = config.getLogger("cat2").getAppenders();
            assertEquals("Expected 1 Appender reference for cat2 but got " + appendersMap.size(), 1,
                    appendersMap.size());
            assertTrue(appendersMap.get("File") instanceof FileAppender);

            appendersMap = config.getLogger("cat3").getAppenders();
            assertEquals("Expected 1 Appender reference for cat3 but got " + appendersMap.size(), 1,
                    appendersMap.size());
            assertTrue(appendersMap.get("File") instanceof FileAppender);

            appendersMap = config.getRootLogger().getAppenders();
            assertEquals("Expected 2 Appender references for the root logger but got " + appendersMap.size(), 2,
                    appendersMap.size());
            assertTrue(appendersMap.get("File") instanceof FileAppender);
            assertTrue(appendersMap.get("STDOUT") instanceof ConsoleAppender);

            assertEquals("Expected COMPOSITE_SOURCE for composite configuration but got " + config.getConfigurationSource(),
                    config.getConfigurationSource(), ConfigurationSource.COMPOSITE_SOURCE);
        }
    };
    runTest(lcr, test);
}
 
Example #27
Source File: LoggingMixin.java    From picocli with Apache License 2.0 5 votes vote down vote up
public static LoggerContext initializeLog4j() {
    ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
    builder.setStatusLevel(Level.ERROR); // show internal log4j2 errors
    builder.setConfigurationName("QuickAndDirtySetup");
    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"));
    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").addAttribute("level", Level.WARN)));
    return Configurator.initialize(builder.build());
}
 
Example #28
Source File: LogFactory.java    From chronus with Apache License 2.0 5 votes vote down vote up
public void start(Logger cfgLogger, String clKey) {
    //为false时,返回多个LoggerContext对象, true:返回唯一的单例LoggerContext
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = ctx.getConfiguration();
    List<AppenderRef> appenderRefs = new ArrayList<>();
    Map<String, Appender> appenderMap = ((org.apache.logging.log4j.core.Logger) cfgLogger).getAppenders();
    List<Appender> appenders = new ArrayList<>();
    appenderMap.forEach((key, appenderCfg) -> {
        Appender appender;
        if (appenderCfg instanceof ConsoleAppender) {
            appender = appenderCfg;
        } else {
            appender = getAppender(clKey, config, appenderCfg);
        }
        if (appender != null && appender.isStopped()) {
            appender.start();
        }
        if (appender != null) {
            AppenderRef ref = AppenderRef.createAppenderRef(appender.getName(), Level.ALL, null);
            appenderRefs.add(ref);
            appenders.add(appender);
        }
    });
    if (CollectionUtils.isEmpty(appenders)) {
        return;
    }
    AppenderRef[] refs = new AppenderRef[appenderRefs.size()];
    refs = appenderRefs.toArray(refs);
    LoggerConfig loggerConfig = LoggerConfig.createLogger(false, cfgLogger.getLevel(), clKey, "true", refs, null, config, null);
    appenders.stream().forEach(e ->
            loggerConfig.addAppender(e, Level.ALL, null)
    );
    config.addLogger(clKey, loggerConfig);
    ctx.updateLoggers(config);
}
 
Example #29
Source File: PGMServer.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
protected Logger setupLogger() {
  AnsiConsole.systemInstall();

  final java.util.logging.Logger global = java.util.logging.Logger.getLogger("");
  global.setUseParentHandlers(false);

  final Handler[] handlers = global.getHandlers();
  for (int i = 0; i < handlers.length; ++i) {
    global.removeHandler(handlers[i]);
  }

  global.addHandler(new ForwardLogHandler());
  org.apache.logging.log4j.Logger logger = LogManager.getRootLogger();

  if (logger instanceof org.apache.logging.log4j.core.Logger) {
    final Iterator<org.apache.logging.log4j.core.Appender> appenders =
        ((org.apache.logging.log4j.core.Logger) logger).getAppenders().values().iterator();
    while (appenders.hasNext()) {
      final org.apache.logging.log4j.core.Appender appender = appenders.next();
      if (appender instanceof ConsoleAppender) {
        ((org.apache.logging.log4j.core.Logger) logger).removeAppender(appender);
      }
    }
  }

  new Thread(new TerminalConsoleWriterThread(System.out, reader)).start();
  System.setOut(new PrintStream(new LoggerOutputStream(logger, Level.INFO), true));
  System.setErr(new PrintStream(new LoggerOutputStream(logger, Level.WARN), true));

  BasicConfigurator.resetConfiguration();

  try {
    return (Logger) PGMServer.class.getField("LOGGER").get(PGMServer.class);
  } catch (IllegalAccessException | NoSuchFieldException e) {
    // No-op
  }

  return logger;
}
 
Example #30
Source File: Log4j2ConfigurationFactoryTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Test
void testSoutPlainText() {
    Configuration configuration = getLogConfig(Map.of("ship_agent_logs", "false"));

    assertThat(configuration.getAppenders().values()).hasSize(1);
    Appender appender = configuration.getAppenders().values().iterator().next();

    assertThat(appender).isInstanceOf(ConsoleAppender.class);
    assertThat(appender.getLayout()).isInstanceOf(PatternLayout.class);
}