View Javadoc
1   /*
2    * #%L
3    * settings4j
4    * ===============================================================
5    * Copyright (C) 2008 - 2015 Brabenetz Harald, Austria
6    * ===============================================================
7    * Licensed under the Apache License, Version 2.0 (the "License");
8    * you may not use this file except in compliance with the License.
9    * You may obtain a copy of the License at
10   * 
11   *      http://www.apache.org/licenses/LICENSE-2.0
12   * 
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   * #L%
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   * With this Implementation you can define a Key in your web.xml (init-parameter "settings4jLog4jConfigurationKey") with that you can configure your Path to
36   * your log4j.xml.
37   * <p>
38   * Each WebApplication in you Servlet Container can have its own key. And so you can configure for each webApplication a separated log4j.xml.
39   * </p>
40   * <p>
41   * See Example {@link Log4jConfigurationLoaderListener}.
42   * </p>
43   *
44   * @author brabenetz
45   */
46  public class Log4jConfigurationLoader {
47  
48      /**
49       * Key for log4j configuration.
50       */
51      public static final String LOG4J_CONFIG_SETTINGS4JKEY = "settings4jLog4jConfigurationKey";
52  
53      private ServletContext servletContext;
54  
55      /**
56       * If the InitParameter "Settings4jLog4jConfigurationKey" exists in the given {@link ServletContext}, then Log4j
57       * will be configured with it.
58       *
59       * @param servCxt The ServletContext where the InitParameters are configured.
60       */
61      public void initLog4jConfiguration(final ServletContext servCxt) {
62          this.servletContext = servCxt;
63  
64          // be sure that the DefaultPropertiesLoader is initialized:
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       * @param configLocation location.
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              // so, resource is not a URL:
96              // attempt to get the resource from the class path
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      * Writes an explanatory message and a stack trace for a given <code>Throwable</code> exception to the servlet log
117      * file. The name and type of the servlet log file is specific to the servlet container, usually an event log.
118      *
119      * @param message a <code>String</code> that describes the error or exception
120      * @param throwable the <code>Throwable</code> error or exception
121      */
122     public void log(final String message, final Throwable throwable) {
123         this.servletContext.log(message, throwable);
124     }
125 
126     /**
127      * Writes the specified message to a servlet log file, usually an event log. The name and type of the servlet log
128      * file is specific to the servlet container.
129      *
130      * @param msg a <code>String</code> specifying the message to be written to the log file
131      */
132     public void log(final String msg) {
133         this.servletContext.log(msg);
134     }
135 
136     /**
137      * Create the DefaultPropertiesLoader to use. Can be overridden in subclasses.
138      *
139      * @return the new DefaultPropertiesLoader
140      */
141     protected DefaultPropertiesLoader createDefaultPropertiesLoader() {
142         return new DefaultPropertiesLoader();
143     }
144 
145 }