KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > server > logging > ServerLogManager


1
2 /*
3  * The contents of this file are subject to the terms
4  * of the Common Development and Distribution License
5  * (the License). You may not use this file except in
6  * compliance with the License.
7  *
8  * You can obtain a copy of the license at
9  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
10  * glassfish/bootstrap/legal/CDDLv1.0.txt.
11  * See the License for the specific language governing
12  * permissions and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL
15  * Header Notice in each file and include the License file
16  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
17  * If applicable, add the following below the CDDL Header,
18  * with the fields enclosed by brackets [] replaced by
19  * you own identifying information:
20  * "Portions Copyrighted [year] [name of copyright owner]"
21  *
22  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
23  */

24 package com.sun.enterprise.server.logging;
25
26
27
28 import java.util.logging.Logger JavaDoc;
29 import java.util.logging.Level JavaDoc;
30 import java.util.logging.Handler JavaDoc;
31 import java.util.logging.Filter JavaDoc;
32 import java.util.logging.ConsoleHandler JavaDoc;
33 import java.util.logging.ErrorManager JavaDoc;
34
35 import java.util.List JavaDoc;
36 import java.util.Iterator JavaDoc;
37
38 import com.sun.enterprise.server.ServerContext;
39 import com.sun.enterprise.server.ApplicationServer;
40 import com.sun.enterprise.config.serverbeans.ServerBeansFactory;
41 import com.sun.enterprise.config.serverbeans.Server;
42 import com.sun.enterprise.config.serverbeans.Config;
43 import com.sun.enterprise.config.serverbeans.ElementProperty;
44 import com.sun.enterprise.config.serverbeans.ModuleLogLevels;
45 import com.sun.enterprise.config.serverbeans.LogService;
46
47 import com.sun.logging.LogDomains;
48
49
50 /**
51  * Class ServerLogManager is a subclass of LogManager for use within the
52  * Application Server. The FileandSyslogHandler is installed
53  * on each logger created by this log manager.
54  *
55  * _REVISIT_: Need to make sure that the LogLevels in domain.xml is parsed
56  * first to set the log levels correctly. We may miss setting some of the
57  * loglevels, because the values in domain.xml is not available when some
58  * loggers are created
59  */

