KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > catalina > logger > TomcatMonologFileLogger


1 /*
2     TomcatMonologFileLogger.java
3     An Extension of a Logger that channels the logging trough Monolog instead
4     of Tomcat's default FileLogger.
5  */

6
7 //package org.enhydra.logging;
8
package org.apache.catalina.logger;
9
10 import java.io.File JavaDoc;
11 import java.io.FileInputStream JavaDoc;
12 import java.io.FileWriter JavaDoc;
13 import java.io.IOException JavaDoc;
14 import java.io.PrintWriter JavaDoc;
15 import java.sql.Timestamp JavaDoc;
16 import java.util.Enumeration JavaDoc;
17 import java.util.Iterator JavaDoc;
18 import java.util.Locale JavaDoc;
19 import java.util.Properties JavaDoc;
20 import java.util.ResourceBundle JavaDoc;
21 import java.util.Set JavaDoc;
22
23 import javax.management.MBeanServerConnection JavaDoc;
24 import javax.management.ObjectName JavaDoc;
25 import javax.management.remote.JMXConnector JavaDoc;
26 import javax.management.remote.JMXConnectorFactory JavaDoc;
27 import javax.management.remote.JMXServiceURL JavaDoc;
28
29 import org.apache.catalina.LifecycleException;
30 import org.apache.catalina.util.StringManager;
31 import org.objectweb.util.monolog.Monolog;
32 import org.objectweb.util.monolog.api.BasicLevel;
33 import org.objectweb.util.monolog.api.Level;
34 import org.objectweb.util.monolog.api.LoggerFactory;
35 import org.objectweb.util.monolog.wrapper.common.Configurable;
36
37 import com.lutris.util.Config;
38 import com.lutris.util.ConfigException;
39
40
41 /**
42  * Implementation of <b>Logger</b> that appends log messages to a file
43  * named {prefix}.{date}.{suffix} in a configured directory, with an
44  * optional preceding timestamp.
45  *
46  * @author Igor Smirnov
47  * @version $Revision: v1.0
48  */

