Java 类org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration 实例源码

项目:JukeBot    文件:Log4JConfig.java   
private Configuration createConfiguration(final String name, ConfigurationBuilder<BuiltConfiguration> builder) {

        builder.setConfigurationName(name);
        /* Only internal Log4J2 messages with level ERROR will be logged */
        builder.setStatusLevel(Level.ERROR);
        /* Create appender that logs to System.out */
        AppenderComponentBuilder appenderBuilder = builder.newAppender("STDOUT", "CONSOLE")
                .addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT);
        /* Create pattern for log messages */
        appenderBuilder.add(builder.newLayout("PatternLayout")
                .addAttribute("pattern", "[%d{HH:mm:ss}] (%c{1}) [%level] %msg%n%throwable"));
                                         /*timestamp  logger name  level   log message & optional throwable */
        builder.add(appenderBuilder);
        /* Create logger that uses STDOUT appender */
        builder.add(builder.newLogger("JukeBot", JUKEBOT_LOG_LEVEL)
                .add(builder.newAppenderRef("STDOUT"))
                .addAttribute("additivity", false));

        /* Create root logger--messages not from the above logger will all go through this one */
        builder.add(builder.newRootLogger(LIB_LOG_LEVEL).add(builder.newAppenderRef("STDOUT")));
        return builder.build();
    }
项目:log4j2-logstash-layout    文件:LogstashLayoutTest.java   
private void test_lineSeparator_suffix(LogEvent logEvent, boolean prettyPrintEnabled, SoftAssertions assertions) {

        // Create the layout.
        BuiltConfiguration config = ConfigurationBuilderFactory.newConfigurationBuilder().build();
        LogstashLayout layout = LogstashLayout
                .newBuilder()
                .setConfiguration(config)
                .setTemplateUri("classpath:LogstashJsonEventLayoutV1.json")
                .setPrettyPrintEnabled(prettyPrintEnabled)
                .build();

        // Check the serialized event.
        String serializedLogEvent = layout.toSerializable(logEvent);
        String assertionCaption = String.format("testing lineSeperator (prettyPrintEnabled=%s)", prettyPrintEnabled);
        assertions.assertThat(serializedLogEvent).as(assertionCaption).endsWith("}" + System.lineSeparator());

    }
