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