1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.settings4j.helper.web;
19
20 import java.net.MalformedURLException;
21 import java.net.URL;
22 import java.util.Locale;
23
24 import javax.servlet.ServletContext;
25
26 import org.apache.log4j.PropertyConfigurator;
27 import org.apache.log4j.helpers.Loader;
28 import org.apache.log4j.xml.DOMConfigurator;
29 import org.settings4j.Settings4j;
30
31
32
33
34
35
36
37
38
39
40
41
42
43 public class Log4jConfigurationLoader {
44
45
46
47
48 public static final String LOG4J_CONFIG_SETTINGS4JKEY = "settings4jLog4jConfigurationKey";
49
50 private ServletContext servletContext;
51
52
53
54
55
56
57
58 public void initLog4jConfiguration(final ServletContext servCxt) {
59 servletContext = servCxt;
60
61
62 createDefaultPropertiesLoader().initDefaultProperties(servletContext);
63
64 final String log4jConfigSettings4jKey = servletContext.getInitParameter(LOG4J_CONFIG_SETTINGS4JKEY);
65 if (log4jConfigSettings4jKey == null) {
66 log("Log4j not initialized: context parameter not set [name=" + LOG4J_CONFIG_SETTINGS4JKEY + "]");
67 return;
68 }
69 final String configLocation = Settings4j.getString(log4jConfigSettings4jKey);
70 if (configLocation == null) {
71 log("Log4j not initialized: configLocation not set");
72 } else {
73 try {
74 this.initLogging(configLocation);
75 log("Log4j initialized [configurationPath=" + configLocation + "]");
76 } catch (final Throwable e) {
77 log("Log4j not initialized [configurationPath=" + configLocation + "]", e);
78 }
79 }
80 }
81
82
83
84
85 protected void initLogging(final String configLocation) {
86 log("initLogging [" + configLocation + "].");
87 URL url = null;
88 try {
89 url = new URL(configLocation);
90 log("found url: " + url);
91 } catch (final MalformedURLException ex) {
92
93
94 log("attempt to get the resource from the class path.");
95 url = Loader.getResource(configLocation);
96 }
97 if (url != null) {
98 log("Using URL [" + url + "] for automatic log4j configuration.");
99
100 if (configLocation.toLowerCase(Locale.ENGLISH).endsWith(".xml")) {
101 DOMConfigurator.configure(url);
102 } else {
103 PropertyConfigurator.configure(url);
104 }
105
106 } else {
107 log("Could not find resource: [" + configLocation + "].");
108 }
109 }
110
111
112
113
114
115
116
117
118
119 public void log(final String message, final Throwable throwable) {
120 servletContext.log(message, throwable);
121 }
122
123
124
125
126
127
128
129 public void log(final String msg) {
130 servletContext.log(msg);
131 }
132
133
134
135
136
137
138 protected DefaultPropertiesLoader createDefaultPropertiesLoader() {
139 return new DefaultPropertiesLoader();
140 }
141
142 }