项目:logredactor    文件:Log4j2RedactorTest.java   
protected Configuration buildConfiguration() {
  ConfigurationBuilder<BuiltConfiguration> builder = newConfigurationBuilder();
  builder.setConfigurationName(Log4j2RedactorTest.class.getName());
  builder.setStatusLevel(Level.INFO);

  AppenderComponentBuilder appenderBuilder = builder.newAppender("Stderr", "CONSOLE")
      .addAttribute("target", ConsoleAppender.Target.SYSTEM_ERR);
  appenderBuilder.add(builder.newLayout("PatternLayout")
      .addAttribute("pattern", "%msg"));
  builder.add(appenderBuilder);

  AppenderComponentBuilder rewriteBuilder = builder.newAppender("Redactor", "Rewrite")
      .addComponent(builder.newComponent("RedactorPolicy", "RedactorPolicy")
          .addAttribute("rules", resourcePath + getPolicyFilename()))
      .addComponent(builder.newAppenderRef("Stderr"));
  builder.add(rewriteBuilder);

  builder.add(builder.newRootLogger(Level.INFO)
      .add(builder.newAppenderRef("Redactor")));

  return builder.build();
}
项目:logging-log4j2    文件:ConfigurationAssemblerTest.java   
@Test
public void testBuildConfiguration() throws Exception {
    try {
        System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR,
                "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector");
        final ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory
                .newConfigurationBuilder();
        CustomConfigurationFactory.addTestFixtures("config name", builder);
        final Configuration configuration = builder.build();
        try (LoggerContext ctx = Configurator.initialize(configuration)) {
            validate(configuration);
        }
    } finally {
        System.getProperties().remove(Constants.LOG4J_CONTEXT_SELECTOR);
    }
}
项目:logging-log4j2    文件:TestConfigurator.java   
@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)));
}
项目:logging-log4j2    文件:ConfigurationBuilderTest.java   
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");
}
项目:logging-log4j2    文件:CustomConfigurationFactory.java   
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();
}
项目:logging-log4j2    文件:RollingFileAppenderUpdateDataTest.java   
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;
}
项目:coteafs-logger    文件:ConfigBuilder.java   
private static void addAppenderRef (final AppenderComponentBuilder appenderCom,
        final List <AppenderRefSetting> appenderRef, final ConfigurationBuilder <BuiltConfiguration> build) {
    for (final AppenderRefSetting setting : appenderRef) {
        final AppenderRefComponentBuilder ref = build.newAppenderRef (setting.getRef ());
        addAttributes (ref, setting.getAttributes ());
        appenderCom.addComponent (ref);
    }
}
项目:coteafs-logger    文件:ConfigBuilder.java   
private static void addLayout (final AppenderComponentBuilder appenderCom, final LayoutSetting layout,
        final ConfigurationBuilder <BuiltConfiguration> build) {
    if (layout == null) return;
    final LayoutComponentBuilder layoutCom = build.newLayout (layout.getPlugin ());
    addAttributes (layoutCom, layout.getAttributes ());
    appenderCom.add (layoutCom);
}
项目:coteafs-logger    文件:ConfigBuilder.java   
private void addAppenders (final ConfigurationBuilder <BuiltConfiguration> build) {
    for (final AppenderSetting appender : this.appenders) {
        final AppenderComponentBuilder appenderCom = build.newAppender (appender.getName (), appender.getPlugin ());
        addAttributes (appenderCom, appender.getAttributes ());
        addLayout (appenderCom, appender.getLayout (), build);
        addAppenderRef (appenderCom, appender.getAppenderRef (), build);
        addComponent (appenderCom, appender.getComponent (), build);
        build.add (appenderCom);
    }
}
项目:coteafs-logger    文件:ConfigBuilder.java   
private <K extends ComponentBuilder <K>> void addComponent (final ComponentBuilder <K> component,
        final ComponentSetting setting, final ConfigurationBuilder <BuiltConfiguration> build) {
    if (setting == null) return;
    final ComponentBuilder <?> comp = build.newComponent (setting.getPlugin ());
    for (final ComponentSetting c : setting.getComponents ()) {
        final ComponentBuilder <?> newComp = build.newComponent (c.getPlugin ());
        addAttributes (newComp, c.getAttributes ());
        if (!c  .getComponents ()
                .isEmpty ()) {
            addComponent (newComp, c, build);
        }
        comp.addComponent (newComp);
    }
    component.addComponent (comp);
}
项目:coteafs-logger    文件:ConfigBuilder.java   
private void addRootLogger (final ConfigurationBuilder <BuiltConfiguration> build) {
    final RootLoggerComponentBuilder root = build.newRootLogger (this.loggers   .getLevel ()
                                                                                .getStatus ());
    for (final AppenderRefSetting setting : this.loggers.getAppenderRef ()) {
        final AppenderRefComponentBuilder ref = build.newAppenderRef (setting.getRef ());
        addAttributes (ref, setting.getAttributes ());
        root.add (ref);
    }
    build.add (root);
}
项目:log4j2-logstash-layout    文件:LogstashLayoutTest.java   
@Test
public void test_inline_template() throws Exception {

    // Create the log event.
    SimpleMessage message = new SimpleMessage("Hello, World");
    String timestamp = "2017-09-28T17:13:29.098+02:00";
    long timeMillis = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX").parse(timestamp).getTime();
    LogEvent logEvent = Log4jLogEvent
            .newBuilder()
            .setLoggerName(LogstashLayoutTest.class.getSimpleName())
            .setLevel(Level.INFO)
            .setMessage(message)
            .setTimeMillis(timeMillis)
            .build();

    // Create the template.
    ObjectNode templateRootNode = JSON_NODE_FACTORY.objectNode();
    templateRootNode.put("@timestamp", "${json:timestamp}");
    String staticFieldName = "staticFieldName";
    String staticFieldValue = "staticFieldValue";
    templateRootNode.put(staticFieldName, staticFieldValue);
    String template = templateRootNode.toString();

    // Create the layout.
    BuiltConfiguration configuration = ConfigurationBuilderFactory.newConfigurationBuilder().build();
    String timeZoneId = TimeZone.getTimeZone("Europe/Amsterdam").getID();
    LogstashLayout layout = LogstashLayout
            .newBuilder()
            .setConfiguration(configuration)
            .setTemplate(template)
            .setTimeZoneId(timeZoneId)
            .build();

    // Check the serialized event.
    String serializedLogEvent = layout.toSerializable(logEvent);
    JsonNode rootNode = OBJECT_MAPPER.readTree(serializedLogEvent);
    assertThat(point(rootNode, "@timestamp").asText()).isEqualTo(timestamp);
    assertThat(point(rootNode, staticFieldName).asText()).isEqualTo(staticFieldValue);

}
项目:jeesuite-libs    文件:LogContextInitializer.java   
/**
     * 初始化日志配置
     */
    public static void initLog4j2WithoutConfigFile() {
        System.out.println("no local log4j2.xml file found,init logContext");

        ConfigurationBuilder< BuiltConfiguration > builder =
                ConfigurationBuilderFactory.newConfigurationBuilder();

        builder.setStatusLevel( Level.ERROR);
        builder.setConfigurationName("RollingBuilder");
        // create the console appender
        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 );

