How to insert current webapp folder name in log4j file_name

I am writing a Java web application for deployment in Tomcat and I use log4j for logging. I like to automatically insert the folder name of the web application into the generated log file name.

Currently the file name setting looks like this: 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 in the properties file, or do I need to create a registrar instance from the code?

+8
java web-applications tomcat log4j
source share
2 answers

This is not a solution only for the configuration file, so I leave the question open for a while.

I renamed log4j.properties to myapp-log4j.properties and changed the log file name property as follows:

 log4j.appender.R.File=${catalina.base}/logs/#{context.name}.log 

Since I have a servlet that loads at startup, I initialize 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; } 

Everything seems to be working fine, but I don't really like that I need to change the properties file in the code.

+1
source share

First try adding your "log4j.properties".

 current.webapp.folder=myapp 

Secondly, if you used the "PropertyConfigurator" ...

 Properties props = new Property(); /* Read "log4j.properties" */ Properties webappProps = new Property(); /* Read setting ex."current.webapp.folder=myapp" */ Enumeration<Object> e = props.propertyNames(); while (e.hasMoreElements()) { String key = (String) e.nextElement(); // used org.apache.log4j.helpers.OptionConverter props.setProperty( key, OptionConverter.substVars(props.getProperty(key), webappProps)); } PropertyConfigurator.configure(props); 
0
source share

All Articles