KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > util > monolog > wrapper > log4j > MonologLoggerFactory


1 /**
2  * Copyright (C) 2001-2003 France Telecom R&D
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17  */

18 package org.objectweb.util.monolog.wrapper.log4j;
19
20 import org.apache.log4j.PropertyConfigurator;
21 import org.apache.log4j.BasicConfigurator;
22 import org.apache.log4j.LogManager;
23 import org.apache.log4j.xml.DOMConfigurator;
24 import org.objectweb.util.monolog.api.BasicLevel;
25 import org.objectweb.util.monolog.api.Logger;
26 import org.objectweb.util.monolog.api.TopicalLogger;
27 import org.objectweb.util.monolog.wrapper.common.AbstractFactory;
28 import org.objectweb.util.monolog.Monolog;
29
30 import java.io.FileInputStream JavaDoc;
31 import java.io.FileNotFoundException JavaDoc;
32 import java.io.IOException JavaDoc;
33 import java.io.InputStream JavaDoc;
34 import java.util.Enumeration JavaDoc;
35 import java.util.Properties JavaDoc;
36 import java.util.ResourceBundle JavaDoc;
37 import java.util.HashSet JavaDoc;
38
39 /**
40  * This class wraps the LoggerFactory, HandlerFactory, LevelFactory concepts
41  * into the log4j world. This implementation supports also the Configurable
42  * interface. Then it is possible to specify a log4j configuration file.
43  *
44  * @author Sebastien Chassande-Barrioz
45  */