//      LayoutComponentBuilder layoutBuilder = builder.newLayout("PatternLayout")
//              .addAttribute("pattern", "%d [%t] %-5level: %msg%n");
//      ComponentBuilder triggeringPolicy = builder.newComponent("Policies")
//              .addComponent(builder.newComponent("CronTriggeringPolicy").addAttribute("schedule", "0 0 0 * * ?"))
//              .addComponent(builder.newComponent("SizeBasedTriggeringPolicy").addAttribute("size", "100M"));
//      appenderBuilder = builder.newAppender("rolling", "RollingFile")
//              .addAttribute("fileName", "target/rolling.log")
//              .addAttribute("filePattern", "target/archive/rolling-%d{MM-dd-yy}.log.gz")
//              .add(layoutBuilder)
//              .addComponent(triggeringPolicy);
//      builder.add(appenderBuilder);

        builder.add(builder.newRootLogger(Level.INFO).add(builder.newAppenderRef("Stdout")));
        builder.add(builder.newLogger("com.jeesuite", Level.TRACE).add(builder.newAppenderRef("Stdout")).addAttribute("additivity", false));

        Configurator.initialize(builder.build());
    }
项目:slack-appender    文件:SlackAppenderIT.java   
@Before
   public void setup() {
ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
String webhookUrl = System.getProperty(SLACK_WEBHOOK, System.getenv(SLACK_WEBHOOK));
assertNotNull(SLACK_WEBHOOK + " MUST NOT be null", webhookUrl);
AppenderComponentBuilder appenderComponentBuilder = builder.newAppender("SlackerFoo", "Slack");
appenderComponentBuilder.addAttribute("webhookUrl", webhookUrl);
appenderComponentBuilder.addAttribute("httpClientImpl", OkHttp3Client.class.getName());
appenderComponentBuilder.add(builder.newLayout("PatternLayout").
    addAttribute("pattern", "%-5p - [%t] %-26.26c{1}"));
builder.add(appenderComponentBuilder);
builder.add(builder.newRootLogger(Level.INFO).add(builder.newAppenderRef("SlackerFoo")));
Configurator.initialize(builder.build());
   }
项目:ldbc_graphalytics    文件:LogUtil.java   
public static void intializeLoggers() {
    ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
    builder.setConfigurationName("logger");
    RootLoggerComponentBuilder rootLogger = builder.newRootLogger(Level.DEBUG);
    builder.add(rootLogger);

    Configurator.initialize(builder.build());
}
项目:logging-log4j2    文件:Log4j1ConfigurationParser.java   
/**
 * Parses a Log4j 1.2 properties configuration file in ISO 8859-1 encoding into a ConfigurationBuilder.
 *
 * @param input
 *            InputStream to read from is assumed to be ISO 8859-1, and will not be closed.
 * @return the populated ConfigurationBuilder, never {@literal null}
 * @throws IOException
 *             if unable to read the input
 * @throws ConfigurationException
 *             if the input does not contain a valid configuration
 */
