KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > logging > MonologFactory


1 /*
2  *
3  *
4  * @ author Igor Smirnov
5  */

6
7 package org.enhydra.logging;
8
9 import java.io.FileInputStream JavaDoc;
10 import java.util.Enumeration JavaDoc;
11 import java.util.Hashtable JavaDoc;
12 import java.util.Iterator JavaDoc;
13 import java.util.Locale JavaDoc;
14 import java.util.Properties JavaDoc;
15 import java.util.ResourceBundle JavaDoc;
16 import java.util.Set JavaDoc;
17 import java.util.Vector JavaDoc;
18
19 import javax.management.MBeanServer JavaDoc;
20 import javax.management.MBeanServerFactory JavaDoc;
21 import javax.management.ObjectName JavaDoc;
22
23 import org.apache.commons.logging.Log;
24 import org.apache.commons.logging.LogConfigurationException;
25 import org.apache.commons.logging.LogFactory;
26 import org.objectweb.util.monolog.Monolog;
27 import org.objectweb.util.monolog.api.Logger;
28 import org.objectweb.util.monolog.api.LoggerFactory;
29 import org.objectweb.util.monolog.wrapper.common.Configurable;
30
31 import com.lutris.util.ConfigException;
32
33 /**
34  * <p>Concrete subclass of {@link LogFactory} specific to log4j.
35  *
36  * @deprecated Per discussion on COMMONS-DEV, the behind-the-scenes use
37  * of this class as a proxy factory has been removed. For 1.0, you
38  * can still request it directly if you wish, but it doesn't really
39  * do anything useful, and will be removed in 1.1.
40  *
41  * @author Costin Manolache
42  */

