KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > jonas > common > Log


1 /**
2  * JOnAS: Java(TM) Open Application Server
3  * Copyright (C) 1999-2004 Bull S.A.
4  * Contact: jonas-team@objectweb.org
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19  * USA
20  *
21  * --------------------------------------------------------------------------
22  * $Id: Log.java,v 1.62 2005/05/13 12:33:54 danesa Exp $
23  * --------------------------------------------------------------------------
24  */

25
26
27 package org.objectweb.jonas.common;
28
29 import java.io.File JavaDoc;
30 import java.io.FileInputStream JavaDoc;
31 import java.io.FileNotFoundException JavaDoc;
32 import java.io.InputStream JavaDoc;
33 import java.io.PrintWriter JavaDoc;
34 import java.text.SimpleDateFormat JavaDoc;
35 import java.util.Date JavaDoc;
36 import java.util.Enumeration JavaDoc;
37 import java.util.Properties JavaDoc;
38
39 import org.objectweb.jonas_timer.TraceTimer;
40
41 import org.objectweb.common.TraceCore;
42
43 import org.objectweb.jonas_ejb.container.TraceEjb;
44
45 import org.objectweb.jonas_jms.TraceJms;
46
47 import org.objectweb.util.monolog.Monolog;
48 import org.objectweb.util.monolog.api.BasicLevel;
49 import org.objectweb.util.monolog.api.HandlerFactory;
50 import org.objectweb.util.monolog.api.LevelFactory;
51 import org.objectweb.util.monolog.api.Logger;
52 import org.objectweb.util.monolog.api.LoggerFactory;
53 import org.objectweb.util.monolog.api.MonologFactory;
54 import org.objectweb.util.monolog.file.DottedStringTools;
55 import org.objectweb.util.monolog.file.monolog.PropertiesConfAccess;
56 import org.objectweb.util.monolog.wrapper.p6spy.P6SpyLogger;
57 import org.objectweb.util.monolog.wrapper.printwriter.PrintWriterImpl;
58
59 /**
60  * This class provides utility method for using Monolog
61  * @author Philippe Coq.
62  * @author Sebastien Chassande-Barrioz sebastien.chassande@inrialpes.fr
63  * @author Philippe Durieux
64  * @author Florent Benoit & Ludovic Bert
65  * @author Adriana Danes : change MBean implementation model from inheritance to delegation
66  */