public ConfigurationBuilder<BuiltConfiguration> buildConfigurationBuilder(final InputStream input)
        throws IOException {
    try {
        properties.load(input);
        strSubstitutorProperties = new StrSubstitutor(properties);
        strSubstitutorSystem = new StrSubstitutor(System.getProperties());
        final String rootCategoryValue = getLog4jValue(ROOTCATEGORY);
        final String rootLoggerValue = getLog4jValue(ROOTLOGGER);
        if (rootCategoryValue == null && rootLoggerValue == null) {
            // This is not a Log4j 1 properties configuration file.
            warn("Missing " + ROOTCATEGORY + " or " + ROOTLOGGER + " in " + input);
            // throw new ConfigurationException(
            // "Missing " + ROOTCATEGORY + " or " + ROOTLOGGER + " in " + input);
        }
        builder.setConfigurationName("Log4j1");
        // DEBUG
        final String debugValue = getLog4jValue("debug");
        if (Boolean.valueOf(debugValue)) {
            builder.setStatusLevel(Level.DEBUG);
        }
        // Root
        buildRootLogger(getLog4jValue(ROOTCATEGORY));
        buildRootLogger(getLog4jValue(ROOTLOGGER));
        // Appenders
        final Map<String, String> appenderNameToClassName = buildClassToPropertyPrefixMap();
        for (final Map.Entry<String, String> entry : appenderNameToClassName.entrySet()) {
            final String appenderName = entry.getKey();
            final String appenderClass = entry.getValue();
            buildAppender(appenderName, appenderClass);
        }
        // Loggers
        buildLoggers("log4j.category.");
        buildLoggers("log4j.logger.");
        buildProperties();
        return builder;
    } catch (final IllegalArgumentException e) {
        throw new ConfigurationException(e);
    }
}
项目:logging-log4j2    文件:Log4j1ConfigurationFactory.java   
@Override
public Configuration getConfiguration(final LoggerContext loggerContext, final ConfigurationSource source) {
    final ConfigurationBuilder<BuiltConfiguration> builder;
    try (final InputStream configStream = source.getInputStream()) {
        builder = new Log4j1ConfigurationParser().buildConfigurationBuilder(configStream);
    } catch (final IOException e) {
        throw new ConfigurationException("Unable to load " + source, e);
    }
    return builder.build();
}
项目:logging-log4j2    文件:ConfigurationBuilderTest.java   
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");
}
项目:logging-log4j2    文件:ConfigurationBuilderTest.java   
@Test
public void testXmlConstructing() throws Exception {
    //assumeTrue(System.lineSeparator().length() == 1); // Only run test on platforms with single character line endings (such as Linux), not on Windows
    final ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
    addTestFixtures("config name", builder);
    final String xmlConfiguration = builder.toXmlConfiguration();
    assertEquals(expectedXml, xmlConfiguration);
}
项目:logging-log4j2    文件:CustomConfigurationFactory.java   
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();
}
项目:logging-log4j2    文件:TestConfigurator.java   
@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"));
}
项目:logging-log4j2    文件:ConfigurationBuilderTest.java   
@Test
public void testXmlConstructing() throws Exception {
    assumeTrue(System.lineSeparator().length() == 1); // Only run test on platforms with single character line endings (such as Linux), not on Windows
    final ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
    addTestFixtures("config name", builder);
    final String xmlConfiguration = builder.toXmlConfiguration();
    assertEquals(expectedXml, xmlConfiguration);
}
项目:logging-log4j2    文件:ConfigurationAssemblerTest.java   
@Test
public void testBuildConfiguration() throws Exception {
    try {
        System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR,
                "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector");
        final ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
        CustomConfigurationFactory.addTestFixtures("config name", builder);
        final Configuration configuration = builder.build();
        try (LoggerContext ctx = Configurator.initialize(configuration)) {
            validate(configuration);
        }
    } finally {
        System.getProperties().remove(Constants.LOG4J_CONTEXT_SELECTOR);
    }
}
项目:elasticsearch_my    文件:LogConfigurator.java   
private static void configureStatusLogger() {
    final ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
    builder.setStatusLevel(Level.ERROR);
    Configurator.initialize(builder.build());
}
项目:JukeBot    文件:Log4JConfig.java   
@Override
public Configuration getConfiguration(final LoggerContext loggerContext, final String name, final URI configLocation) {
    ConfigurationBuilder<BuiltConfiguration> builder = newConfigurationBuilder();
    return createConfiguration(name, builder);
}
项目:coteafs-logger    文件:ConfigBuilder.java   
private void addProperties (final ConfigurationBuilder <BuiltConfiguration> build) {
    for (final PropertySetting property : this.properties) {
        build.addProperty (property.getName (), property.getValue ());
    }
}
项目:log4j2-logstash-layout    文件:LogstashLayoutTest.java   
@Test
public void test_empty_root_cause() throws Exception {

    // Create the log event.
    SimpleMessage message = new SimpleMessage("Hello, World!");
    RuntimeException exception = new RuntimeException("failure for test purposes");
    LogEvent logEvent = Log4jLogEvent
            .newBuilder()
            .setLoggerName(LogstashLayoutTest.class.getSimpleName())
            .setLevel(Level.ERROR)
            .setMessage(message)
            .setThrown(exception)
            .build();

    // Create the template.
    ObjectNode templateRootNode = JSON_NODE_FACTORY.objectNode();
    templateRootNode.put("ex_class", "${json:exceptionClassName}");
    templateRootNode.put("ex_message", "${json:exceptionMessage}");
    templateRootNode.put("ex_stacktrace", "${json:exceptionStackTrace}");
    templateRootNode.put("root_ex_class", "${json:exceptionRootCauseClassName}");
    templateRootNode.put("root_ex_message", "${json:exceptionRootCauseMessage}");
    templateRootNode.put("root_ex_stacktrace", "${json:exceptionRootCauseStackTrace}");
    String template = templateRootNode.toString();

    // Create the layout.
    BuiltConfiguration configuration = ConfigurationBuilderFactory.newConfigurationBuilder().build();
    LogstashLayout layout = LogstashLayout
            .newBuilder()
            .setConfiguration(configuration)
            .setStackTraceEnabled(true)
            .setTemplate(template)
            .build();

    // Check the serialized event.
    String serializedLogEvent = layout.toSerializable(logEvent);
    JsonNode rootNode = OBJECT_MAPPER.readTree(serializedLogEvent);
    assertThat(point(rootNode, "ex_class").asText()).isEqualTo(exception.getClass().getCanonicalName());
    assertThat(point(rootNode, "ex_message").asText()).isEqualTo(exception.getMessage());
    assertThat(point(rootNode, "ex_stacktrace").asText()).startsWith(exception.getClass().getCanonicalName() + ": " + exception.getMessage());
    assertThat(point(rootNode, "root_ex_class").asText()).isEqualTo(point(rootNode, "ex_class").asText());
    assertThat(point(rootNode, "root_ex_message").asText()).isEqualTo(point(rootNode, "ex_message").asText());
    assertThat(point(rootNode, "root_ex_stacktrace").asText()).isEqualTo(point(rootNode, "ex_stacktrace").asText());

}
项目:log4j2-logstash-layout    文件:LogstashLayoutTest.java   
@Test
public void test_root_cause() throws Exception {

    // Create the log event.
    SimpleMessage message = new SimpleMessage("Hello, World!");
    RuntimeException exceptionCause = new RuntimeException("failure cause for test purposes");
    RuntimeException exception = new RuntimeException("failure for test purposes", exceptionCause);
    LogEvent logEvent = Log4jLogEvent
            .newBuilder()
            .setLoggerName(LogstashLayoutTest.class.getSimpleName())
            .setLevel(Level.ERROR)
            .setMessage(message)
            .setThrown(exception)
            .build();

    // Create the template.
    ObjectNode templateRootNode = JSON_NODE_FACTORY.objectNode();
    templateRootNode.put("ex_class", "${json:exceptionClassName}");
    templateRootNode.put("ex_message", "${json:exceptionMessage}");
    templateRootNode.put("ex_stacktrace", "${json:exceptionStackTrace}");
    templateRootNode.put("root_ex_class", "${json:exceptionRootCauseClassName}");
    templateRootNode.put("root_ex_message", "${json:exceptionRootCauseMessage}");
    templateRootNode.put("root_ex_stacktrace", "${json:exceptionRootCauseStackTrace}");
    String template = templateRootNode.toString();

    // Create the layout.
    BuiltConfiguration configuration = ConfigurationBuilderFactory.newConfigurationBuilder().build();
    LogstashLayout layout = LogstashLayout
            .newBuilder()
            .setConfiguration(configuration)
            .setStackTraceEnabled(true)
            .setTemplate(template)
            .build();

    // Check the serialized event.
    String serializedLogEvent = layout.toSerializable(logEvent);
    JsonNode rootNode = OBJECT_MAPPER.readTree(serializedLogEvent);
    assertThat(point(rootNode, "ex_class").asText()).isEqualTo(exception.getClass().getCanonicalName());
    assertThat(point(rootNode, "ex_message").asText()).isEqualTo(exception.getMessage());
    assertThat(point(rootNode, "ex_stacktrace").asText()).startsWith(exception.getClass().getCanonicalName() + ": " + exception.getMessage());
    assertThat(point(rootNode, "root_ex_class").asText()).isEqualTo(exceptionCause.getClass().getCanonicalName());
    assertThat(point(rootNode, "root_ex_message").asText()).isEqualTo(exceptionCause.getMessage());
    assertThat(point(rootNode, "root_ex_stacktrace").asText()).startsWith(exceptionCause.getClass().getCanonicalName() + ": " + exceptionCause.getMessage());

}
项目:log4j2-logstash-layout    文件:LogstashLayoutTest.java   
@Test
public void test_mdc_key_access() throws IOException {

    // Create the log event.
    SimpleMessage message = new SimpleMessage("Hello, World!");
    StringMap contextData = new SortedArrayStringMap();
    String mdcDirectlyAccessedKey = "mdcKey1";
    String mdcDirectlyAccessedValue = "mdcValue1";
    contextData.putValue(mdcDirectlyAccessedKey, mdcDirectlyAccessedValue);
    String mdcPatternMatchedKey = "mdcKey2";
    String mdcPatternMatchedValue = "mdcValue2";
    contextData.putValue(mdcPatternMatchedKey, mdcPatternMatchedValue);
    String mdcPatternMismatchedKey = "mdcKey3";
    String mdcPatternMismatchedValue = "mdcValue3";
    contextData.putValue(mdcPatternMismatchedKey, mdcPatternMismatchedValue);
    LogEvent logEvent = Log4jLogEvent
            .newBuilder()
            .setLoggerName(LogstashLayoutTest.class.getSimpleName())
            .setLevel(Level.INFO)
            .setMessage(message)
            .setContextData(contextData)
            .build();

    // Create the template.
    ObjectNode templateRootNode = JSON_NODE_FACTORY.objectNode();
    String mdcFieldName = "mdc";
    templateRootNode.put(mdcFieldName, "${json:mdc}");
    templateRootNode.put(mdcDirectlyAccessedKey, String.format("${json:mdc:%s}", mdcDirectlyAccessedKey));
    String template = templateRootNode.toString();

    // Create the layout.
    BuiltConfiguration configuration = ConfigurationBuilderFactory.newConfigurationBuilder().build();
    LogstashLayout layout = LogstashLayout
            .newBuilder()
            .setConfiguration(configuration)
            .setStackTraceEnabled(true)
            .setTemplate(template)
            .setMdcKeyPattern(mdcPatternMatchedKey)
            .build();

    // Check the serialized event.
    String serializedLogEvent = layout.toSerializable(logEvent);
    JsonNode rootNode = OBJECT_MAPPER.readTree(serializedLogEvent);
    assertThat(point(rootNode, mdcDirectlyAccessedKey).asText()).isEqualTo(mdcDirectlyAccessedValue);
    assertThat(point(rootNode, mdcFieldName, mdcPatternMatchedKey).asText()).isEqualTo(mdcPatternMatchedValue);
    assertThat(point(rootNode, mdcFieldName, mdcPatternMismatchedKey).asText()).isNullOrEmpty();

}
项目:logging-log4j2    文件:Log4j1ConfigurationConverter.java   
protected void convert(final InputStream input, final OutputStream output) throws IOException {
    final ConfigurationBuilder<BuiltConfiguration> builder = new Log4j1ConfigurationParser()
            .buildConfigurationBuilder(input);
    builder.writeXmlConfiguration(output);
}
项目:logging-log4j2    文件:CustomConfigurationFactory.java   
@Override
public Configuration getConfiguration(final LoggerContext loggerContext, final String name, final URI configLocation) {
    final ConfigurationBuilder<BuiltConfiguration> builder = newConfigurationBuilder();
    return addTestFixtures(name, builder);
}
项目:logging-log4j2    文件:ConfigurationBuilderFactory.java   
public static <T extends BuiltConfiguration> ConfigurationBuilder<T> newConfigurationBuilder(final Class<T> clazz) {
    return new DefaultConfigurationBuilder<>(clazz);
}
项目:logging-log4j2    文件:TestConfigurator.java   
@Test
public void testRolling() throws Exception {
    final ConfigurationBuilder< BuiltConfiguration > builder =
            ConfigurationBuilderFactory.newConfigurationBuilder();

    builder.setStatusLevel( Level.ERROR);
    builder.setConfigurationName("RollingBuilder");
    // create the console appender
    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 );

    final LayoutComponentBuilder layoutBuilder = builder.newLayout("PatternLayout")
            .addAttribute("pattern", "%d [%t] %-5level: %msg%n");
    final ComponentBuilder triggeringPolicy = builder.newComponent("Policies")
            .addComponent(builder.newComponent("CronTriggeringPolicy").addAttribute("schedule", "0 0 0 * * ?"))
            .addComponent(builder.newComponent("SizeBasedTriggeringPolicy").addAttribute("size", "100M"));
    appenderBuilder = builder.newAppender("rolling", "RollingFile")
            .addAttribute("fileName", "target/rolling.log")
            .addAttribute("filePattern", "target/archive/rolling-%d{MM-dd-yy}.log.gz")
            .add(layoutBuilder)
            .addComponent(triggeringPolicy);
    builder.add(appenderBuilder);

    // create the new logger
    builder.add( builder.newLogger( "TestLogger", Level.DEBUG )
            .add( builder.newAppenderRef( "rolling" ) )
            .addAttribute( "additivity", false ) );

    builder.add( builder.newRootLogger( Level.DEBUG )
            .add( builder.newAppenderRef( "rolling" ) ) );
    final Configuration config = builder.build();
    config.initialize();
    assertNotNull("No rolling file appender", config.getAppender("rolling"));
    assertEquals("Unexpected Configuration", "RollingBuilder", config.getName());
    // Initialize the new configuration
    final LoggerContext ctx = Configurator.initialize( config );
    Configurator.shutdown(ctx);

}
项目:logging-log4j2    文件:CustomConfigurationFactory.java   
@Override
public Configuration getConfiguration(final LoggerContext loggerContext, final String name, final URI configLocation) {
    final ConfigurationBuilder<BuiltConfiguration> builder = newConfigurationBuilder();
    return addTestFixtures(name, builder);
}
项目:logging-log4j2    文件:RollingFileAppenderUpdateDataTest.java   
private ConfigurationBuilder<BuiltConfiguration> buildConfigA() {
    return buildConfigurationBuilder("target/rolling-update-date/foo.log.%i");
}
项目:logging-log4j2    文件:RollingFileAppenderUpdateDataTest.java   
private ConfigurationBuilder<BuiltConfiguration> buildConfigB() {
    return buildConfigurationBuilder("target/rolling-update-date/foo.log.%d{yyyy-MM-dd-HH:mm:ss}.%i");
}
项目:logging-log4j2    文件:ConfigurationBuilderFactory.java   
/**
 * Returns a new default ConfigurationBuilder to construct Log4j configurations.
 * @return A new ConfigurationBuilder.
 */
public static ConfigurationBuilder<BuiltConfiguration> newConfigurationBuilder() {
    return new DefaultConfigurationBuilder<>();
}