Archive
Configuring logging in Spring
If you’re like me, then you probably don’t want thousands of configuration files for your applications and keep everything in one place.
Few years back I was using Log4J for logging, but as a new solution has made its way into the SDK, I changed too. I know that a lot of people will argue and say that Log4J is much better, but I like more to use standard solution. Also Log4J became more like a de facto industry standard, so it becomes more like of a personal preference.
Anyway the solution proposed onward can be applied to both java.util.logging and Log4J, but I will exemplify only the first.
With Spring IoC container, you can easily create beans in your context. The idea is very simple, just create a bean using the Spring IoC and use the setter methods to configure the logging system.
public class LogConfigurator { public void setLogLevels(Map<String, String> logLevels) { for (String loggerName : logLevels.keySet()) { Logger.getLogger(loggerName).setLevel(Level.parse(logLevels.get(loggerName))); } } public void setLogHandlers(Map<String, Handler> logHandlers) { for (String loggerName : logHandlers.keySet()) { Logger.getLogger(loggerName).addHandler(logHandlers.get(loggerName)); } } public void setLogUseParentHandlers(Map<String, Boolean> logUseParentHandlers) { for (String loggerName : logUseParentHandlers.keySet()) { Logger.getLogger(loggerName).setUseParentHandlers(logUseParentHandlers.get(loggerName)); } } }
The above methods are used to set the logging levels, handlers and if to use the parent logger handlers. They receive as parameter a map between the logger name and the setting.
Now in your applicationContext.xml
file you will have:
<bean id="logConfigurator" class="LogConfigurator"> <property name="logHandlers"> <map> <entry key="module.1" value-ref="customHandler"/> </map> </property> <property name="logLevels"> <map> <entry key="module.2" value="INFO"/> </map> </property> </bean>
This will set the log level of the second module to INFO and will add a custom handler to the first module.
You can apply the same technique to some other configurations as well.