From: Mathieu Baudier Date: Sat, 21 Jun 2008 12:02:34 +0000 (+0000) Subject: Restructure example X-Git-Tag: argeo-slc-2.1.7~2781 X-Git-Url: http://git.argeo.org/?a=commitdiff_plain;h=c25e351a0ac40764d555234235adf7f71c463e0c;p=gpl%2Fargeo-slc.git Restructure example Improve logging git-svn-id: https://svn.argeo.org/slc/trunk@1261 4cfe0d0a-d680-48aa-b62c-e0a02a3f76cc --- diff --git a/org.argeo.slc.core/src/main/java/org/argeo/slc/logging/Log4jUtils.java b/org.argeo.slc.core/src/main/java/org/argeo/slc/logging/Log4jUtils.java new file mode 100644 index 000000000..6249c6f21 --- /dev/null +++ b/org.argeo.slc.core/src/main/java/org/argeo/slc/logging/Log4jUtils.java @@ -0,0 +1,78 @@ +package org.argeo.slc.logging; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +import org.apache.commons.io.IOUtils; +import org.apache.log4j.LogManager; +import org.apache.log4j.PropertyConfigurator; +import org.argeo.slc.core.SlcException; +import org.springframework.core.io.DefaultResourceLoader; +import org.springframework.util.ResourceUtils; +import org.springframework.util.SystemPropertyUtils; + +public class Log4jUtils { + + /** + * Configure log4j based on properties, with the following priorities (from + * highest to lowest):
+ * 1. System properties
+ * 2. configuration file itself + */ + public static void initLog4j(String configuration) { + // clears previous configuration + shutDownLog4j(); + + ClassLoader cl = Log4jUtils.class.getClassLoader(); + Properties properties = new Properties(); + if (configuration != null) { + InputStream in = null; + try { + if (configuration + .startsWith(ResourceUtils.CLASSPATH_URL_PREFIX)) { + String path = configuration + .substring(ResourceUtils.CLASSPATH_URL_PREFIX + .length()); + in = cl.getResourceAsStream(path); + } else { + in = new DefaultResourceLoader(cl).getResource( + configuration).getInputStream(); + } + + properties.load(in); + } catch (IOException e) { + throw new SlcException("Cannot load properties from " + + configuration); + } finally { + IOUtils.closeQuietly(in); + } + } + + // Overrides with System properties + overrideLog4jProperties(properties, System.getProperties()); + + PropertyConfigurator.configure(properties); + } + + private static void overrideLog4jProperties(Properties target, + Properties additional) { + for (String key : additional.stringPropertyNames()) { + if (key.startsWith("log4j.")) { + if (!key.equals("log4j.configuration")) { + String value = SystemPropertyUtils + .resolvePlaceholders(additional.getProperty(key)); + target.put(key, value); + } + } + } + } + + public static void shutDownLog4j() { + LogManager.shutdown(); + } + + private Log4jUtils() { + + } +}