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