0
Follow
0
View

How to set log4j 2.x output path after reading in log4j.xml

cxiao007 注册会员
2023-01-25 06:57

Though your best go-to resource for this would be Log4j's official documentation, I will list out two more references that can help you out.

Baeldung is one of my favourite Java blogs. You can go through this article.

You can also refer to this Stackoverflow answer.

If you are in a hurry, have a look at the below code snippet.

        final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
        final Configuration config = ctx.getConfiguration();
        final Layout layout = PatternLayout.createDefaultLayout(config);
        Appender appender = FileAppender.createAppender("path/to/logFile.log", "false", "false", "File", "true",
            "false", "false", "4000", layout, null, "false", null, config);
        appender.start();
        config.addAppender(appender);
        AppenderRef ref = AppenderRef.createAppenderRef("File", null, null);
        AppenderRef[] refs = new AppenderRef[] {ref};
        LoggerConfig loggerConfig = LoggerConfig.createLogger("false", "info", "org.apache.logging.log4j",
            "true", refs, null, config, null );
        loggerConfig.addAppender(appender, null, null);
        config.addLogger("org.apache.logging.log4j", loggerConfig);
        ctx.updateLoggers();

About the Author

Question Info

Publish Time
2023-01-25 06:57
Update Time
2023-01-25 06:57