43 public final class MonologFactory extends LogFactory {
44    public org.objectweb.util.monolog.api.LoggerFactory lf;
45    public String JavaDoc traceproperties;
46    private Logger logger = null;
47    private String JavaDoc path, jonas, fileName;
48    private static ResourceBundle JavaDoc rb = null;
49    public static String JavaDoc PROPERTY_FILE;
50    static ObjectName JavaDoc objectName;
51    
52     public MonologFactory() throws ConfigException{
53       
54       super();
55       try {
56               configure();
57               this.logger = lf.getLogger("MonologFactory");
58             }catch (ConfigException ex) {
59               throw new ConfigException("Cannot configure logger. Logger not initialized.");
60             }
61     }
62
63     /**
64      * The configuration attributes for this {@link LogFactory}.
65      */

66     private Hashtable JavaDoc attributes = new Hashtable JavaDoc();
67
68     // previously returned instances, to avoid creation of proxies
69
private Hashtable JavaDoc instances = new Hashtable JavaDoc();
70
71     // --------------------------------------------------------- Public Methods
72

73     /**
74      * Return the configuration attribute with the specified name (if any),
75      * or <code>null</code> if there is no such attribute.
76      *
77      * @param name Name of the attribute to return
78      */

79     public Object JavaDoc getAttribute(String JavaDoc name) {
80         return (attributes.get(name));
81     }
82     
83     /**
84      * Return an array containing the names of all currently defined
85      * configuration attributes. If there are no such attributes, a zero
86      * length array is returned.
87      */

88     public String JavaDoc[] getAttributeNames() {
89         Vector JavaDoc names = new Vector JavaDoc();
90         Enumeration JavaDoc keys = attributes.keys();
91         while (keys.hasMoreElements()) {
92             names.addElement((String JavaDoc) keys.nextElement());
93         }
94         String JavaDoc results[] = new String JavaDoc[names.size()];
95         for (int i = 0; i < results.length; i++) {
96             results[i] = (String JavaDoc) names.elementAt(i);
97         }
98         return (results);
99     }
100     
101
102     /**
103      * Convenience method to derive a name from the specified class and
104      * call <code>getInstance(String)</code> with it.
105      *
106      * @param clazz Class for which a suitable Log name will be derived
107      *
108      * @exception LogConfigurationException if a suitable <code>Log</code>
109      * instance cannot be returned
110      */

111     public Log getInstance(Class JavaDoc clazz)
112         throws LogConfigurationException
113
114     {
115         Log instance = (Log) instances.get(clazz.getName());
116         if( instance != null )
117             return instance;
118         instance=new CommonLoggingMonologLogger(lf.getLogger(clazz.getName()));
119         instances.put( clazz.getName(), instance );
120         return instance;
121     }
122
123     public Log getInstance(String JavaDoc name)
124         throws LogConfigurationException
125     {
126         Log instance = (Log) instances.get(name);
127         if( instance != null )
128             return instance;
129
130         instance=new CommonLoggingMonologLogger( lf.getLogger( name ));
131         instances.put( name, instance );
132         return instance;
133     }
134
135
136     /**
137      * Release any internal references to previously created {@link Log}
138      * instances returned by this factory. This is useful environments
139      * like servlet containers, which implement application reloading by
140      * throwing away a ClassLoader. Dangling references to objects in that
141      * class loader would prevent garbage collection.
142      */

143     public void release() {
144
145         instances.clear();
146
147         // what's the log4j mechanism to cleanup ???
148
}
149
150
151     /**
152      * Remove any configuration attribute associated with the specified name.
153      * If there is no such attribute, no action is taken.
154      *
155      * @param name Name of the attribute to remove
156      */

157     public void removeAttribute(String JavaDoc name) {
158         attributes.remove(name);
159     }
160
161
162     /**
163      * Set the configuration attribute with the specified name. Calling
164      * this with a <code>null</code> value is equivalent to calling
165      * <code>removeAttribute(name)</code>.
166      *
167      * @param name Name of the attribute to set
168      * @param value Value of the attribute to set, or <code>null</code>
169      * to remove any setting for this attribute
170      */

171     public void setAttribute(String JavaDoc name, Object JavaDoc value) {
172         if (value == null) {
173             attributes.remove(name);
174         } else {
175             attributes.put(name, value);
176         }
177     }
178
179     /**
180      * Configure the logger. All current configuration is discarded.
181      * This is a simplistic initial implementation that just allows
182      * directing to a single log file or stderr on a level basis.
183      * A more complete interface will be provided in the future.
184      *
185      * @param logFile The log file to write to.
186      * @param fileLevels List of levels that will be written to the file.
187      * @param stderrLevels List of levels that will be written to stderr.
188      * The same level may appear in both lists.
189      * @exception java.io.IOException If an error occurs opening the log file.
190      */

191     public synchronized void configure(String JavaDoc monologConfFile) {
192       
193         // Load the configuration in a Properties object
194
String JavaDoc b = null;
195       Properties JavaDoc p = new Properties JavaDoc();
196         try {
197            p.load(new FileInputStream JavaDoc(monologConfFile));
198         // Search the class name of the LoggerFactory which must be instanciated
199
b = p.getProperty("log.config.classname", null);
200         // Instanciate the LoggerFactory
201
lf = (LoggerFactory) Class.forName(b).newInstance();
202         // Configure with the properties
203
p.put(Configurable.LOG_CONFIGURATION_TYPE, Configurable.PROPERTY);
204        p.put(Configurable.LOG_CONFIGURATION_FILE, monologConfFile);
205
206          ((Configurable) lf).configure(p);
207
208
209           }
210         catch (Exception JavaDoc e) {
211
212        }
213   }
214   
215     /**
216      * Default configuration of the logger. A JMX search for logger configuration file name.
217      * This file must be present in the classpath
218      */

219   public synchronized void configure()
220         throws ConfigException {
221           String JavaDoc b = null;
222           String JavaDoc propkey;
223           String JavaDoc propvalue;
224           Properties JavaDoc props = new Properties JavaDoc();
225              
226      try{
227          findMBeanServer();
228          findObjectName();
229          if (objectName != null)
230             PROPERTY_FILE = objectName.getKeyProperty("fname");
231          // Search the classpath for the logger configuration file
232
rb = ResourceBundle.getBundle(PROPERTY_FILE,new Locale JavaDoc("en","US"), ClassLoader.getSystemClassLoader());
233       
234      Enumeration JavaDoc enumeration = rb.getKeys();
235      
236      while (enumeration.hasMoreElements())
237      {
238
239          propkey = (String JavaDoc) enumeration.nextElement();
240          propvalue = rb.getString(propkey);
241          props.setProperty(propkey, propvalue);
242      }
243          
244       } catch (Exception JavaDoc e){
245         throw new ConfigException("Logger configuration file could not be found: logger could not be initialized!");
246     }
247
248         try {
249
250         // Search the class name of the LoggerFactory which must be instanciated
251
b = props.getProperty("log.config.classname", null);
252            if (b == null) {
253                throw new ConfigException("Malformed configuration log file:"
254                    + " log.config.classname not available");
255            }
256
257            // Instanciate the LoggerFactory
258

259          props.put(Configurable.LOG_CONFIGURATION_TYPE, Configurable.PROPERTY);
260 // lf = Monolog.getMonologFactory(props);
261

262          lf = Monolog.getMonologFactory(b);
263
264
265           }
266         catch (Exception JavaDoc e) {
267            throw new ConfigException("Malformed configuration log file:"
268                    + " log.config.classname not available");
269        }
270     
271 }
272
273
274   private MBeanServer JavaDoc findMBeanServer () throws Exception JavaDoc {
275     MBeanServer JavaDoc mBeanServer;
276     try {
277       java.util.ArrayList JavaDoc server = MBeanServerFactory.findMBeanServer(null);
278       if (server == null) {
279         throw new Exception JavaDoc("MBeansServer not found");
280       }
281       else {
282         mBeanServer = (MBeanServer JavaDoc)server.get(0);
283         //System.err.println("domain:" + mBeanServer.getDefaultDomain());
284
}
285     } catch (Exception JavaDoc e) {
286       throw new com.lutris.appserver.server.session.SessionException(e);
287     }
288     return mBeanServer;
289   }
290
291   /**
292    * finds the ObjectName which correspondes to the MBean of the jonas logger
293    */

294   private void findObjectName () throws Exception JavaDoc {
295     try {
296       objectName = new ObjectName JavaDoc("jonas:type=service,name=log,*");
297       MBeanServer JavaDoc mBeanServer = findMBeanServer();
298       Set JavaDoc mBeans = mBeanServer.queryNames(objectName, null);
299       int l;
300       if ((l = mBeans.size()) > 1) {
301         throw new Exception JavaDoc("MBean set size not equal 1: " + l);
302       }else if (l == 0){
303         objectName = null;
304         return;
305     }
306       Iterator JavaDoc i = mBeans.iterator();
307       objectName = (ObjectName JavaDoc)i.next();
308     } catch (Exception JavaDoc e) {
309       throw new Exception JavaDoc(e);
310     }
311     return;
312   }
313
314   }
Popular Tags