org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilderFactory Java Examples

The following examples show how to use org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilderFactory. 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: 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 #2
Source File: LoggerFactory.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public static void initGuiLogging(String logFile) {
  ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
  builder.add(builder.newRootLogger(Level.INFO));
  LoggerContext context = Configurator.initialize(builder.build());

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

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

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

  context.getRootLogger().addAppender(fileAppender);
  context.getRootLogger().addAppender(textAreaAppender);
  context.updateLoggers();
}
 
Example #3
Source File: ConfigurationAssemblerTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuildConfiguration() {
    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);
    }
}
 
Example #4
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 #5
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 #6
Source File: ConfigurationAssemblerTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example #7
Source File: JsonTemplateLayoutTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void test_property_injection() {

    // Create the log event.
    final SimpleMessage message = new SimpleMessage("Hello, World");
    final LogEvent logEvent = Log4jLogEvent
            .newBuilder()
            .setLoggerName(LOGGER_NAME)
            .setLevel(Level.INFO)
            .setMessage(message)
            .build();

    // Create the event template with property.
    final String propertyName = "propertyName";
    final String eventTemplate = writeJson(Map(
            propertyName, "${" + propertyName + "}"));

    // Create the layout with property.
    final String propertyValue = "propertyValue";
    final Configuration config = ConfigurationBuilderFactory
            .newConfigurationBuilder()
            .addProperty(propertyName, propertyValue)
            .build();
    final JsonTemplateLayout layout = JsonTemplateLayout
            .newBuilder()
            .setConfiguration(config)
            .setEventTemplate(eventTemplate)
            .build();

    // Check the serialized event.
    usingSerializedLogEventAccessor(layout, logEvent, accessor ->
            assertThat(accessor.getString(propertyName)).isEqualTo(propertyValue));

}
 
Example #8
Source File: ConfigurationAssemblerTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example #9
Source File: ConfigurationBuilderTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #10
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 #11
Source File: ConfigurationBuilderTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #12
Source File: Log4j2Configuration.java    From product-microgateway with Apache License 2.0 5 votes vote down vote up
public static void initialize(String logLevel) {
    if (System.getProperty(LOG4J_CONFIGURATION_FILE) == null) {
        ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder()
                .setStatusLevel(Level.ERROR)
                .setConfigurationName(LOG4J_CONFIGURATION_NAME);
        AppenderComponentBuilder appenderBuilder = builder.newAppender(APPENDER_NAME, APPENDER_PLUGIN_TYPE)
                .add(builder.newLayout(APPENDER_LAYOUT_PLUGIN_TYPE)
                        .addAttribute(APPENDER_PATTERN_KEY, APPENDER_PATTERN_VALUE));
        builder.add(appenderBuilder);
        switch (logLevel) {
            case TRACE_LOG_LEVEL:
                builder.add(builder.newRootLogger(Level.TRACE).add(builder.newAppenderRef(APPENDER_NAME)));
                break;
            case DEBUG_LOG_LEVEL:
                builder.add(builder.newRootLogger(Level.DEBUG).add(builder.newAppenderRef(APPENDER_NAME)));
                break;
            case INFO_LOG_LEVEL:
                builder.add(builder.newRootLogger(Level.INFO).add(builder.newAppenderRef(APPENDER_NAME)));
                break;
            case WARN_LOG_LEVEL:
                builder.add(builder.newRootLogger(Level.WARN).add(builder.newAppenderRef(APPENDER_NAME)));
                break;
            default:
                builder.add(builder.newRootLogger(Level.ERROR).add(builder.newAppenderRef(APPENDER_NAME)));
                break;
        }
        Configurator.initialize(builder.build());
    }
}
 
Example #13
Source File: LogUtil.java    From ldbc_graphalytics with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example #14
Source File: ConfigurationBuilderTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Test
public void testXmlConstructing() {
    //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);
}
 
Example #15
Source File: LogUtil.java    From fix-orchestra with Apache License 2.0 5 votes vote down vote up
public static Logger initializeFileLogger(String fileName, Level level, Class<?> clazz) {
  final ConfigurationBuilder<BuiltConfiguration> builder =
      ConfigurationBuilderFactory.newConfigurationBuilder();
  final AppenderComponentBuilder appenderBuilder =
      builder.newAppender("file", "File").addAttribute("fileName", fileName);
  builder.add(appenderBuilder);
  builder.add(
      builder.newLogger(clazz.getCanonicalName(), level).add(builder.newAppenderRef("file")));
  builder.add(builder.newRootLogger(level).add(builder.newAppenderRef("file")));
  final LoggerContext ctx = Configurator.initialize(builder.build());
  return LogManager.getLogger(clazz);
}
 
Example #16
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 #17
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 #18
Source File: LogConfigurator.java    From crate with Apache License 2.0 4 votes vote down vote up
private static void configureStatusLogger() {
    final ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
    builder.setStatusLevel(Level.ERROR);
    Configurator.initialize(builder.build());
}
 
Example #19
Source File: TestConfigurator.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@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);

}
 
Example #20
Source File: ReconfigureAppenderTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
private void createAndAddAppender()
{
	ConfigurationBuilder<BuiltConfiguration> config_builder =
		ConfigurationBuilderFactory.newConfigurationBuilder();

	// All loggers must have a root logger. The default root logger logs ERRORs to the console.
	// Override this with a root logger that does not log anywhere as we leave it up the the
	// appenders on the logger.
	config_builder.add(config_builder.newRootLogger(Level.INFO));

	// Initialise the logger context.
	LoggerContext logger_context =
		Configurator.initialize(config_builder.build());

	// Retrieve the logger.
	Logger logger = (Logger) LogManager.getLogger(this.getClass());

	Builder pattern_builder = PatternLayout.newBuilder().setPattern(
		"[%d{dd-MM-yy HH:mm:ss}] %p %m %throwable %n");

	PatternLayout pattern_layout = (PatternLayout) pattern_builder.build();

	appender = RollingFileAppender
		.newBuilder()
		.setLayout(pattern_layout)
		.setName("rollingfileappender")
		.setFilePattern("target/filepattern.%i.log")
		.setPolicy(SizeBasedTriggeringPolicy.createPolicy("5 MB"))
		.setAppend(true)
		.setStrategy(
			DirectWriteRolloverStrategy
				.newBuilder()
				.setConfig(logger_context.getConfiguration())
				.setMaxFiles("5")
				.build())
		.setConfiguration(logger_context.getConfiguration())
		.build();

	appender.start();

	logger.addAppender(appender);
}