]> git.argeo.org Git - gpl/argeo-slc.git/blob - org.argeo.slc.core/src/main/java/org/argeo/slc/logging/Log4jUtils.java
6398e608e289b62d80bff3792bf8af943489affb
[gpl/argeo-slc.git] / org.argeo.slc.core / src / main / java / org / argeo / slc / logging / Log4jUtils.java
1 package org.argeo.slc.logging;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.util.Properties;
6
7 import org.apache.commons.io.IOUtils;
8 import org.apache.log4j.LogManager;
9 import org.apache.log4j.PropertyConfigurator;
10 import org.argeo.slc.core.SlcException;
11 import org.springframework.core.io.DefaultResourceLoader;
12 import org.springframework.util.ResourceUtils;
13 import org.springframework.util.SystemPropertyUtils;
14
15 public class Log4jUtils {
16
17 /**
18 * Configure log4j based on properties, with the following priorities (from
19 * highest to lowest):<br>
20 * 1. System properties<br>
21 * 2. configuration file itself
22 */
23 public static void initLog4j(String configuration) {
24 // clears previous configuration
25 shutDownLog4j();
26
27 ClassLoader cl = Log4jUtils.class.getClassLoader();
28 Properties properties = new Properties();
29 if (configuration != null) {
30 InputStream in = null;
31 try {
32 if (configuration
33 .startsWith(ResourceUtils.CLASSPATH_URL_PREFIX)) {
34 String path = configuration
35 .substring(ResourceUtils.CLASSPATH_URL_PREFIX
36 .length());
37 in = cl.getResourceAsStream(path);
38 } else {
39 in = new DefaultResourceLoader(cl).getResource(
40 configuration).getInputStream();
41 }
42
43 properties.load(in);
44 } catch (IOException e) {
45 throw new SlcException("Cannot load properties from "
46 + configuration);
47 } finally {
48 IOUtils.closeQuietly(in);
49 }
50 }
51
52 // Overrides with System properties
53 overrideLog4jProperties(properties, System.getProperties());
54
55 PropertyConfigurator.configure(properties);
56 }
57
58 private static void overrideLog4jProperties(Properties target,
59 Properties additional) {
60 for (Object obj : additional.keySet()) {
61 String key = obj.toString();
62 if (key.startsWith("log4j.")) {
63 if (!key.equals("log4j.configuration")) {
64 String value = SystemPropertyUtils
65 .resolvePlaceholders(additional.getProperty(key));
66 target.put(key, value);
67 }
68 }
69 }
70 }
71
72 public static void shutDownLog4j() {
73 LogManager.shutdown();
74 }
75
76 private Log4jUtils() {
77
78 }
79 }