0
votes

Im using Log4j2 2.6.2.At the start of the application, I'm calling the following code

ConfigurationBuilder< BuiltConfiguration > builder = ConfigurationBuilderFactory.newConfigurationBuilder();
builder.setStatusLevel( Level.ERROR );
builder.setConfigurationName("OverrideDefaultConsoleLayout");
AppenderComponentBuilder appenderBuilder = builder.newAppender("Stdout", "CONSOLE").addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT);
appenderBuilder.add(builder.newLayout("PatternLayout").addAttribute("pattern", "%% %msg%n"));       
builder.add(appenderBuilder);
builder.add(builder.newLogger("Log4j2Test", Level.DEBUG).add(builder.newAppenderRef("Stdout")).addAttribute("additivity", false));
builder.add(builder.newRootLogger(Level.DEBUG).add(builder.newAppenderRef("Stdout")));
Configurator.initialize(builder.build());
LogManager.getLogger("Log4j2Test").error("Output % followed by this message");

I referred to the following documentation: http://logging.apache.org/log4j/2.x/manual/customconfig.html

My goal is to programmatically configure Log4j2. As a trial, I'm trying to override the default layout for the console Appender.

No configuration file (.properties, .xml) is available to the application. As a result, on startup, the following message is displayed.

ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console. 

The output is displayed as

15:43:50.865 [main] ERROR Log4j2Test - Output % followed by this message

i.e. the default layout is in use. My programmatic override of the default is not working. Can anyone help in rectifying the code?

1

1 Answers

2
votes

Just calling the code you showed may not work. It needs to be coded as a class extending ConfigurationFactory, and annotated with @Plugin so that Log4j can discover it and use it instead of looking for a configuration file.

The example code on the Log4j manual page you link to shows how to do this.