Add File Appender using log4j2 programmatically at runtime

Issue

This Content is from Stack Overflow. Question asked by JenUndSho

Now we migrating from log4j to log4j2. Configuration file is not changed (is includes only Console appender). We want to add File Appender at runtime, so log files are created but logs are not appeared.
When we used log4j2, we made this way:

    PatternLayout layout = new PatternLayout("%d - " + DEFAULT_CONVERSION_PATTERN);
    FileAppender fileAppender = new FileAppender(layout, file.getPath());
    fileAppender.setName("fileAppender");
    logger.removeAllAppenders();
    logger.addAppender(fileAppender);
    logger.addAppender(new ConsoleAppender(layout));

And it worked fine. But when we moved to log4j2, we used this code:

    PatternLayout layout = PatternLayout.newBuilder().withPattern("%d - " + DEFAULT_CONVERSION_PATTERN).build();
    FileAppender fileAppender = FileAppender.newBuilder().setLayout(layout).withFileName(file.getPath())
                    .setName("fileAppender").build();
    LoggerContext.getContext().getLogger(name).getAppenders().clear();
    LoggerContext.getContext().getLogger(name).addAppender(fileAppender);
    LoggerContext.getContext().getLogger(name).addAppender(ConsoleAppender.newBuilder().setLayout(layout).build());

File is created but logs appears only in Console… Can someone help please valid creating FileAppender?



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?