mohlerm
mohlerm

Reputation: 31

Create a Log4j 2.x FileAppender programmatically

I want to migrate from Log4j 1.2 to 2.4. Since I'm running multiple instances of my program on the same machines I want to include an ID (called clientId in the following code) in the logfile. Therefore I used Log4j 1.2's way to setup a FileAppender programmatically:

int clientId = ?// gets set before

FileAppender fa = new FileAppender();
fa.setName("FileLogger");
fa.setFile("logs/client_" + clientId + ".log");
fa.setLayout(new PatternLayout("%d %-5p %c{1} %m%n"));
fa.setThreshold(Level.INFO);
fa.setAppend(true);
fa.activateOptions();
Logger.getRootLogger().addAppender(fa);

I fail to achieve something similar with Log4j 2.0, since they removed the ability to directly modify these properties. Instead I tried to use a CustomConfigurationFactory like described in https://logging.apache.org/log4j/2.x/manual/customconfig.html#Example But I fail to understand how I make use of it? The documentation states

This will cause the Configuration to automatically be hooked into Log4j when the LoggerContext is created.

I tried something like:

LoggerContext context = (LoggerContext) LogManager.getContext(false);
context.getConfiguration(CustomConfigurationFactory.getInstance());

but this doesn't work.

Upvotes: 2

Views: 3193

Answers (1)

mohlerm
mohlerm

Reputation: 31

I found it out myself. I modified the Factory to use a FileAppender:

    builder.setConfigurationName(name);
    builder.setStatusLevel(Level.INFO);
    builder.add(builder.newFilter("ThresholdFilter", Filter.Result.ACCEPT, Filter.Result.NEUTRAL).
            addAttribute("level", Level.INFO));
    AppenderComponentBuilder appenderBuilder = builder.newAppender("file", "FILE").
            addAttribute("fileName", "log/client_"+Config.CLIENTID+".log");
    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.INFO).
            add(builder.newAppenderRef("file")).
            addAttribute("additivity", false));
    builder.add(builder.newRootLogger(Level.INFO).add(builder.newAppenderRef("file")));
    return builder.build();

And then use:

ConfigurationFactory.setConfigurationFactory(new CustomConfigurationFactory());
Logger log = LogManager.getLogger(Main.class.getName());

to get the new logger

Upvotes: 1

Related Questions