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()); }
@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); } }
@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))); }
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; }
@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); }
@Test public void test_property_injection() throws Exception { // Create the log event. SimpleMessage message = new SimpleMessage("Hello, World"); LogEvent logEvent = Log4jLogEvent .newBuilder() .setLoggerName(LogstashLayoutTest.class.getSimpleName()) .setLevel(Level.INFO) .setMessage(message) .build(); // Create the template with property. ObjectNode templateRootNode = JSON_NODE_FACTORY.objectNode(); String propertyName = "propertyName"; templateRootNode.put(propertyName, "${" + propertyName + "}"); String template = templateRootNode.toString(); // Create the layout with property. String propertyValue = "propertyValue"; Configuration config = ConfigurationBuilderFactory .newConfigurationBuilder() .addProperty(propertyName, propertyValue) .build(); LogstashLayout layout = LogstashLayout .newBuilder() .setConfiguration(config) .setTemplate(template) .build(); // Check the serialized event. String serializedLogEvent = layout.toSerializable(logEvent); JsonNode rootNode = OBJECT_MAPPER.readTree(serializedLogEvent); assertThat(point(rootNode, propertyName).asText()).isEqualTo(propertyValue); }
/** * 初始化日志配置 */ 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()); }
@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()); }
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()); }
@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); }
@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")); }
@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); }
@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); } }
private static void configureStatusLogger() { final ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder(); builder.setStatusLevel(Level.ERROR); Configurator.initialize(builder.build()); }
@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()); }
@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()); }
@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(); }
@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); }