I'm writing a Java web application to deploy in Tomcat and i'm using log4j for logging. I like to insert automatically the web application's folder name in the generated log file's name.
Currently the filename setting looks like this in log4j.properties:
log4j.appender.R.File=${catalina.home}/logs/mywebapp.log
and i need something like this:
log4j.appender.R.File=${catalina.home}/logs/${current.webapp.folder}.log
Is there some kind of environment variable for this to specify in the properties file, or i have to instantiate the logger from code?
It's not a configuration file only solution, so i keep the question open for a while.
I've renamed the log4j.properties
to myapp-log4j.properties
and modified the log file name property like this:
log4j.appender.R.File=${catalina.base}/logs/#{context.name}.log
Because i have a servlet which is loaded at startup, i'm initializing log4j in the init() function.
String contextPath = getServletContext().getContextPath();
// First reconfigure log4j
String contextName = contextPath.substring(1);
if (!configureLog4J(contextName)) {
return;
}
The function for this:
public static final String LOG4JAPPENDERRFILE = "log4j.appender.R.File";
private boolean configureLog4J(String contextName) {
Properties props = new Properties();
try {
InputStream configStream = getClass().getResourceAsStream("/myapp-log4j.properties");
props.load(configStream);
configStream.close();
} catch(IOException e) {
System.out.println("FATAL! Cannot load log4j configuration file from classpath.");
e.printStackTrace(System.out);
return false;
}
String logFile = props.getProperty(LOG4JAPPENDERRFILE);
logFile=logFile.replace("#{context.name}", contextName);
props.setProperty(LOG4JAPPENDERRFILE, logFile);
LogManager.resetConfiguration();
PropertyConfigurator.configure(props);
return true;
}
It seems like to work fine, but i don't really like that i have to modify the properties file in code.