46 public class MonologLoggerFactory
47         extends AbstractFactory {
48
49     public static final String JavaDoc LOG4J_CF_PROP = "log4j.categoryFactory";
50     public static final String JavaDoc LOG4J_CF_VALUE
51         = "org.objectweb.util.monolog.wrapper.log4j.MonologCategoryFactory";
52
53     /**
54      * The root logger of the logger hierarchy
55      */

56     protected static Logger rootLogger = null;
57
58     /**
59      * It specifies the factory of MonologCategory instances.
60      */

61     private static org.apache.log4j.spi.LoggerFactory factory
62         = new MonologCategoryFactory();
63
64     /**
65      * This static code initializes the BasicLevel fields.
66      */

67     static {
68         BasicLevel.INHERIT = -1;
69         debug("INHERIT= " + BasicLevel.INHERIT);
70         BasicLevel.DEBUG = org.apache.log4j.Level.DEBUG.toInt();
71         debug("DEBUG= " + BasicLevel.DEBUG);
72         BasicLevel.INFO = org.apache.log4j.Level.INFO.toInt();
73         debug("INFO= " + BasicLevel.INFO);
74         BasicLevel.WARN = org.apache.log4j.Level.WARN.toInt();
75         debug("WARN= " + BasicLevel.WARN);
76         BasicLevel.ERROR = org.apache.log4j.Level.ERROR.toInt();
77         debug("ERROR= " + BasicLevel.ERROR);
78         BasicLevel.FATAL = org.apache.log4j.Level.FATAL.toInt();
79         debug("FATAL= " + BasicLevel.FATAL);
80
81         BasicLevel.LEVEL_INHERIT = new LevelImpl("INHERIT", BasicLevel.INHERIT);
82         BasicLevel.LEVEL_DEBUG = new LevelImpl("DEBUG", BasicLevel.DEBUG);
83         BasicLevel.LEVEL_INFO = new LevelImpl("INFO", BasicLevel.INFO);
84         BasicLevel.LEVEL_WARN = new LevelImpl("WARN", BasicLevel.WARN);
85         BasicLevel.LEVEL_ERROR = new LevelImpl("ERROR", BasicLevel.ERROR);
86         BasicLevel.LEVEL_FATAL = new LevelImpl("FATAL", BasicLevel.FATAL);
87
88         if (!org.apache.log4j.Logger.getRootLogger().getAllAppenders().hasMoreElements()) {
89             BasicConfigurator.configure();
90         }
91         if (classLoaderIsoltion) {
92             String JavaDoc rootName = null;
93             int i = 0;
94             while (rootLogger == null) {
95                 rootName = "root" + i;
96                 try {
97                     org.apache.log4j.Logger rlog =
98                         org.apache.log4j.Logger.getLogger(rootName, factory);
99                     rlog.setAdditivity(false);
100                     rootLogger = (Logger) rlog;
101                     Monolog.debug("Instanciate the root logger " + rootName);
102                 } catch (ClassCastException JavaDoc exc) {
103                     // this name has already been reserved by another
104
// instance of this class from another class loader
105
i ++;
106                 }
107             }
108             rootLoggerName = rootName;
109             rootLoggerPrefix = rootLoggerName + '.';
110         }
111     }
112
113     /**
114      * It intializes the data struture, defines the default level and the root
115      * logger.
116      */

117     public MonologLoggerFactory() {
118         super();
119         if (!classLoaderIsoltion) {
120             rootLogger = new MonologCategory(
121                 org.apache.log4j.Logger.getRootLogger());
122         }
123     }
124
125     public String JavaDoc getWrapperName() {
126         return "log4j";
127     }
128
129     protected String JavaDoc[][] getDefaultHandlerType2className() {
130         return new String JavaDoc[][] {
131             {handlerTypes[0], "org.objectweb.util.monolog.wrapper.log4j.ConsoleHandler"},
132             {handlerTypes[1], "org.objectweb.util.monolog.wrapper.log4j.FileHandler"},
133             {handlerTypes[2], "org.objectweb.util.monolog.wrapper.log4j.RollingFileHandler"},
134             {handlerTypes[3], "org.objectweb.util.monolog.wrapper.log4j.NTEventLogHandler"},
135             {handlerTypes[4], "org.objectweb.util.monolog.wrapper.log4j.JMXHandler"}
136         };
137     }
138
139     // IMPLEMENTATION OF THE Configurable INTERFACE //
140

141     /**
142      * This method permits to configure the factory with tha specific
143      * configuration file: like a log4j.properties
144      */

145     public void configure(Properties JavaDoc prop) throws Exception JavaDoc {
146         debug("MonologLoggerFactory.configure(prop=" + prop + ")");
147         if (prop == null) {
148             if (!org.apache.log4j.Logger.getRootLogger().getAllAppenders().hasMoreElements()) {
149                 BasicConfigurator.configure();
150             }
151             return;
152         }
153
154         String JavaDoc conf = prop.getProperty(LOG_CONFIGURATION_TYPE,
155             prop.getProperty("log4jConfiguration", DEFAULT));
156         debug("MonologLoggerFactory.configure(): conf=" + conf);
157
158         if (DEFAULT.equals(conf)) {
159             if (!org.apache.log4j.Logger.getRootLogger().getAllAppenders().hasMoreElements()) {
160                 BasicConfigurator.configure();
161             }
162             return;
163         }
164
165         // Fetch the configuration file name
166
String JavaDoc filename = prop.getProperty(LOG_CONFIGURATION_FILE,
167             prop.getProperty("log4jConfigurationFile", ""));
168         debug("MonologLoggerFactory.configure(): filename=" + filename);
169
170         if (XML.equals(conf)) {
171             DOMConfigurator.configure(filename);
172         }
173         else if (PROPERTY.equals(conf)) {
174             Properties JavaDoc log4jfileprop = null;
175             // Check if the file name designs a path valid into the
176
// classpath, or designs a path valid into the file system.
177
// In both case load the property file
178
if (prop.getProperty(LOG_CONFIGURATION_FILE_USE_CLASSPATH, "false")
179                 .equalsIgnoreCase("true")
180                 || prop.getProperty("findFileInClassPath", "false")
181                 .equalsIgnoreCase("true")) {
182
183                 debug("MonologLoggerFactory.configure(): load from classpath");
184
185                 if (!LogManager.DEFAULT_CONFIGURATION_FILE.equals(filename)) {
186                     debug("MonologLoggerFactory.configure(): not default config file");
187                     // valid into the classpath
188
log4jfileprop = getProperties(filename);
189                     log4jfileprop.setProperty(LOG4J_CF_PROP, LOG4J_CF_VALUE);
190                     PropertyConfigurator.configure(log4jfileprop);
191                 }
192                 // else the file is already loaded by the Logger class
193
}
194             else {
195                 debug("MonologLoggerFactory.configure(): load from file system");
196                 // valid into the file system
197
log4jfileprop = new Properties JavaDoc();
198                 log4jfileprop.load(new FileInputStream JavaDoc(filename));
199                 log4jfileprop.setProperty(LOG4J_CF_PROP, LOG4J_CF_VALUE);
200                 PropertyConfigurator.configure(log4jfileprop);
201             }
202         }
203         else {
204             throw new Exception JavaDoc("Unsupported configuration type: " + conf);
205         }
206         debug("MonologLoggerFactory.configure(): End");
207     }
208
209     // Return null if properties are not reachable
210
private Properties JavaDoc getProperties(String JavaDoc name) throws IOException JavaDoc {
211         InputStream JavaDoc is = getClass().getClassLoader().getResourceAsStream(name);
212         if (is != null) {
213             Properties JavaDoc props = new Properties JavaDoc();
214             props.load(is);
215             return props;
216         }
217         throw new FileNotFoundException JavaDoc("Not found in classpath: " + name);
218     }
219
220
221     // IMPLEMENTATION OF INTERFACE LoggerFactory //
222
//-------------------------------------------//
223

224     public Logger getLogger(String JavaDoc key) {
225         if (key == null || key.length() == 0 || key.equalsIgnoreCase("root")) {
226             return rootLogger;
227         }
228                 // isolates the logger hierarchy
229
key = monoLoggerName(key);
230         if (resourceBundleName == null)
231             return (Logger) org.apache.log4j.Logger.getLogger(key, factory);
232         else
233             return getLogger(key, resourceBundleName);
234     }
235
236     public synchronized Logger getLogger(String JavaDoc key, String JavaDoc rbn) {
237         if (key == null || key.length() == 0 || key.equalsIgnoreCase("root")) {
238             return rootLogger;
239         }
240                 // isolates the logger hierarchy
241
key = monoLoggerName(key);
242         org.apache.log4j.Logger res =
243             org.apache.log4j.Logger.getLogger(key, factory);
244         res.setResourceBundle(ResourceBundle.getBundle(rbn));
245         return (Logger) res;
246     }
247
248     public Logger[] getLoggers() {
249         HashSet JavaDoc al = new HashSet JavaDoc();
250         for (Enumeration JavaDoc e = org.apache.log4j.LogManager.getCurrentLoggers();
251              e.hasMoreElements();) {
252             Object JavaDoc o = e.nextElement();
253             if (o instanceof Logger)
254                 al.add(o);
255         }
256         al.add(rootLogger);
257         return (Logger[]) al.toArray(new TopicalLogger[0]);
258     }
259 }
260
Popular Tags