How to use properties in a Spring project to configure log4j.xml
I have multiple properties files in my Spring project. The spring context loads these properties and handles property overriding in a convenient manner. Is there a way to take the properties that are available to my Spring configuration XML files (ie. ${myprop}
) and use them in a similar fashion in my log4j.xml
file? I know that I can pass system prop开发者_高级运维erties to log4j using -Dprop=value
on startup, but I would prefer having all of the configuration in the properties files in my project. Is this possible?
My app runs in Tomcat.
Try to use this class, after integrating your multiple properties files to one Properties.
public class DOMConfiguratorWithProperties extends DOMConfigurator {
private Properties propertiesField = null;
public synchronized Properties getProperties() {
return propertiesField;
}
public synchronized void setProperties(final Properties properties) {
propertiesField = properties;
}
@Override
protected String subst(final String value) {
return super.subst(value, getProperties());
}
public static void configure(final String filename) {
new DOMConfiguratorWithProperties().doConfigure(
filename,
LogManager.getLoggerRepository());
}
public static void configure(
final String filename,
final Properties properties) {
DOMConfiguratorWithProperties configurator = new DOMConfiguratorWithProperties();
configurator.setProperties(properties);
configurator.doConfigure(
filename,
LogManager.getLoggerRepository());
}
}
I think the only way you can interact with Log4J is through the Nested diagnostic context.
So if you are very desperate, you could write a Spring AOP aspect that sets the diagnostic context for your Spring Bean logs (and you could use the properties there). However, that would require that the Log be available to the Spring Bean, so you would need to add a getLog()
method to your service interfaces (this gets a lot easier if you use static AspectJ compilation and is described in AspectJ in Action).
But short of using AOP, I can't think of a sensible way to let Spring and Log4J interact.
精彩评论