Can I use multiple log4j.properties files in the same Tomcat web application?

I am writing a special extension for a ready-made Java web application. The application uses log4j for logging, and I would like to add a new logger and application specifically for my extension. The problem is that the application manages the log4j.properties file, which is dynamically generated based on the selection in the user interface of the admin screen. Since this is a ready-made application, I cannot change the source code. Therefore, if I add my own registrar and appender (s) to the file, it will be overwritten at any time when the administrator changes the logging settings in the user interface.

Is it possible to get log4j for its configuration from 2 files? For example, I would like something like the following:

applog.properties #(Dynamically generated from admin UI)
mylog.properties  #(My static properties)

In this case, log4j will somehow combine the entries from both files for a complete configuration.

Is it possible? or are there other workarounds?

+5
source share
1 answer

I never found a way to merge several log4j.properties files, but I found a suitable solution. The log4j configuration can be controlled programmatically at runtime, similar to the code snippet below. This effectively combined my user log4j parameters into the configuration defined by the log4j.properties file, which in my case I could not edit.

// Init custom logging

// Define layout
PatternLayout layout = new PatternLayout();
layout.setConversionPattern("%d [%-5p] -- %m%n");

// Create appender
RollingFileAppender appender = new RollingFileAppender();
appender.setFile(LOG_PATH);
appender.setMaxFileSize("2MB");
appender.setMaxBackupIndex(0);
appender.setLayout(layout);
appender.activateOptions(); // It didn't work without this

// Get our logger and add appender.
log = Logger.getLogger("[MyCustomLogger]");
log.setLevel(YOUR_LOGGING_LEVEL_HERE);
log.addAppender(appender);
+2
source

All Articles