I have a project with log4j properties defined in xml.
<?xml version="1.0" encoding="UTF-8" ?>
<Configuration>
<Appenders>
<File name="LogFileAppender" fileName="${sys:logFileName:-default}" append="false">
<PatternLayout>
<Pattern>%d [%t] %p - %m%n</Pattern>
</PatternLayout>
</File>
</Appenders>
<Loggers>
<Root level="error">
<AppenderRef ref="LogFileAppender"/>
</Root>
</Loggers>
</Configuration>
I update the fileName value to the correct path in the code before any logging occurs to get the correct output folder.
public static void initializeLoggers(String logPath)
{
// set output paths for log files
System.setProperty("logFileName", logPath + "PROJECT.log");
// reconfigure loggers with paths
org.apache.logging.log4j.core.LoggerContext ctx =
(org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false);
ctx.reconfigure();
}
Everything works as expected for the most part. Log files are output to the correct logPath with data written out. However, there is a file called "default" created in the default project directory before we even reach initializeLoggers() because of the call to
static Logger log = LogManager.getLogger(MyClass.class); // Logging
at the top of the code.
I found away to not generate a "default file" by simply leaving the field as blank like so:
fileName="${sys:logFileName:-}"
But in doing so the code complains and gives errors since the property is null at that specific time.
2022-01-19 13:07:51,936 main ERROR The parameter is null: fileName 2022-01-19 13:07:51,944 main ERROR Could not create plugin of type class org.apache.logging.log4j.core.appender.FileAppender for element File org.apache.logging.log4j.core.config.ConfigurationException: Arguments given for element File are invalid: field 'fileName' has invalid value '' at org.apache.logging.log4j.core.config.plugins.util.PluginBuilder.injectFields(PluginBuilder.java:210)
Is there any way around this so that I can
- not generate an unused "default file"
- not have errors being thrown about null values