How to properly create a RollingFileAppender with AppenderComponentBuilder in log4j 2

后端 未结 1 897
借酒劲吻你
借酒劲吻你 2021-01-16 07:27

I would like the user to choose the type of the appender(s) that will be created via a configurable option.

For example, let\'s say that I have a command line argum

相关标签:
1条回答
  • 2021-01-16 08:00
    1. Yes, this is the intended way to programmatically create a new configuration.

    2. Here is an example of how to create a rolling file appender. Since Appenders can be configured with arbitrary components you use the generic ComponentBuilder to specify those plugins.

      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);
      
      // 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" ) ) );
      Configurator.initialize(builder.build());
      
    0 讨论(0)
提交回复
热议问题