Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can multiple log4j.properties files be used in the same Tomcat web app?

Tags:

log4j

I'm writing a custom extension to an off-the-shelf Java web application. The application uses log4j for logging and I'd like to add a new logger and appender specifically for my extension. The problem is that the application manages the log4j.properties file which is dynamically generated based on selections in an admin screen UI. Since this is an "off-the-shelf" application, I can't modify the source code. So, if I add my own logger & appender(s) to the file, it gets overwritten anytime an admin changes logging preferences in the UI.

Is it possible to get log4j to get it's configuration from 2 files? For example, I'd want something like the following:

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

In this scenario, log4j would somehow combine the entries from both files for the complete configuration.

Is this possible? or are there other workarounds?

like image 262
WayneC Avatar asked Nov 06 '22 07:11

WayneC


1 Answers

I never did find a way to "merge" multiple log4j.properties file, but I did find a workable solution. log4j configuration can be manipulated programatically at runtime similar to the code snippet below. This effectively merged my custom log4j settings into the configuration defined by the log4j.properties file, which in my case I couldn't 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);
like image 185
WayneC Avatar answered Nov 13 '22 01:11

WayneC