[SOLVED] Add File Appender using log4j2 programmatically at runtime


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());
    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())

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


From what you describe, it seems you successfully instantiated a FileAppender that is ready to log messages it receives, but somehow no message is passed to this Appender.

Somehow your code example calls a nonexisting method LoggerContext.getContext() – I believe this should be LoggerContextFactory.getContext() or LogManager.getContext(). And in total, you may want to check the example from the documentation.

This Question was asked in StackOverflow by JenUndSho and Answered by Hiran Chaudhuri It 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?