67 public class Log {
68
69     // name of the config file - initialized by the configure method
70
private static String JavaDoc configFile = "trace";
71
72     /**
73      * This class is actually a wrapper on the unique loggerFactory
74      */

75     private static LoggerFactory lf = null;
76
77     /**
78      * Properties used for Logging system
79      * Kept here mainly for debugging
80      */

81     private static Properties JavaDoc props = null;
82
83     // List of topic used inside JOnAS
84
// This list may be not exhaustive since many topics can be added for
85
// different purposes or to refine debugging.
86
// To get the complete list, use "jonas admin -t"
87

88     public static final String JavaDoc JONAS_ADMIN_PREFIX = "org.objectweb.jonas.admin";
89
90     public static final String JavaDoc JONAS_DBM_PREFIX = "org.objectweb.jonas.dbm";
91
92     public static final String JavaDoc JONAS_JCA_PREFIX = "org.objectweb.jonas.jca";
93
94     public static final String JavaDoc JONAS_CLIENT_PREFIX = "org.objectweb.jonas.client";
95
96     public static final String JavaDoc JONAS_JDBCXA_PREFIX = "org.objectweb.jonas.jdbc_xa";
97
98     public static final String JavaDoc JONAS_NAMING_PREFIX = "org.objectweb.jonas.naming";
99
100     public static final String JavaDoc JONAS_PROPCTX_PREFIX = "org.objectweb.jonas.propagation";
101
102     public static final String JavaDoc JONAS_REGISTRY_PREFIX = "org.objectweb.jonas.registry";
103
104     public static final String JavaDoc JONAS_SECURITY_PREFIX = "org.objectweb.jonas.security";
105
106     public static final String JavaDoc JONAS_CLIENTSTUBGEN_PREFIX = "org.objectweb.jonas_lib.genclientstub";
107
108     public static final String JavaDoc JONAS_GENBASE_PREFIX = "org.objectweb.jonas_lib.genbase";
109
110     public static final String JavaDoc JONAS_JACC_SECURITY_PREFIX = "org.objectweb.jonas.security.jacc";
111
112     public static final String JavaDoc JONAS_WS_SECURITY_PREFIX = "org.objectweb.jonas.security.ws";
113
114     public static final String JavaDoc JONAS_CSIV2_SECURITY_PREFIX = "org.objectweb.jonas.security.csiv2";
115
116     public static final String JavaDoc JONAS_CSIV2_DETAILS_SECURITY_PREFIX = "org.objectweb.jonas.security.csiv2_details";
117
118     public static final String JavaDoc JONAS_SERVER_PREFIX = "org.objectweb.jonas.server";
119
120     public static final String JavaDoc JONAS_WEB_PREFIX = "org.objectweb.jonas.web";
121
122     public static final String JavaDoc JONAS_EAR_PREFIX = "org.objectweb.jonas.ear";
123
124     public static final String JavaDoc JONAS_MAIL_PREFIX = "org.objectweb.jonas.mail";
125
126     public static final String JavaDoc JONAS_TESTS_PREFIX = "org.objectweb.jonas_tests";
127
128     public static final String JavaDoc JONAS_LOADER_PREFIX = "org.objectweb.jonas.loader";
129
130     public static final String JavaDoc JONAS_GENIC_PREFIX = "org.objectweb.jonas.genic";
131
132     public static final String JavaDoc JONAS_GENIC_VELOCITY_PREFIX = "org.objectweb.jonas.genic.velocity";
133
134     public static final String JavaDoc JONAS_WSGEN_PREFIX = "org.objectweb.jonas_ws.wsgen";
135
136     public static final String JavaDoc JONAS_WSGEN_EWS_PREFIX = "org.objectweb.jonas_ws.wsgen.ews";
137
138     public static final String JavaDoc JONAS_WS_PREFIX = "org.objectweb.jonas.ws";
139
140     public static final String JavaDoc JONAS_WS_EJBPROVIDER_PREFIX = "org.objectweb.jonas.ws.ejbprovider";
141
142     public static final String JavaDoc JONAS_PUBLISH_PREFIX = "org.objectweb.jonas.publication";
143
144     public static final String JavaDoc JONAS_JMX_PREFIX = "org.objectweb.jonas.jmx";
145
146     public static final String JavaDoc JONAS_MANAGEMENT_PREFIX = "org.objectweb.jonas.management";
147
148     public static final String JavaDoc JONAS_DOMAIN_MANAGEMENT_PREFIX = "org.objectweb.jonas.domain.management";
149
150     public static final String JavaDoc JONAS_MANAGEMENT_EVENT_PREFIX = "org.objectweb.jonas.management.event";
151
152     public static final String JavaDoc JONAS_MEJB = "org.objectweb.jonas.mejb";
153
154     public static final String JavaDoc JONAS_DISCOVERY_PREFIX = "org.objectweb.jonas.discovery";
155
156     public static final String JavaDoc SPY_LOGGER_NAME = "org.objectweb.jonas.jdbc.sql";
157
158     public static final String JavaDoc JONAS_DEPLOY_WORK_PREFIX = "org.objectweb.jonas_lib.deployment.work";
159
160     public static final String JavaDoc JONAS_JAXR_PREFIX = "org.objectweb.jonas.jaxr";
161
162     public static final String JavaDoc JONAS_WORK_MGR_PREFIX = "org.objectweb.jonas_lib.work";
163
164
165     /**
166      * Logger for Naming
167      */

168     private static boolean isDebugNaming = false;
169
170
171     /**
172      * Prefix for DB service (for example hsqldb service)
173      */

174     public static final String JavaDoc JONAS_DB_PREFIX = "org.objectweb.jonas.db";
175
176     /**
177      * Output tag for the hamdler
178      */

179     private static final String JavaDoc HANDLER_OUTPUT_ATTRIBUTE = "output";
180
181     /**
182      * Output tag which must be replaced by JOnAS
183      */

184     private static final String JavaDoc AUTOMATIC_CONFIG = "automatic";
185
186     /**
187      * Directory for the logs $JONAS_BASE/logs
188      */

189     private static final String JavaDoc LOG_DIRECTORY = "logs";
190
191     /**
192      * Format of a timestamp log.
193      */

194     private static final String JavaDoc TIMESTAMP_FORMAT = "-yyyy-MM-dd";
195
196     /**
197      * Suffix of a log file.
198      */

199     private static final String JavaDoc SUFFIX_LOGFILE = "log";
200
201     /**
202      * Default logger factory
203      */

204     private static final String JavaDoc DEFAULT_LOGGERFACTORY = "org.objectweb.util.monolog.wrapper.javaLog.LoggerFactory";
205
206     private static boolean clientcontainer = false;
207
208     /**
209      * JProp fully qualified Classname
210      */

211     private static final String JavaDoc JPROP_CLASSNAME = "org.objectweb.jonas.common.JProp";
212
213     /**
214      * Configure Logger
215      * @param file The configuration file for monolog (usually: trace.properties)
216      */

217     public static void configure(String JavaDoc file) {
218         configFile = file;
219         getLoggerFactory();
220         if (!clientcontainer) {
221             P6SpyLogger.logger = lf.getLogger(SPY_LOGGER_NAME);
222             TraceTimer.configure(lf);
223             TraceCore.configure(lf);
224             // Comment out call until JONAS uses Log4j
225
// TraceTm.configure(lf);
226
}
227
228         TraceEjb.configure(lf);
229         TraceJms.configure(lf);
230     }
231
232     /**
233      * It returns the unique LoggerFactory used in JOnAS.
234      * initialize it if not already done.
235      */

236     public static synchronized LoggerFactory getLoggerFactory() {
237         if (lf == null) {
238             try {
239                 // Detect client case = no JONAS_BASE
240
if (isClient()) {
241                     clientcontainer = true;
242                     InputStream JavaDoc is = null;
243
244                     // Is there a specific file to use instead the default name
245
String JavaDoc traceClient = System.getProperty("jonas.client.trace.file");
246                     if (traceClient != null) {
247                         try {
248                             is = new FileInputStream JavaDoc(new File JavaDoc(traceClient));
249                         } catch (FileNotFoundException JavaDoc fne) {
250                             System.err.println("Can not init logger with the supplied file '" + traceClient + "', this file doesn't exist. Init with default values.");
251
252                         }
253                     } else {
254                         //Client
255
//Is there a trace properties file in the classpath ?
256
is = Thread.currentThread().getContextClassLoader().getResourceAsStream("traceclient.properties");
257                     }
258                     if (is == null) {
259                         // no traceclient.properties found
260
// using a default configuration
261
props = new Properties JavaDoc();
262                         props.put("log.config.classname", DEFAULT_LOGGERFACTORY);
263                         props.put("logger.root.level", "INFO");
264                     } else {
265                         // use the configuration of the properties file.
266
props = new Properties JavaDoc();
267                         props.load(is);
268                     }
269                     lf = Monolog.getMonologFactory(props);
270                     return lf;
271                 }
272                 // server case
273
// get jonas configuration properties
274
Object JavaDoc jProp = null;
275                 try {
276                     jProp = JProp.getInstance();
277                     // Run jonas
278
// Create a JProp object for the configFile
279
JProp.getInstance(configFile);
280                 } catch (Exception JavaDoc e) {
281                     System.err.println("Can't read jonas.properties. Check that you have defined a $JONAS_BASE variable");
282                 }
283
284
285                 // load properties from config file
286
props = JProp.getInstance(configFile).getConfigFileEnv();
287                 String JavaDoc jonasBase = null;
288                 String JavaDoc nameOfServer = null;
289                 if (jProp != null) {
290                     jonasBase = JProp.getJonasBase();
291                     nameOfServer = ((JProp) jProp).getValue("jonas.name", "jonas");
292                 } else {
293                     // Set default
294
jonasBase = ".";
295                     nameOfServer = "jonas";
296                 }
297
298                 // Before sending props, replace AUTOMATIC pattern by a file in $JONAS_BASE/logs/
299
// File are named <JOnAS_server_name>TIMESTAMP_FORMAT.SUFFIX_LOGFILE
300
File JavaDoc logFirFile = new File JavaDoc(jonasBase + File.separator + LOG_DIRECTORY);
301
302                 // Properties sent may be updated if AUTOMATIC_CONFIG is used
303
// Updated properties are in
304
Properties JavaDoc updatedProps = null;
305
306                 //Create a date format
307
SimpleDateFormat JavaDoc sdf = new SimpleDateFormat JavaDoc(TIMESTAMP_FORMAT);
308                 String JavaDoc date = sdf.format(new Date JavaDoc());
309                 // How many AUTOMATIC field have been replaced
310
int nbAut = 0;
311
312                 File JavaDoc logFile = null;
313                 for (Enumeration JavaDoc keys = props.keys(); keys.hasMoreElements();) {
314                     String JavaDoc key = (String JavaDoc) keys.nextElement();
315                     if (key == null) {
316                         continue;
317                     }
318
319                     if (key.startsWith(PropertiesConfAccess.HANDLER_FIELD)) {
320                         String JavaDoc temp = DottedStringTools.getFirst(key);
321
322                         if (temp == null) {
323                             continue;
324                         }
325
326                         temp = DottedStringTools.getEnd(key);
327                         if (temp == null) {
328                             continue;
329                         }
330
331                         String JavaDoc handlerName = DottedStringTools.getBegin(temp);
332
333                         String JavaDoc stringType = props.getProperty(PropertiesConfAccess.HANDLER_FIELD + PropertiesConfAccess.DOT + handlerName + PropertiesConfAccess.DOT + PropertiesConfAccess.HANDLER_TYPE_ATTRIBUTE, null);
334                         String JavaDoc stringOutput = props.getProperty(PropertiesConfAccess.HANDLER_FIELD + PropertiesConfAccess.DOT + handlerName + PropertiesConfAccess.DOT + HANDLER_OUTPUT_ATTRIBUTE, null);
335                         // Got the type and the output
336
// --> Compare with the pattern AUTOMATIC_CONFIG for the FILE type.
337
if ((stringType != null) && (stringOutput != null)) {
338                             if (PropertiesConfAccess.HANDLER_TYPE_ATTRIBUTE_FILE_VALUE.equalsIgnoreCase(stringType)
339                                 || (PropertiesConfAccess.HANDLER_TYPE_ATTRIBUTE_ROLLING_FILE_VALUE.equalsIgnoreCase(stringType))) {
340                                 if (stringOutput.equalsIgnoreCase(AUTOMATIC_CONFIG)) {
341                                     // OK, it's match
342
String JavaDoc fileName = null;
343
344                                     if (nbAut > 0) {
345                                         // Add an unique entry by adding nbAut value.
346
fileName = nameOfServer + date + PropertiesConfAccess.DOT + nbAut + PropertiesConfAccess.DOT + SUFFIX_LOGFILE;
347                                     } else {
348                                         // this is the first occurence of AUTOMATIC_CONFIG, create updatedProps
349
updatedProps = (Properties JavaDoc) props.clone();
350                                         fileName = nameOfServer + date + PropertiesConfAccess.DOT + SUFFIX_LOGFILE;
351                                     }
352
353                                     // Log directory exists ?
354
if (logFirFile.exists()) {
355                                         logFile = new File JavaDoc(logFirFile, fileName);
356                                     } else {
357                                         // No $JONAS_BASE/logs directory, try current directory
358
logFile = new File JavaDoc(fileName);
359                                     }
360
361                                     updatedProps.setProperty(PropertiesConfAccess.HANDLER_FIELD + PropertiesConfAccess.DOT + handlerName + PropertiesConfAccess.DOT + HANDLER_OUTPUT_ATTRIBUTE, logFile.getPath());
362                                     nbAut++;
363
364                                 }
365                                 else {
366                                     // not automatic -- change relative file name to be relative to JONAS_BASE/logs
367
logFile = new File JavaDoc(stringOutput);
368                                     if (!logFile.isAbsolute()) {
369                                         // file name is relative so try to create in JONAS_BASE/logs
370
if (logFirFile.exists()) { // Log directory exists ?
371
logFile = new File JavaDoc(logFirFile, stringOutput);
372                                         } else { // No $JONAS_BASE/logs directory, try current directory
373
logFile = new File JavaDoc(stringOutput);
374                                         }
375                                         if (nbAut == 0) {
376                                             updatedProps = (Properties JavaDoc) props.clone();
377                                             nbAut++;
378                                         }
379                                         if (stringOutput.endsWith(".automatic") ||
380                                             stringOutput.endsWith(".auto")) {
381                                             nbAut++;
382                                             String JavaDoc autoStr = logFile.getPath().substring(0, logFile.getPath().lastIndexOf('.')) + date +
383                                                              PropertiesConfAccess.DOT + nbAut + PropertiesConfAccess.DOT + SUFFIX_LOGFILE;
384                                             logFile = new File JavaDoc(autoStr);
385                                         }
386                                         updatedProps.setProperty(PropertiesConfAccess.HANDLER_FIELD + PropertiesConfAccess.DOT + handlerName + PropertiesConfAccess.DOT + HANDLER_OUTPUT_ATTRIBUTE, logFile.getPath());
387                                     }
388                                 }
389                             }
390                         }
391                     }
392                 }
393
394                 // Instanciate the LoggerFactory
395
String JavaDoc b = props.getProperty("log.config.classname", null);
396                 if (b == null) {
397                     System.err.println("Malformed configuration log file: log.config.classname not available");
398                     return null;
399                 }
400                 lf = (LoggerFactory) Class.forName(b).newInstance();
401                 // Configure the LoggerFactory with the updated properties or the initial ones
402
if (updatedProps == null) {
403                     PropertiesConfAccess.load(props, lf, (HandlerFactory) lf, (LevelFactory) lf);
404                 } else {
405                     PropertiesConfAccess.load(updatedProps, lf, (HandlerFactory) lf, (LevelFactory) lf);
406                 }
407                 //Register the monolog factory in Monolog
408
Monolog.monologFactory = (MonologFactory) lf;
409             } catch (Exception JavaDoc e) {
410                 System.err.println("Cannot get LoggerFactory:" + e);
411                 e.printStackTrace();
412             }
413         }
414         return lf;
415     }
416
417     /**
418      * @return Returns true if we are in a client context
419      */

420     private static boolean isClient() {
421         boolean hasJonasBase = System.getProperty("jonas.base") != null;
422         boolean hasJonasRoot = System.getProperty("install.root") != null;
423         boolean hasJProp = true;
424         try {
425             Thread.currentThread().getContextClassLoader().loadClass(JPROP_CLASSNAME);
426         } catch (ClassNotFoundException JavaDoc cnfe) {
427             hasJProp = false;
428         }
429         // a server has the 3 params, all other case are clients case
430
return !(hasJProp && hasJonasBase && hasJonasRoot);
431     }
432
433     /**
434      * Reset logger factory
435      */

436     public static void reset() {
437         lf = null;
438     }
439
440     /**
441      * Returns the standard PrintWriter associated to the logger defined by
442      * its topic.
443      * This is mainly used for DBM and Connectors.
444      */

445     public static PrintWriter JavaDoc getLogWriter(String JavaDoc topic) {
446         // TODO : should not create a new object at each call
447
return new PrintWriterImpl(getLogger(topic), getLoggerFactory());
448     }
449
450     /**
451      * Shortcut that returns the LevelFactory
452      */

453     public static LevelFactory getLevelFactory() {
454         return (LevelFactory) getLoggerFactory();
455     }
456
457     /**
458      * Shortcut to get the Logger by its topic name.
459      * @param topic the topic of the returned logger
460      * @return always a logger instance (never null value).
461      */

462     public static Logger getLogger(String JavaDoc topic) {
463         return getLoggerFactory().getLogger(topic);
464     }
465
466     public static Properties JavaDoc getProperties() {
467         return props;
468     }
469
470     public static final boolean isDebugNaming() {
471         return isDebugNaming;
472     }
473
474
475     /**
476      * Sets booleans which enable debugging (debug level or Warn)
477      */

478     public static void syncLevels() {
479         // debug
480
isDebugNaming = getLogger(JONAS_NAMING_PREFIX).isLoggable(BasicLevel.DEBUG);
481     }
482 }
483
Popular Tags