60 public class ServerLogManager extends BaseLogManager {
61
62     // We will use a single instance of Handler for all the Loggers
63
// Note: these handlers extend StreamHandler whose methods are synchronized
64
private static FileandSyslogHandler handlerSingleton;
65     private static ConsoleHandler JavaDoc consoleHandler;
66     private static SystemLogHandler syslogHandler;
67     private static DeploymentAuditLogHandler deploymentAuditHandler;
68     
69     // If we are running on Windows, RI or some other platform where we
70
// cannot do syslog and the user has turned on use-system-logging is true
71
// then we will set this flag to avoid wasting cycles to reload the library
72
private static boolean syslogLibraryLoadError = false;
73
74     // If there is any CustomHandler and/or CustomFilter we will plug that.
75
private static Handler JavaDoc customHandler = null;
76     private static Filter JavaDoc customFilter = null;
77
78
79     private static ServerLogManager thisInstance;
80
81     private static List JavaDoc listOfUnInitializedLoggers = new java.util.ArrayList JavaDoc();
82
83     // caches value of System property com.sun.aas.verboseMode
84
private static Boolean JavaDoc verboseMode = null;
85
86     private static boolean customFilterError = false;
87
88     private static boolean customHandlerError = false;
89
90     private static final String JavaDoc SUN_OS = "SunOS";
91
92     private static final String JavaDoc LINUX_OS = "Linux";
93
94     private static final String JavaDoc OS_NAME_PROPERTY = "os.name";
95
96     private Object JavaDoc lockObj = new Object JavaDoc();
97
98     private static final String JavaDoc ORG_APACHE_CATALINA = "org.apache.catalina.";
99     private static final String JavaDoc ORG_APACHE_COYOTE = "org.apache.coyote.";
100     private static final String JavaDoc ORG_APACHE_JASPER = "org.apache.jasper.";
101     private static final String JavaDoc SYNCHRONIZATION =
102                         "javax.ee.enterprise.system.tools.synchronization";
103
104     public ServerLogManager() {
105         super();
106         thisInstance = this;
107     }
108
109     /**
110      * When a new logger is created in the system, this method will be invoked
111      * to intialize the log level appropriately and also to set the required
112      * LogHandlers.
113      */

114     protected void initializeLogger(Logger JavaDoc logger) {
115     synchronized(lockObj) {
116             internalInitializeLogger( logger );
117         
118             if( getLogService() == null ) {
119                 listOfUnInitializedLoggers.add( logger );
120             }
121         }
122     }
123
124     /**
125      * Internal Method to initialize a list of unitialized loggers.
126      */

127     private void internalInitializeLogger( final Logger JavaDoc logger ) {
128         java.security.AccessController.doPrivileged(
129             new java.security.PrivilegedAction JavaDoc() {
130                 public Object JavaDoc run() {
131                     // Explicitly remove all handlers.
132
Handler JavaDoc[] h = logger.getHandlers();
133                     for (int i = 0; i < h.length; i++) {
134                         logger.removeHandler(h[i]);
135                     }
136
137                     if (logger.getName().equals(LogDomains.DPLAUDIT_LOGGER)) {
138                         // redirect to deployment audit log
139
logger.addHandler(getDeploymentAuditHandler());
140                         logger.setUseParentHandlers(false);
141                     }
142
143
144                     if( logger.getName().intern() == "".intern() ) {
145
146                         logger.addHandler(getFileandSyslogHandler() );
147                         if ( logToStderr() ) {
148                             logger.addHandler(getConsoleHandler());
149                         }
150                         if( logToSyslog() ) {
151                            Handler JavaDoc syslogHandler = getSyslogHandler();
152                            if( syslogHandler != null ) {
153                                logger.addHandler( syslogHandler );
154                            }
155                         }
156                         logger.setUseParentHandlers( false );
157
158                     }
159
160                     Level JavaDoc logLevel = getConfiguredLogLevel(logger.getName());
161                     if( logLevel != null ) {
162                         logger.setLevel( logLevel );
163                     }
164                     postInitializeLogger( logger );
165                     return null;
166                 }
167             }
168         );
169     }
170
171     /**
172      * This is where we plug in any custom Log Handler and Log Filter.
173      */

174     private void postInitializeLogger( final Logger JavaDoc logger ) {
175         final Handler JavaDoc customHandler = getCustomHandler( );
176         final Filter JavaDoc customFilter = getCustomFilter( );
177         if( ( customHandler == null)
178           &&( customFilter == null ) ) {
179             return;
180         }
181         java.security.AccessController.doPrivileged(
182             new java.security.PrivilegedAction JavaDoc() {
183                 public Object JavaDoc run() {
184                     if( customHandler != null ) {
185                          logger.addHandler( customHandler );
186                     }
187                     if( customFilter != null ) {
188                          logger.setFilter( customFilter );
189                     }
190                     return null;
191                 }
192             }
193         );
194     }
195
196
197     /**
198      * _REVISIT_: Talk to JDO team to see if we can nuke this method and
199      * rely on the generic framework for the Logger initialization..
200      */

201     public static void initializeServerLogger( Logger JavaDoc logger ) {
202     }
203
204
205     /**
206      * This is a Singleton factory method to get and instance of
207      * FileandSyslogHandler.
208      */

209     private static synchronized Handler JavaDoc getFileandSyslogHandler ( ) {
210         if( handlerSingleton == null ) {
211             try {
212                 handlerSingleton = FileandSyslogHandler.getInstance();
213                 handlerSingleton.setLevel( Level.ALL );
214             } catch( Exception JavaDoc e ) {
215                 new ErrorManager JavaDoc().error( "Exception caught in getHandler ",
216                      e, ErrorManager.GENERIC_FAILURE );
217             }
218         }
219         return handlerSingleton;
220     }
221
222     
223     /**
224      * This is a Singleton factory method to get an instance of
225      * DeploymentLogHandler.
226      */

227     private static synchronized Handler JavaDoc getDeploymentAuditHandler( ) {
228         if( deploymentAuditHandler == null ) {
229             try {
230                 deploymentAuditHandler = DeploymentAuditLogHandler.getInstance();
231                 deploymentAuditHandler.setLevel(DeploymentAuditLogHandler.getConfiguredLevel());
232             } catch( Exception JavaDoc e ) {
233                 new ErrorManager JavaDoc().error( "Exception caught in getHandler ",
234                      e, ErrorManager.GENERIC_FAILURE );
235             }
236         }
237         return deploymentAuditHandler;
238     }
239
240
241     /**
242      * This is a Singleton factory method to get an instance of ConsoleHandler.
243      */

244     private static synchronized Handler JavaDoc getConsoleHandler() {
245         if( consoleHandler == null ) {
246             try {
247                 consoleHandler = new ConsoleHandler JavaDoc();
248                 consoleHandler.setLevel(Level.ALL);
249                 consoleHandler.setFormatter(new UniformLogFormatter());
250
251             } catch( Exception JavaDoc e ) {
252                 new ErrorManager JavaDoc().error(
253                      "Exception caught in getConsoleHandler ",
254                      e, ErrorManager.GENERIC_FAILURE );
255             }
256         }
257         return consoleHandler;
258     }
259
260
261      private static synchronized Handler JavaDoc getSyslogHandler() {
262          if( syslogLibraryLoadError ) return null;
263          if( syslogHandler == null ) {
264              try {
265                  syslogHandler = new SystemLogHandler();
266                  syslogHandler.setLevel(Level.ALL);
267                  syslogHandler.setFormatter(new UniformLogFormatter());
268  
269              } catch( Exception JavaDoc e ) {
270                  syslogLibraryLoadError = true;
271                  // WE WILL EAT AWAY THE EXCEPTION, IF SOME ONE TURNS ON SYSLOG
272
// ON WINDOWS or LINUX, They will not see any error.
273
}
274          }
275          return syslogHandler;
276      }
277
278     /**
279      * If there is any custom handler we will use that.
280      */

281     private static synchronized Handler JavaDoc getCustomHandler( ) {
282         if( (customHandler != null )
283           ||(customHandlerError) )
284         {
285             return customHandler;
286         }
287         LogService logService = getLogService( );
288         if( logService == null ) {
289             return null;
290         }
291         String JavaDoc customHandlerClassName = null;
292         try {
293             customHandlerClassName = logService.getLogHandler( );
294
295             customHandler = (Handler JavaDoc) getInstance( customHandlerClassName );
296             // We will plug in our UniformLogFormatter to the custom handler
297
// to provide consistent results
298
if( customHandler != null ) {
299                 customHandler.setFormatter( new UniformLogFormatter( ) );
300             }
301         } catch( Exception JavaDoc e ) {
302             customHandlerError = true;
303             new ErrorManager JavaDoc().error( "Error In Initializing Custom Handler " +
304                 customHandlerClassName, e, ErrorManager.GENERIC_FAILURE );
305         }
306         return customHandler;
307     }
308
309     /**
310      * If there is any Custom Filter we will use that.
311      */

312     private static Filter JavaDoc getCustomFilter( ) {
313         if(( customFilter != null )
314           ||( customFilterError ) )
315         {
316             return customFilter;
317         }
318         LogService logService = getLogService( );
319         if( logService == null ) {
320             return null;
321         }
322         String JavaDoc customFilterClassName = null;
323         try {
324             customFilterClassName = logService.getLogFilter( );
325             customFilter = (Filter JavaDoc) getInstance( customFilterClassName );
326         } catch( Exception JavaDoc e ) {
327             customFilterError = true;
328             new ErrorManager JavaDoc().error( "Error In Instantiating Custom Filter " +
329                 customFilterClassName, e, ErrorManager.GENERIC_FAILURE );
330         }
331         return customFilter;
332     }
333
334
335     /**
336      * A Utility method to get the LogService Configuration element.
337      */

338     static LogService getLogService( ) {
339         try {
340             ServerContext sc = ApplicationServer.getServerContext();
341             if( sc == null ) {
342                 return null;
343             }
344             return ServerBeansFactory.getConfigBean(
345                 sc.getConfigContext()).getLogService( );
346         } catch( Exception JavaDoc e ) {
347             new ErrorManager JavaDoc().error( "Error In getLogService ", e,
348                 ErrorManager.GENERIC_FAILURE );
349         }
350         return null;
351     }
352
353
354     /**
355      * A Utility method to instantiate Custom Log Handler and Log Filter.
356      */

357     private static Object JavaDoc getInstance( final String JavaDoc className ) {
358         if( className == null ) return null;
359         return java.security.AccessController.doPrivileged(
360             new java.security.PrivilegedAction JavaDoc() {
361                 public Object JavaDoc run() {
362                     try {
363                         ClassLoader JavaDoc cl =
364                             Thread.currentThread().getContextClassLoader();
365                         if (cl == null)
366                             cl = ClassLoader.getSystemClassLoader();
367                         return Class.forName( className, true,cl).newInstance();
368                     } catch( Exception JavaDoc e ) {
369                         new ErrorManager JavaDoc().error(
370                             "Error In Instantiating Class " + className, e,
371                             ErrorManager.GENERIC_FAILURE );
372                     }
373                     return null;
374                }
375            }
376        );
377     }
378
379     
380     // return true if log msgs have to be printed on to Syslog
381
private static boolean logToSyslog() {
382          boolean sunOS =
383              System.getProperty( OS_NAME_PROPERTY ).equals( SUN_OS );
384          boolean linuxOS =
385              System.getProperty( OS_NAME_PROPERTY ).equals( LINUX_OS );
386
387          // If it is not SUN OS, then logToSyslog should return false
388
if( !sunOS && !linuxOS ) {
389              return false;
390          }
391          if( syslogLibraryLoadError )
392              return false;
393          LogService logService = getLogService( );
394          if( logService != null ) {
395              return logService.isUseSystemLogging( );
396          }
397          return false;
398      }
399
400
401     // return true if log msgs have to be printed on stderr
402
private static boolean logToStderr() {
403         try {
404         // Check if server was started with "asadmin start-domain --verbose"
405
// This system property is set in PELaunchFilter.
406
if ( verboseMode == null ) {
407         verboseMode = Boolean.FALSE;
408         String JavaDoc verbose = System.getProperty("com.sun.aas.verboseMode");
409         if ( verbose != null && verbose.equals("true") ) {
410             verboseMode = Boolean.TRUE;
411         }
412         }
413         if ( verboseMode.booleanValue() == true ) {
414         return true;
415         }
416
417         // check if log-console / echo-log-messages-to-stderr is true
418
ServerContext sc = ApplicationServer.getServerContext();
419         if (sc == null) {
420         // This can happen before ApplicationServer.onInitialization()
421
// has been called.
422
return false;
423         }
424
425             Config cfg =
426                 ServerBeansFactory.getConfigBean(sc.getConfigContext());
427             return cfg.getLogService().isLogToConsole();
428
429         } catch ( Exception JavaDoc ex ) {
430             new ErrorManager JavaDoc().error(
431                 "Error while geting echo-log-messages-to-stderr attribute of " +
432                 " log-service ", ex, ErrorManager.GENERIC_FAILURE );
433         return false;
434         }
435     }
436
437
438     /**
439      * Given a logger name, this method returns its level as defined
440      * in domain.xml (the app server config file).
441      * _REVISIT_:
442      * 1. Replace multiple if (loggerName) checks with a Hashmap
443      */

444     public static Level JavaDoc getConfiguredLogLevel(String JavaDoc loggerName) {
445         ServerContext sc = ApplicationServer.getServerContext();
446         if (sc == null) {
447             if (loggerName.startsWith(SYNCHRONIZATION)) {
448                 try {
449                     String JavaDoc level = System.getProperty(SYNCHRONIZATION, "INFO");
450                     return Level.parse(level);
451                 } catch (Exception JavaDoc e) {
452                     return Level.INFO;
453                 }
454             } else {
455                 return Level.INFO;
456             }
457         }
458
459         if (loggerName.equals(LogDomains.DPLAUDIT_LOGGER)) {
460             try {
461                 Level JavaDoc level = DeploymentAuditLogHandler.getConfiguredLevel();
462                 return level;
463             } catch (Throwable JavaDoc thr) {
464                 return Level.OFF;
465             }
466         }
467         
468         Level JavaDoc logLevel = null;
469         try {
470             Config cfg =
471                 ServerBeansFactory.getConfigBean(sc.getConfigContext());
472             ModuleLogLevels allModulesLogLevels =
473                 cfg.getLogService().getModuleLogLevels( );
474             // _REVISIT_: Right now ModuleLogLevels element in Log-Service
475
// is optional. If the user doesn't specify any module log levels
476
// then we will use 'INFO' as the default. For 8.1 this should
477
// be a required element.
478
if( allModulesLogLevels == null ) { return Level.INFO; }
479             if( allModulesLogLevels.getRoot( ).equals( "OFF" ) ) {
480                 return Level.OFF;
481             }
482
483             // _REVISIT_: This is a bad way of searching for a loggername match
484
// clean this up after Technology Preview
485
ElementProperty[] elementProperties =
486                 cfg.getLogService().getModuleLogLevels().getElementProperty( );
487
488             if( elementProperties != null ) {
489                 for( int i = 0; i < elementProperties.length; i++ ) {
490                     if( elementProperties[i].getName().equals(loggerName) ) {
491                         return Level.parse( elementProperties[i].getValue());
492                     }
493                 }
494             }
495
496             String JavaDoc logModName = ModuleToLoggerNameMapper.getModuleName(loggerName);
497             if (logModName!=null) {
498                 try {
499                     String JavaDoc val = allModulesLogLevels.getAttributeValue(logModName);
500                     logLevel = Level.parse(val);
501                 } catch (Exception JavaDoc noSuch) { //no such module name,such as "core", in <module-log-levels>
502
}
503         }
504         } catch ( Exception JavaDoc e ) {
505             new ErrorManager JavaDoc().error( "Error In Setting Initial Loglevel", e,
506                 ErrorManager.GENERIC_FAILURE );
507         }
508         return logLevel;
509     }
510
511
512     /**
513      * Here's an oppurtunity to reInitialize the Loggers, if they are
514      * initialized before the admin service started.
515      */

516     public static void reInitializeServerLoggers() {
517         try {
518             FileandSyslogHandler handler=
519                 (FileandSyslogHandler)getFileandSyslogHandler();
520             // If there is a file name specified by the administrator for
521
// Log File, then here's a first oppurtunity to change the
522
// file name because the Log Handles may have been initialized
523
// before the configuration data is completely read.
524
handler.changeFileName( getLogService().getFile() );
525             Long JavaDoc rotationTimeLimitValue = new Long JavaDoc(
526                 getLogService().getLogRotationTimelimitInMinutes().trim() );
527             if( rotationTimeLimitValue.longValue( ) != 0 ) {
528                 // If there is a value specified for the rotation based on
529
// time we set that first, if not then we will fall back to
530
// size based rotation
531
LogRotationTimer.getInstance().startTimer(
532                     new LogRotationTimerTask(
533                         rotationTimeLimitValue.longValue( ) ) );
534                 // Disable the Size Based Rotation if the Time Based
535
// Rotation is set.
536
handler.setLimitForRotation( 0 );
537             } else {
538                 Integer JavaDoc rotationLimitAttrValue = new Integer JavaDoc(
539                     getLogService().getLogRotationLimitInBytes().trim() );
540                 // We set the LogRotation limit here. The rotation limit is the
541
// Threshold for the number of bytes in the log file after which
542
// it will be rotated.
543
handler.setLimitForRotation(
544                     rotationLimitAttrValue.intValue() );
545             }
546   
547             if( listOfUnInitializedLoggers.size() == 0 ) {
548                 return;
549             }
550             Iterator JavaDoc listIterator = listOfUnInitializedLoggers.iterator( );
551             while( listIterator.hasNext( ) ) {
552                 thisInstance.initializeLogger( (Logger JavaDoc) listIterator.next() );
553             }
554         } catch( Exception JavaDoc e ) {
555             new ErrorManager JavaDoc().error(
556                 "Exception caught in reInitializeServerLoggers ",
557                  e, ErrorManager.GENERIC_FAILURE );
558         }
559     }
560 }
561
Popular Tags