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(); }
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(); }
private AppenderComponentBuilder createAppender(final String key, final Properties properties) { final String name = (String) properties.remove(CONFIG_NAME); if (Strings.isEmpty(name)) { throw new ConfigurationException("No name attribute provided for Appender " + key); } final String type = (String) properties.remove(CONFIG_TYPE); if (Strings.isEmpty(type)) { throw new ConfigurationException("No type attribute provided for Appender " + key); } final AppenderComponentBuilder appenderBuilder = builder.newAppender(name, type); addFiltersToComponent(appenderBuilder, properties); final Properties layoutProps = PropertiesUtil.extractSubset(properties, "layout"); if (layoutProps.size() > 0) { appenderBuilder.add(createLayout(name, layoutProps)); } return processRemainingProperties(appenderBuilder, properties); }
@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 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"); }
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(); }
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); } }
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); }
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); } }
/** * 初始化日志配置 */ 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()); }
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); }
private void buildFileAppender(final String appenderName, final AppenderComponentBuilder appenderBuilder) { buildMandatoryAttribute(appenderName, appenderBuilder, "File", "fileName"); buildAttribute(appenderName, appenderBuilder, "Append", "append"); buildAttribute(appenderName, appenderBuilder, "BufferedIO", "bufferedIo"); buildAttribute(appenderName, appenderBuilder, "BufferSize", "bufferSize"); buildAttribute(appenderName, appenderBuilder, "ImmediateFlush", "immediateFlush"); buildAppenderLayout(appenderName, appenderBuilder); }
private void buildDailyRollingFileAppender(final String appenderName) { final AppenderComponentBuilder appenderBuilder = builder.newAppender(appenderName, RollingFileAppender.PLUGIN_NAME); buildFileAppender(appenderName, appenderBuilder); final String fileName = getLog4jAppenderValue(appenderName, "File"); final String datePattern = getLog4jAppenderValue(appenderName, "DatePattern", fileName + "'.'yyyy-MM-dd"); appenderBuilder.addAttribute("filePattern", fileName + "%d{" + datePattern + "}"); final ComponentBuilder<?> triggeringPolicy = builder.newComponent("Policies") .addComponent(builder.newComponent("TimeBasedTriggeringPolicy").addAttribute("modulate", true)); appenderBuilder.addComponent(triggeringPolicy); appenderBuilder .addComponent(builder.newComponent("DefaultRolloverStrategy").addAttribute("max", Integer.MAX_VALUE)); builder.add(appenderBuilder); }
private void buildRollingFileAppender(final String appenderName) { final AppenderComponentBuilder appenderBuilder = builder.newAppender(appenderName, RollingFileAppender.PLUGIN_NAME); buildFileAppender(appenderName, appenderBuilder); final String fileName = getLog4jAppenderValue(appenderName, "File"); appenderBuilder.addAttribute("filePattern", fileName + ".%i"); final String maxFileSizeString = getLog4jAppenderValue(appenderName, "MaxFileSize", "10485760"); final String maxBackupIndexString = getLog4jAppenderValue(appenderName, "MaxBackupIndex", "1"); final ComponentBuilder<?> triggeringPolicy = builder.newComponent("Policies").addComponent( builder.newComponent("SizeBasedTriggeringPolicy").addAttribute("size", maxFileSizeString)); appenderBuilder.addComponent(triggeringPolicy); appenderBuilder.addComponent( builder.newComponent("DefaultRolloverStrategy").addAttribute("max", maxBackupIndexString)); builder.add(appenderBuilder); }
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"); }
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(); }
@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")); }
private void buildFileAppender(final String appenderName) { final AppenderComponentBuilder appenderBuilder = builder.newAppender(appenderName, FileAppender.PLUGIN_NAME); buildFileAppender(appenderName, appenderBuilder); builder.add(appenderBuilder); }
private void buildNullAppender(final String appenderName) { final AppenderComponentBuilder appenderBuilder = builder.newAppender(appenderName, NullAppender.PLUGIN_NAME); builder.add(appenderBuilder); }
@Override public AppenderComponentBuilder add(final LayoutComponentBuilder builder) { return addComponent(builder); }
@Override public AppenderComponentBuilder add(final FilterComponentBuilder builder) { return addComponent(builder); }
@Override public ConfigurationBuilder<T> add(final AppenderComponentBuilder builder) { return add(appenders, builder); }
@Override public AppenderComponentBuilder newAppender(final String name, final String type) { return new DefaultAppenderComponentBuilder(this, name, type); }
@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); }