49
50 public class TomcatMonologFileLogger
51     extends LoggerBase {
52       private String JavaDoc _options;
53       private transient boolean _started;
54       private org.objectweb.util.monolog.api.LoggerFactory lf;
55       private org.objectweb.util.monolog.api.Logger logger = null;
56       private String JavaDoc path, jonas, fileName;
57       private static ResourceBundle JavaDoc rb = null;
58       public static String JavaDoc PROPERTY_FILE;
59       static ObjectName JavaDoc objectName;
60       //LifecycleSupport lifecycle = new LifecycleSupport(LoggerBase.class);
61

62       public TomcatMonologFileLogger () throws ConfigException {
63       
64       try {
65               configure();
66               this.logger = lf.getLogger("TomcatMonologFileLogger");
67               
68             }catch (ConfigException ex) {
69                 throw new ConfigException("TomcatMonologFileLogger:Cannot configure logger. Logger not initialized.");
70             }
71      
72     }
73
74     private String JavaDoc date = "";
75
76     /**
77      * The directory in which log files are created.
78      */

79     private String JavaDoc directory = "logs";
80
81
82     /**
83      * The descriptive information about this implementation.
84      */

85     protected static final String JavaDoc info =
86         "org.apache.catalina.logger.FileLogger/1.0";
87
88
89     /**
90      * The prefix that is added to log file filenames.
91      */

92     private String JavaDoc prefix = "catalina.";
93
94
95     /**
96      * The string manager for this package.
97      */

98     private StringManager sm =
99         StringManager.getManager(Constants.Package);
100
101
102     /**
103      * Has this component been started?
104      */

105     private boolean started = false;
106
107
108     /**
109      * The suffix that is added to log file filenames.
110      */

111     private String JavaDoc suffix = ".log";
112
113
114     /**
115      * Should logged messages be date/time stamped?
116      */

117     private boolean timestamp = false;
118
119
120     /**
121      * The PrintWriter to which we are currently logging, if any.
122      */

123     private PrintWriter JavaDoc writer = null;
124
125
126     // --------------------------------------------------------- Public Methods
127

128
129     /**
130      * Writes the specified message to a servlet log file, usually an event
131      * log. The name and type of the servlet log is specific to the
132      * servlet container.
133      *
134      * @param msg A <code>String</code> specifying the message to be written
135      * to the log file
136      */

137     public void log(String JavaDoc msg){
138              
139         // Construct the timestamp we will use, if requested
140

141         Timestamp JavaDoc ts = new Timestamp JavaDoc(System.currentTimeMillis());
142         String JavaDoc tsString = ts.toString().substring(0, 19);
143         String JavaDoc tsDate = tsString.substring(0, 10);
144         String JavaDoc logString = "";
145
146         // If the date has changed, switch log files
147
/*if (!date.equals(tsDate)) {
148             synchronized (this) {
149                 if (!date.equals(tsDate)) {
150                     close();
151                     date = tsDate;
152                     open();
153                 }
154             }
155         }*/

156
157         // Log this message, timestamped if necessary
158

159             if (timestamp) {
160                 logString = tsString + " " + msg;
161             } else {
162                 logString = msg;
163             }
164         
165         
166         Level priority=BasicLevel.LEVEL_INFO;
167         
168         /*if (Log.DEBUG.equals(tag))
169             priority=BasicLevel.LEVEL_DEBUG;
170         else if (Log.WARN.equals(tag) || Log.ASSERT.equals(tag))
171             priority=BasicLevel.LEVEL_ERROR;
172         else if (Log.FAIL.equals(tag))
173             priority=BasicLevel.LEVEL_FATAL; */

174         
175         //if (!logger.isLoggable(priority))
176
// return;
177

178         logger.log(priority,
179                 "",
180                 ""+msg,
181                 null);
182
183     }
184
185       public synchronized void configure(String JavaDoc monologConfFile)
186         throws ConfigException {
187       
188         if (monologConfFile==null || monologConfFile.length() == 0) {
189             throw new ConfigException(
190                 "impossible to configure monolog without configuration file");
191         }
192         // Load the configuration in a Properties object
193
String JavaDoc b = null;
194       Properties JavaDoc p = new Properties JavaDoc();
195         try {
196   
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          
201            if (b == null) {
202                throw new ConfigException("Malformed configuration log file:"
203                    + " log.config.classname not available");
204            }
205   
206            // Instanciate the LoggerFactory
207
lf = (LoggerFactory) Class.forName(b).newInstance();
208            // Configure with the properties
209
p.put(Configurable.LOG_CONFIGURATION_TYPE, Configurable.PROPERTY);
210          p.put(Configurable.LOG_CONFIGURATION_FILE, monologConfFile);
211   // p.put(Configurable.LOG_CONFIGURATION_FILE_USE_CLASSPATH, "true");
212

213          ((Configurable) lf).configure(p);
214
215   
216   // PropertiesConfAccess.load(p, lf, (HandlerFactory) lf, (LevelFactory) lf);
217
}
218         catch (Exception JavaDoc e) {
219            throw new ConfigException("Malformed configuration log file:"
220                    + " log.config.classname not available");
221        }
222   }
223   
224     public synchronized void configure()
225         throws ConfigException {
226           String JavaDoc b = null;
227           String JavaDoc propkey;
228           String JavaDoc propvalue;
229           Properties JavaDoc props = new Properties JavaDoc();
230        
231    // Search the classpath for the logger configuration file
232

233              
234      try{
235          findObjectName();
236          if (objectName != null)
237             PROPERTY_FILE = objectName.getKeyProperty("fname");
238           rb = ResourceBundle.getBundle(PROPERTY_FILE,new Locale JavaDoc("en","US"), ClassLoader.getSystemClassLoader());
239       
240      Enumeration JavaDoc enumeration = rb.getKeys();
241  
242      
243      while (enumeration.hasMoreElements())
244      {
245
246          propkey = (String JavaDoc) enumeration.nextElement();
247          propvalue = rb.getString(propkey);
248          props.setProperty(propkey, propvalue);
249      }
250       
251       
252       } catch (Exception JavaDoc e){
253         throw new ConfigException("Logger configuration file could not be found: logger could not be initialized!");
254     }
255
256         try {
257
258         // Search the class name of the LoggerFactory which must be instanciated
259
b = props.getProperty("log.config.classname", null);
260            if (b == null) {
261                throw new ConfigException("Malformed configuration log file:"
262                    + " log.config.classname not available");
263            }
264
265            // Instanciate the LoggerFactory
266

267          props.put(Configurable.LOG_CONFIGURATION_TYPE, Configurable.PROPERTY);
268          lf = Monolog.getMonologFactory(b);
269          
270
271     // PropertiesConfAccess.load(p, lf, (HandlerFactory) lf, (LevelFactory) lf);
272
}
273         catch (Exception JavaDoc e) {
274            throw new ConfigException("Malformed configuration log file:"
275                    + " log.config.classname not available");
276        }
277
278   }
279
280
281     /**
282      * Configure Logger with given config section
283      *
284      * @param logConfig containing parameters for configuring logger
285      */

286     public void configure(Config logConfig) throws ConfigException {
287         String JavaDoc fileName = null;
288
289         if (logConfig.containsKey("Monolog")) {
290             fileName = logConfig.getString("Monolog");
291             try{
292               configure(fileName);
293              } catch (Exception JavaDoc ex) {
294                 try {
295                   configure();
296                 }catch (ConfigException cex) {
297                   throw new ConfigException("Cannot configure logger. Config file is null.");
298                 }
299              }
300
301         } else {
302             try {
303               configure();
304             }catch (ConfigException ex) {
305               throw new ConfigException("Cannot configure logger. Logger not initialized.");
306             }
307         }
308      }
309   
310   
311   /**
312    * finds the ObjectName which correspondes to the MBean of the jonas logger
313    */

314   private void findObjectName () throws Exception JavaDoc {
315     JMXConnector JavaDoc connector = null;
316     try {
317      
318       String JavaDoc serviceName = "jonas";
319       
320       // The name of the started jonas server (service name)
321
serviceName = System.getProperty("jonas.name");
322       if ( serviceName == null) {
323         serviceName = "jonas";
324       }
325       
326
327
328       // The address of the connector server
329
JMXServiceURL JavaDoc url = new JMXServiceURL JavaDoc("service:jmx:rmi://localhost/jndi/jrmpconnector_" + serviceName);
330
331       // Connect a JSR 160 JMXConnector to the server side
332
connector = JMXConnectorFactory.connect(url);
333
334       // Retrieve an MBeanServerConnection that represent the MBeanServer the remote
335
// connector server is bound to
336
MBeanServerConnection JavaDoc connection = connector.getMBeanServerConnection();
337
338         objectName = new ObjectName JavaDoc(serviceName + ":type=service,name=log,*");
339         
340       Set JavaDoc mBeans = connection.queryNames(objectName, null);
341       int l = mBeans.size();
342       if ((l) > 1) {
343         throw new Exception JavaDoc("MBean set size not equal 1: " + l);
344       }else if (l == 0){
345         objectName = null;
346         if (connector!=null){
347             try {
348                 connector.close();
349             } catch (Exception JavaDoc exept){}
350         }
351         return;
352         }
353       Iterator JavaDoc i = mBeans.iterator();
354       objectName = (ObjectName JavaDoc)i.next();
355     } catch (Exception JavaDoc e) {
356       throw new Exception JavaDoc(e);
357     }finally {
358         if (connector!=null){
359             try {
360                 connector.close();
361             } catch (Exception JavaDoc exept){}
362         }
363     }
364     return;
365   }
366
367  private void close() {
368
369         if (writer == null)
370             return;
371         writer.flush();
372         writer.close();
373         writer = null;
374         date = "";
375
376     }
377
378 /**
379      * Open the new log file for the date specified by <code>date</code>.
380      */

381     private void open() {
382
383         // Create the directory if necessary
384
File JavaDoc dir = new File JavaDoc(directory);
385         if (!dir.isAbsolute())
386             dir = new File JavaDoc(System.getProperty("catalina.base"), directory);
387         dir.mkdirs();
388
389         // Open the current log file
390
try {
391             String JavaDoc pathname = dir.getAbsolutePath() + File.separator +
392                 prefix + date + suffix;
393             writer = new PrintWriter JavaDoc(new FileWriter JavaDoc(pathname, true), true);
394         } catch (IOException JavaDoc e) {
395             writer = null;
396         }
397
398     }
399
400  public void start() throws LifecycleException {}
401                                                                                     
402                               
403                               
404     /**
405      * Gracefully terminate the active use of the public methods of this
406      * component. This method should be the last one called on a given
407      * instance of this component.
408      *
409      * @exception LifecycleException if this component detects a fatal error
410      * that needs to be reported
411      */

412     public void stop() throws LifecycleException {}
413     
414 }
415
Popular Tags