Skip to content

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

Say I have an appender defined in the log4j.xml file below.

<appender name="FILE" class="org.apache.log4j.DailyRollingFileAppender">
            <param name="File" value="/home/logs/oarm_log.txt" />
            <param name="DatePattern" value="'.'yyyy-MM-dd-HH" />
            <layout class="org.apache.log4j.PatternLayout">
                 <param name="ConversionPattern" value="%d %-5p[] [%t] %c - %mn" />

How could I change the value “/home/logs/oarm_log.txt” to a different value that comes from a string found in the actual Java code so that the code determines where to output the .txt file?



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