KickJava   Java API By Example, From Geeks To Geeks.

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


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

23 package com.sun.enterprise.server.logging;
24
25 import java.util.Map JavaDoc;
26 import java.util.Hashtable JavaDoc;
27 import java.util.Date JavaDoc;
28 import java.util.Properties JavaDoc;
29 import java.util.ArrayList JavaDoc;
30 import java.util.Arrays JavaDoc;
31 import java.util.logging.LogManager JavaDoc;
32 import java.util.logging.LogRecord JavaDoc;
33 import java.util.logging.Logger JavaDoc;
34 import java.util.logging.Level JavaDoc;
35 import java.util.logging.ErrorManager JavaDoc;
36 import java.util.Enumeration JavaDoc;
37 import java.util.LinkedList JavaDoc;
38 import java.util.List JavaDoc;
39 import java.util.Iterator JavaDoc;
40 import java.security.*;
41 import java.io.File JavaDoc;
42
43 import javax.management.Attribute JavaDoc;
44 import javax.management.AttributeList JavaDoc;
45 import javax.management.AttributeNotFoundException JavaDoc;
46 import javax.management.RuntimeOperationsException JavaDoc;
47 import javax.management.DynamicMBean JavaDoc;
48 import javax.management.InvalidAttributeValueException JavaDoc;
49 import javax.management.MBeanException JavaDoc;
50 import javax.management.MBeanInfo JavaDoc;
51 import javax.management.MBeanAttributeInfo JavaDoc;
52 import javax.management.MBeanOperationInfo JavaDoc;
53 import javax.management.MBeanNotificationInfo JavaDoc;
54 import javax.management.MBeanParameterInfo JavaDoc;
55 import javax.management.MBeanServer JavaDoc;
56 import javax.management.NotificationListener JavaDoc;
57 import javax.management.NotificationBroadcasterSupport JavaDoc;
58 import javax.management.ReflectionException JavaDoc;
59 import javax.management.ObjectName JavaDoc;
60 import javax.management.OperationsException JavaDoc;
61
62 import com.sun.enterprise.server.logging.stats.ErrorStatistics;
63 import com.sun.enterprise.server.logging.logviewer.backend.LogFilter;
64 import com.sun.enterprise.server.logging.diagnostics.MessageIdCatalog;
65
66 import com.sun.enterprise.util.StringUtils;
67 import com.sun.enterprise.util.SystemPropertyConstants;
68
69
70 /**
71  * Log MBean can
72  * 1. Fetch the Loggers available in the server
73  * 2. Fetch the log level of a given logger
74  * 3. Dynamically change the log levels of all the avalaible Loggers
75  * 4. Send SEVERE and WARNING Log messages as Alarms to all the interested
76  * parties.
77  *
78  *
79  * @author Hemanth Puttaswamy
80  */

81 public class LogMBean extends NotificationBroadcasterSupport JavaDoc
82     implements DynamicMBean JavaDoc
83 {
84     // Conversion factor to convert minutes to milli seconds, and vice versa.
85
private static final int MINUTES_TO_MILLISECONDS = 60000;
86     
87     private static final String JavaDoc LOGS_DIR = "logs";
88
89     private ObjectName JavaDoc objectName;
90
91     // We can rotate Instance Log and Access Log at the same time using
92
// this LogMBean API. PWC will set it's accessLogRotator implementation
93
private LogRotatorSPI accessLogRotator = null;
94
95     private static final String JavaDoc LOG_MBEAN_DESCRIPTION =
96         " Log MBean can be used for Managinging and Monitoring Logs \n" +
97         " The main features provided by this MBean are .... \n" +
98         " 1. Fetch the Loggers available in the server \n" +
99         " 2. Fetch the log level of a given logger \n" +
100         " 3. Dynamically change the log levels of all the avalaible Loggers \n"+
101         " 4. Send SEVERE and WARNING Log messages as Alarms to all the " +
102         "interested parties ";
103
104     private static final String JavaDoc GET_LOGGER_NAMES = "getLoggerNames";
105
106     private static final String JavaDoc GET_LOGGER_NAMES_DESCRIPTION =
107         " Gets all the Loggers currently running in the System. The returned "+
108         " list is not sorted. ";
109
110     private static final String JavaDoc GET_LOGGER_NAMES_UNDER = "getLoggerNamesUnder";
111
112     private static final String JavaDoc GET_LOGGER_NAMES_UNDER_DESCRIPTION =
113         " Gets all the Loggers under a given logger. The returned list is not "+
114         " sorted. ";
115
116     private static final String JavaDoc GET_LOG_LEVEL = "getLogLevel";
117
118     private static final String JavaDoc GET_LOG_LEVEL_DESCRIPTION =
119         " Gets the current Log Level of the given Logger. The 8 Possible " +
120         " values are 1.SEVERE 2.WARNING 3.INFO 4.CONFIG 5.FINE 6.FINER " +
121         " 7.FINEST 8. Null";
122
123     private static final String JavaDoc SET_LOG_LEVEL = "setLogLevel";
124
125     private static final String JavaDoc SET_LOG_LEVEL_DESCRIPTION =
126          " Sets the log level of the given logger to the request level. An " +
127          " IllegalArgument Exception will be raised if the level is not one " +
128          " of the following 8 values. 1.SEVERE 2.WARNING 3.INFO 4.CONFIG " +
129          " 5.FINE 6.FINER 7.FINEST 8.OFF";
130
131     private static final String JavaDoc SET_LOG_LEVEL_FOR_MODULE =
132         "setLogLevelForModule";
133
134     private static final String JavaDoc SET_LOG_LEVEL_FOR_MODULE_DESCRIPTION =
135          " Sets the log level for a given module .\n" +
136          " The Modules are admin, classloader, cmp-container, configuration "+
137          " , connector, corba, deployment, ejb-container, javamail, jaxr, " +
138          " jaxrpc, mdb-container, naming, saaj, security, server, " +
139          " transaction, verifier, web-container, core " +
140          " IllegalArgument Exception will be raised if the level is not one " +
141          " of the following 8 values. 1.SEVERE 2.WARNING 3.INFO 4.CONFIG " +
142          " 5.FINE 6.FINER 7.FINEST 8.OFF";
143
144     private static final String JavaDoc GET_LOG_RECORD_USING_QUERY =
145         "getLogRecordsUsingQuery";
146
147     private static final String JavaDoc GET_LOG_RECORD_USING_QUERY_DESCRIPTION =
148          " This method returns the Log Records from the server.log file \n"+
149          " based on the query passed....." ;
150
151     private static final String JavaDoc GET_ARCHIVED_LOG_FILES =
152         "getArchivedLogfiles";
153
154     private static final String JavaDoc GET_ARCHIVED_LOG_FILES_DESCRIPTION =
155         " This method returns a list of Archived Log files currently " +
156         " available in the domain/log directory";
157
158     private static final String JavaDoc GET_DIAGNOSTIC_CAUSES_FOR_MESSAGEID =
159         "getDiagnosticCausesForMessageId";
160
161     private static final String JavaDoc
162         GET_DIAGNOSTIC_CAUSES_FOR_MESSAGEID_DESCRIPTION =
163         " This method returns the Possible Causes for an Error Code specified";
164
165     private static final String JavaDoc GET_DIAGNOSTIC_CHECKS_FOR_MESSAGEID =
166         "getDiagnosticChecksForMessageId";
167
168     private static final String JavaDoc
169         GET_DIAGNOSTIC_CHECKS_FOR_MESSAGEID_DESCRIPTION =
170         " This method returns the Diagnostic Checks for an Error Code " +
171         "specified";
172
173     private static final String JavaDoc GET_DIAGNOSTIC_URI_FOR_MESSAGEID =
174         "getDiagnosticURIForMessageId";
175
176     private static final String JavaDoc GET_DIAGNOSTIC_URI_FOR_MESSAGEID_DESCRIPTION =
177         " This method returns the URI to locate the latest Diagnostic info " +
178         " on SUN's Docs Website";
179
180     private static final String JavaDoc ROTATE_NOW =
181         "rotateNow";
182
183     private static final String JavaDoc ROTATE_NOW_DESCRIPTION =
184         " Log file will be rotated when this method is called, This will " +
185         " override the other two rotation mechanisms of rotation based on " +
186         " log file size or timer.\n The timer will be restarted to schedule " +
187         " next rotation if it is specified.";
188
189     private static final String JavaDoc GET_LOGFILES_DIRECTORY = "getLogFilesDirectory";
190     
191     private static final String JavaDoc GET_ERROR_DISTRIBUTION = "getErrorDistribution";
192     private static final String JavaDoc GET_ERROR_DISTRIBUTION_DESCRIPTION = "";
193
194     private static final String JavaDoc GETLOGNAMES4LOGMODULE = "getLognames4LogModule";
195     private static final String JavaDoc GETLOGNAMES4LOGMODULE_DESCRIPTION =
196          " This method returns the predefined logger names for the module name " +
197          " passed in.";
198
199     private static final String JavaDoc GET_LOGFILES_DIRECTORY_DESCRIPTION =
200         " This method returns the LogFiles Directory to help locate " +
201         " Logfiles in the FileSystem...";
202
203     private static final String JavaDoc NOTIFICATION_SEVERE_ALARM =
204         "SevereLogMessages";
205
206     private static final String JavaDoc NOTIFICATION_SEVERE_ALARM_DESCRIPTION =
207         " All Logged Messages whose Log Level is SEVERE will be notified " +
208         " to all the subscribed listeners..." ;
209
210     private static final String JavaDoc NOTIFICATION_WARNING_ALARM =
211         "WarningLogMessages";
212
213     private static final String JavaDoc NOTIFICATION_WARNING_ALARM_DESCRIPTION =
214         " All Logged Messages whose Log Level is WARNING will be notified " +
215         " to all the subscribed listeners..." ;
216
217     private static final String JavaDoc ATTR_LOGGER_NAMES = "LoggerNames";
218
219     private static final String JavaDoc ATTR_LOGGER_NAMES_DESCRIPTION =
220         "All the Loggers currently running in the System. The list " +
221         " is not sorted.";
222     
223     private static final String JavaDoc ATTR_LOGFILES_DIRECTORY = "LogFilesDirectory";
224
225     private static final String JavaDoc ATTR_LOGFILES_DIRECTORY_DESCRIPTION =
226         "The LogFiles Directory to help locate " +
227         "Logfiles in the FileSystem...";
228         
229     private static final String JavaDoc ATTR_ARCHIVED_LOG_FILES = "ArchivedLogfiles";
230
231     private static final String JavaDoc ATTR_ARCHIVED_LOG_FILES_DESCRIPTION =
232         "A list of Archived Log files currently " +
233         "available in the domain/log directory";
234     
235     private static final String JavaDoc ATTR_ERROR_INFORMATION = "ErrorInformation";
236     private static final String JavaDoc ATTR_ERROR_INFORMATION_DESCRIPTION =
237         "ErrorInformation";
238         
239     private static final String JavaDoc ATTR_KEEP_ERROR_STATISTICS_FOR_HOURS =
240         "KeepErrorStatisticsForHours";
241     private static final String JavaDoc
242             ATTR_KEEP_ERROR_STATISTICS_FOR_HOURS_DESCRIPTION =
243         "The number of hours for which error statistics are maintained.";
244     
245     private static final String JavaDoc ATTR_KEEP_ERROR_STATISTICS_FOR_INTERVALS =
246         "KeepErrorStatisticsForIntervals";
247     private static final String JavaDoc
248             ATTR_KEEP_ERROR_STATISTICS_FOR_INTERVALS_DESCRIPTION =
249         "Number of intervals for which error statistics are maintained.";
250     
251     private static final String JavaDoc ATTR_ERROR_STATISTICS_INTERVAL_DURATION =
252         "ErrorStatisticsIntervalDuration";
253     private static final String JavaDoc
254             ATTR_ERROR_STATISTICS_INTERVAL_DURATION_DESCRIPTION =
255         "Duration of each interval for which error statistics are retained.";
256     
257     private static MBeanOperationInfo JavaDoc[] operationInfoArray =
258         new MBeanOperationInfo JavaDoc[11];
259     
260     private static MBeanAttributeInfo JavaDoc[] attributeInfoArray =
261         new MBeanAttributeInfo JavaDoc[7];
262     
263     /**
264      * Info on this MBean
265      */

266     private static MBeanInfo JavaDoc mBeanInfo;
267
268     private MBeanServer JavaDoc mbeanServer = null;
269
270     private static LogMBean mbeanInstance = null;
271
272     /**
273      * A Singleton factory method.
274      */

275     public synchronized static LogMBean getInstance( ) {
276         if( mbeanInstance == null ) {
277             mbeanInstance = new LogMBean();
278             mbeanInstance.initialize( );
279         }
280         return mbeanInstance;
281     }
282
283     /**
284      * A private default constructor to ensure Singleton pattern for LogMBean.
285      */

286     private LogMBean( ) { }
287    
288
289     public void initialize( ) {
290         
291         try {
292             if ( attributeInfoArray.length != 7 ) {
293                 throw new RuntimeException JavaDoc(
294                     "attributeInfoArray array is the wrong length" );
295             }
296
297             attributeInfoArray[0] = new MBeanAttributeInfo JavaDoc(
298                     ATTR_LOGGER_NAMES, "java.util.List",
299                     ATTR_LOGGER_NAMES_DESCRIPTION, true, false, false);
300             
301             attributeInfoArray[1] = new MBeanAttributeInfo JavaDoc(
302                 ATTR_LOGFILES_DIRECTORY, "String",
303                 ATTR_LOGFILES_DIRECTORY_DESCRIPTION, true, false, false);
304             
305             attributeInfoArray[2] = new MBeanAttributeInfo JavaDoc(
306                 ATTR_ARCHIVED_LOG_FILES, "[Ljava.lang.String;",
307                 ATTR_ARCHIVED_LOG_FILES_DESCRIPTION, true, false, false);
308             
309             attributeInfoArray[3] = new MBeanAttributeInfo JavaDoc(
310                 ATTR_ERROR_INFORMATION, List JavaDoc.class.getName(),
311                 ATTR_ERROR_INFORMATION_DESCRIPTION, true, false, false);
312             
313             attributeInfoArray[4] = new MBeanAttributeInfo JavaDoc(
314                 ATTR_KEEP_ERROR_STATISTICS_FOR_HOURS, int.class.getName(),
315                 ATTR_KEEP_ERROR_STATISTICS_FOR_HOURS_DESCRIPTION,
316                 true, true, false);
317             
318             attributeInfoArray[5] = new MBeanAttributeInfo JavaDoc(
319                 ATTR_KEEP_ERROR_STATISTICS_FOR_INTERVALS, int.class.getName(),
320                 ATTR_KEEP_ERROR_STATISTICS_FOR_INTERVALS_DESCRIPTION,
321                 true, true, false);
322                 
323             attributeInfoArray[6] = new MBeanAttributeInfo JavaDoc(
324                 ATTR_ERROR_STATISTICS_INTERVAL_DURATION, long.class.getName(),
325                 ATTR_ERROR_STATISTICS_INTERVAL_DURATION_DESCRIPTION,
326                 true, true, false);
327                 
328             MBeanParameterInfo JavaDoc[] loggerNameParam =
329                 {new MBeanParameterInfo JavaDoc("LoggerName", "String", "Logger Name")};
330             operationInfoArray[0] = new MBeanOperationInfo JavaDoc(
331                 GET_LOGGER_NAMES_UNDER, GET_LOGGER_NAMES_UNDER_DESCRIPTION,
332                 loggerNameParam, "java.util.List", MBeanOperationInfo.ACTION);
333
334             operationInfoArray[1] = new MBeanOperationInfo JavaDoc(GET_LOG_LEVEL,
335                 GET_LOG_LEVEL_DESCRIPTION, loggerNameParam, "String",
336                 MBeanOperationInfo.ACTION);
337
338             MBeanParameterInfo JavaDoc[] loggerNameAndLevelParam =
339                 {new MBeanParameterInfo JavaDoc("LoggerName", "String", "Logger Name"),
340                  new MBeanParameterInfo JavaDoc("LogLevel", "String", "Logger Level") };
341             operationInfoArray[2] = new MBeanOperationInfo JavaDoc(SET_LOG_LEVEL,
342                 SET_LOG_LEVEL_DESCRIPTION, loggerNameAndLevelParam, "void",
343                 MBeanOperationInfo.ACTION);
344
345             operationInfoArray[3] = new MBeanOperationInfo JavaDoc(
346                 SET_LOG_LEVEL_FOR_MODULE, SET_LOG_LEVEL_FOR_MODULE_DESCRIPTION,
347                 loggerNameAndLevelParam, "void", MBeanOperationInfo.ACTION);
348
349             MBeanParameterInfo JavaDoc[] logviewerQueryParams =
350                 {new MBeanParameterInfo JavaDoc("FileName", "String",
351                      " If Filename is specified then it will be used to " +
352                      " run the query. If the user specifies null for this " +
353                      " argument then the current server.log file will be " +
354                      " used to run the query. This argument is specifed to " +
355                      " typically run query on Archived Log File "),
356                  new MBeanParameterInfo JavaDoc("FromRecord", "Long",
357                      "The location within the LogFile"),
358                  new MBeanParameterInfo JavaDoc("next", "Boolean",
359                      "True to get the next set of results and False to get " +
360                      " the previous results "),
361                  new MBeanParameterInfo JavaDoc("forward", "Boolean",
362                      "True to search forward through the log file " ),
363                  new MBeanParameterInfo JavaDoc("requestedCount", "Integer",
364                      "Number of desired records" ),
365                  new MBeanParameterInfo JavaDoc("fromDate", "java.util.Date",
366                      " The lower bound date " ),
367                  new MBeanParameterInfo JavaDoc("toDate", "java.util.Date",
368                      " The upper bound date " ),
369                  new MBeanParameterInfo JavaDoc("logLevel", "String",
370                      " The minimum log level to display " ),
371                  new MBeanParameterInfo JavaDoc("onlyLevel", "Boolean",
372                      " True to only display messsage for \"logLevel\""),
373                  new MBeanParameterInfo JavaDoc("listOfModules", "java.util.List",
374                      " List Of Modules and Logger Names To Match" ),
375                  new MBeanParameterInfo JavaDoc("nameValueMap", "java.util.Properties",
376                      " List Of Name Value Pairs to match " )
377                  };
378             operationInfoArray[4] = new MBeanOperationInfo JavaDoc(
379                 GET_LOG_RECORD_USING_QUERY,
380                 GET_LOG_RECORD_USING_QUERY_DESCRIPTION,
381                 logviewerQueryParams, "javax.management.AttributeList",
382                 MBeanOperationInfo.ACTION);
383
384             MBeanParameterInfo JavaDoc[] diagnosticsParameter =
385                 {new MBeanParameterInfo JavaDoc("messageId", "String", "Error Code") };
386             operationInfoArray[5] = new MBeanOperationInfo JavaDoc(
387                 GET_DIAGNOSTIC_CAUSES_FOR_MESSAGEID,
388                 GET_DIAGNOSTIC_CAUSES_FOR_MESSAGEID_DESCRIPTION,
389                 diagnosticsParameter, "java.util.ArrayList",
390                 MBeanOperationInfo.ACTION);
391
392             operationInfoArray[6] = new MBeanOperationInfo JavaDoc(
393                 GET_DIAGNOSTIC_CHECKS_FOR_MESSAGEID,
394                 GET_DIAGNOSTIC_CHECKS_FOR_MESSAGEID_DESCRIPTION,
395                 diagnosticsParameter, "java.util.ArrayList",
396                 MBeanOperationInfo.ACTION);
397
398             operationInfoArray[7] = new MBeanOperationInfo JavaDoc(
399                 GET_DIAGNOSTIC_URI_FOR_MESSAGEID,
400                 GET_DIAGNOSTIC_URI_FOR_MESSAGEID_DESCRIPTION,
401                 diagnosticsParameter, "String", MBeanOperationInfo.ACTION);
402
403             operationInfoArray[8] = new MBeanOperationInfo JavaDoc(
404                 ROTATE_NOW, ROTATE_NOW_DESCRIPTION,
405                 null, "void", MBeanOperationInfo.ACTION);
406
407
408             final MBeanParameterInfo JavaDoc[] getErrorDistributionParams =
409             {
410                 new MBeanParameterInfo JavaDoc("name", "long","time stamp"),
411                 new MBeanParameterInfo JavaDoc("name", Level JavaDoc.class.getName(), "log level")
412             };
413                      
414             operationInfoArray[9] = new MBeanOperationInfo JavaDoc(
415                 GET_ERROR_DISTRIBUTION, GET_ERROR_DISTRIBUTION_DESCRIPTION,
416                 getErrorDistributionParams, List JavaDoc.class.getName(), MBeanOperationInfo.INFO);
417
418             MBeanParameterInfo JavaDoc[] moduleNameParam =
419                 {new MBeanParameterInfo JavaDoc("ModuleName", "String", "Module Name")};
420             operationInfoArray[10] = new MBeanOperationInfo JavaDoc(
421                 GETLOGNAMES4LOGMODULE,
422                 GETLOGNAMES4LOGMODULE_DESCRIPTION,
423                 moduleNameParam, "java.util.List", MBeanOperationInfo.ACTION);
424
425             String JavaDoc[] alarmTypes = {NOTIFICATION_SEVERE_ALARM,
426                  NOTIFICATION_WARNING_ALARM};
427             MBeanNotificationInfo JavaDoc[] notificationInfo =
428                 {new MBeanNotificationInfo JavaDoc( alarmTypes, "Alarms",
429                     "Severe and Warning Log Messages will be notified ") };
430                     
431             mBeanInfo = new MBeanInfo JavaDoc("LogMBean", LOG_MBEAN_DESCRIPTION,
432                 attributeInfoArray, null, operationInfoArray,
433                 notificationInfo);
434
435             // Now Try to register the LogMBean
436
//new RegisterLogMBean( this ).start( );
437

438         } catch( Exception JavaDoc e ) {
439             new ErrorManager JavaDoc().error(
440                 "Error in LogMBean Initialization", e,
441                 ErrorManager.GENERIC_FAILURE );
442         }
443     }
444
445
446
447     public Object JavaDoc invoke(String JavaDoc operationName, Object JavaDoc[] params,
448         String JavaDoc[] signature) throws MBeanException JavaDoc, ReflectionException JavaDoc
449     {
450         if( operationName == null || operationName.equals("")) {
451             throw new RuntimeOperationsException JavaDoc(
452                 new IllegalArgumentException JavaDoc( "MBean.invoke operation name is "+
453                     " null " ) );
454         }
455         AttributeList JavaDoc resultList = new AttributeList JavaDoc();
456         if( operationName.equals( GET_LOGGER_NAMES ) ) {
457             return getLoggerNames( );
458         } else if( operationName.equals( GET_LOGGER_NAMES_UNDER ) ) {
459             String JavaDoc loggerName = (String JavaDoc) params[0];
460             return getLoggerNamesUnder( loggerName );
461         } else if( operationName.equals( GETLOGNAMES4LOGMODULE ) ) {
462             String JavaDoc module = (String JavaDoc) params[0];
463             return getLognames4LogModule(module);
464         } else if( operationName.equals( GET_LOG_LEVEL ) ) {
465             String JavaDoc loggerName = (String JavaDoc) params[0];
466             return getLogLevel( loggerName );
467         } else if( operationName.equals( SET_LOG_LEVEL ) ) {
468             String JavaDoc loggerName = (String JavaDoc) params[0];
469             String JavaDoc loglevel = (String JavaDoc) params[1];
470             setLogLevel( loggerName, loglevel );
471         } else if( operationName.equals( SET_LOG_LEVEL_FOR_MODULE ) ) {
472             String JavaDoc module = (String JavaDoc) params[0];
473             String JavaDoc loglevel = (String JavaDoc) params[1];
474             setLogLevel( module, loglevel );
475         } else if( operationName.equals( GET_LOG_RECORD_USING_QUERY) ) {
476             String JavaDoc fileName = (String JavaDoc) params[0];
477             Long JavaDoc fromRecord = (Long JavaDoc) params[1];
478             Boolean JavaDoc next = (Boolean JavaDoc) params[2];
479             Boolean JavaDoc forward = (Boolean JavaDoc) params[3];
480             Integer JavaDoc requestedCount = (Integer JavaDoc) params[4];
481             Date JavaDoc fromDate = (Date JavaDoc) params[5];
482             Date JavaDoc toDate = (Date JavaDoc) params[6];
483             String JavaDoc logLevel = (String JavaDoc) params[7];
484             Boolean JavaDoc onlyLevel = (Boolean JavaDoc) params[8];
485             List JavaDoc listOfModules = (java.util.List JavaDoc) params[9];
486             java.util.Properties JavaDoc nvMap = (java.util.Properties JavaDoc) params[10];
487             return getLogRecordsUsingQuery( fileName, fromRecord, next, forward,
488                 requestedCount, fromDate, toDate, logLevel, onlyLevel,
489                 listOfModules, nvMap );
490         } else if( operationName.equals( GET_ARCHIVED_LOG_FILES ) ) {
491             return getArchivedLogFiles( );
492         } else if( operationName.equals( GET_DIAGNOSTIC_CAUSES_FOR_MESSAGEID )){
493             String JavaDoc messageId = (String JavaDoc) params[0];
494             return
495                 MessageIdCatalog.getInstance().getDiagnosticCausesForMessageId(
496                     messageId );
497         } else if( operationName.equals( GET_DIAGNOSTIC_CHECKS_FOR_MESSAGEID )){
498             String JavaDoc messageId = (String JavaDoc) params[0];
499             return
500                 MessageIdCatalog.getInstance().getDiagnosticChecksForMessageId(
501                     messageId );
502         } else if( operationName.equals( GET_DIAGNOSTIC_URI_FOR_MESSAGEID )){
503             String JavaDoc messageId = (String JavaDoc) params[0];
504             return
505                 MessageIdCatalog.getInstance().getDiagnosticURIForMessageId(
506                     messageId );
507         } else if( operationName.equals( ROTATE_NOW ) ) {
508             this.rotateNow( );
509         } else if( operationName.equals( GET_LOGFILES_DIRECTORY ) ) {
510             return this.getLogFilesDirectory( );
511         } else if( operationName.equals( GET_ERROR_DISTRIBUTION ) ) {
512             return this.getErrorDistribution( (Long JavaDoc)params[0], (Level JavaDoc)params[1] );
513         } else {
514             throw new IllegalArgumentException JavaDoc(
515                 "Requested operation " + operationName + " does not exist..." );
516         }
517         return resultList;
518     }
519      
520
521    /**
522      * check if logger already existes
523      */

524     public boolean findLogger(String JavaDoc loggerName ) {
525         Enumeration JavaDoc allLoggers = LogManager.getLogManager().getLoggerNames( );
526         while( allLoggers.hasMoreElements( ) ) {
527             String JavaDoc name = (String JavaDoc)allLoggers.nextElement();
528             if (loggerName.equals(name))
529                 return true;
530         }
531         return false;
532     }
533
534     
535     /**
536      * Gets all the Loggers currently running in the System. The returned
537      * list is not sorted.
538      */

539     public List JavaDoc getLoggerNames( ) {
540         LinkedList JavaDoc loggerNamesList = new LinkedList JavaDoc( );
541         Enumeration JavaDoc allLoggers = LogManager.getLogManager().getLoggerNames( );
542         while( allLoggers.hasMoreElements( ) ) {
543             loggerNamesList.add(allLoggers.nextElement( ));
544         }
545         return loggerNamesList;
546     }
547
548     /**
549      * Gets all the Loggers under a given logger. The returned list is not
550      * sorted.
551      */

552     public List JavaDoc getLoggerNamesUnder( String JavaDoc loggerName ) {
553         LinkedList JavaDoc filteredList = new LinkedList JavaDoc( );
554         Iterator JavaDoc allLoggersIterator = getLoggerNames( ).iterator( );
555         while( allLoggersIterator.hasNext( ) ) {
556             String JavaDoc t = (String JavaDoc) allLoggersIterator.next( );
557             if( t.startsWith( loggerName ) ) {
558                 filteredList.add( t );
559             }
560         }
561         return filteredList;
562     }
563
564
565     /**
566      * Gets the current Log Level of the given Logger. The 8 Possible values
567      * are
568      * 1.SEVERE 2.WARNING 3.INFO 4.CONFIG 5.FINE 6.FINER 7.FINEST 8. Null
569      */

570     public String JavaDoc getLogLevel( String JavaDoc loggerName ) {
571         String JavaDoc logLevelInString = null;
572         Logger JavaDoc logger = Logger.getLogger( loggerName );
573         if( logger == null ) {
574              throw new RuntimeException JavaDoc( " Logger " + loggerName +
575                  " does not exist" );
576         }
577         Level JavaDoc level = logger.getLevel( );
578         boolean foundParentLevel = false;
579         if( level == null ) {
580             while( !foundParentLevel ) {
581                 logger = logger.getParent();
582                 if ( logger == null ){
583                     break;
584                 }
585                 level = logger.getLevel( );
586                 if( level != null ) {
587                     foundParentLevel = true;
588                 }
589             }
590         }
591         if( level != null ) {
592             logLevelInString = level.toString();
593         }
594         return logLevelInString;
595     }
596
597     /**
598      * Sets the log level of the given logger to the request level. An
599      * Exception will be raised if the level is not one of the following 8
600      * values.
601      * 1.SEVERE 2.WARNING 3.INFO 4.CONFIG 5.FINE 6.FINER 7.FINEST 8.OFF
602      *
603      * JDK's java.util.logging.Level.parse will throw IllegalArgument exception
604      * if a wrong value is used for the Level.
605      *
606      * Apparently there seems to be a problem in propogating LogLevel from
607      * parent to child loggers in JDK. So, using this internal method to
608      * set the level for all the individual loggers...
609      */

610     public void setLogLevel( String JavaDoc loggerName, String JavaDoc level ) {
611         internalSetLogLevel(loggerName,Level.parse(level) );
612      /* Level logLevel = Level.parse( level );
613         // NOTE: Don't have to check for listIterator being null, because
614         // even if a wrong logger name is used, a null list will be returned.
615         Iterator listIterator = getLoggerNamesUnder( loggerName ).iterator();
616         while ( listIterator.hasNext( ) ) {
617             internalSetLogLevel( (String) listIterator.next(), logLevel );
618         }
619       */

620     }
621
622     /**
623      * Sets the log level for the given module to the request level. An
624      * Exception will be raised if the level is not one of the following 8
625      * values.
626      * 1.SEVERE 2.WARNING 3.INFO 4.CONFIG 5.FINE 6.FINER 7.FINEST 8.OFF
627      */

628     public void setLogLevelForModule( String JavaDoc module, String JavaDoc level ) {
629         String JavaDoc[] loggerNames = ModuleToLoggerNameMapper.getLoggerNames( module );
630         for (int i=0;loggerNames!=null&&i<loggerNames.length;i++) {
631             setLogLevel(loggerNames[i], level );
632         }
633     }
634
635     /**
636      */

637     private void internalSetLogLevel( final String JavaDoc loggerName,
638         final Level JavaDoc level )
639     {
640         AccessController.doPrivileged(new PrivilegedAction() {
641             public Object JavaDoc run() {
642                 Logger.getLogger( loggerName ).setLevel(level);
643                 return null;
644             }});
645     }
646
647     /**
648      * The public method that Log Viewer Front End will be calling on.
649      * The query will be run on records starting from the fromRecord.
650      * If any of the elements for the query is null, then that element will
651      * not be used for the query. If the user is interested in viewing only
652      * records whose Log Level is SEVERE and WARNING, then the query would
653      * look like:
654      *
655      * fromDate = null, toDate = null, logLevel = WARNING, onlyLevel = false,
656      * listOfModules = null, nameValueMap = null.
657      *
658      * @param fromRecord The location within the LogFile
659      * @param next True to get the next set of results, false to
660      * get the previous set
661      * @param forward True to search forward through the log file
662      * @param requestedCount The # of desired return values
663      * @param fromDate The lower bound date
664      * @param toDate The upper bound date
665      * @param logLevel The minimum log level to display
666      * @param onlyLevel True to only display messsage for "logLevel"
667      * @param listOfModules List of modules to match
668      * @param nameValueMap NVP's to match
669      *
670      * @return
671      */

672     public AttributeList JavaDoc getLogRecordsUsingQuery(
673         String JavaDoc logFilename, Long JavaDoc fromRecord, Boolean JavaDoc next, Boolean JavaDoc forward,
674         Integer JavaDoc requestedCount, Date JavaDoc fromDate, Date JavaDoc toDate,
675         String JavaDoc logLevel, Boolean JavaDoc onlyLevel, List JavaDoc listOfModules,
676         Properties JavaDoc nameValueMap)
677     {
678         return LogFilter.getLogRecordsUsingQuery(logFilename, fromRecord, next,
679             forward, requestedCount, fromDate, toDate, logLevel, onlyLevel,
680             listOfModules, nameValueMap);
681     }
682
683     /**
684      * Gets all Archived log Files in the current Server instance.
685      *
686      * @return An Array of all Archived Log filenames.
687      */

688     public String JavaDoc[] getArchivedLogFiles( ) {
689         String JavaDoc[] archivedLogFiles = new String JavaDoc[0];
690         try {
691             String JavaDoc instDir = System.getProperty(
692                 SystemPropertyConstants.INSTANCE_ROOT_PROPERTY );
693             String JavaDoc[] names = { instDir, LOGS_DIR };
694             String JavaDoc logDir = StringUtils.makeFilePath( names, false );
695             File JavaDoc file = new File JavaDoc( logDir );
696             archivedLogFiles = file.list( new FilenameFilterImpl( ) );
697             // Get the current log file name and see if we have that on the list already.
698
// This is a corner case where user would not have given ".log" extension to
699
// log file and the FileNameFilter has filtered it.
700
// Also note that we are interested in getting just the filename, not the
701
// completepath
702
String JavaDoc currentFileName = new File JavaDoc(
703                 ServerLogManager.getLogService( ).getFile( )).getName( );
704             boolean foundCurrentFile = false;
705             int i = 0;
706             for( i = 0; i < archivedLogFiles.length; i++ ) {
707                 if( currentFileName.equals( archivedLogFiles[i] ) ) {
708                     foundCurrentFile = true;
709                     break;
710                 }
711             }
712             if( !foundCurrentFile ) {
713                 // If we don't have the currentLogFile in the list, then it must be
714
// because it doesn't use .log extension. Now, build a new list with
715
// the current log file name and the list returned from file.list( )
716
String JavaDoc[] newArchivedLogFiles = new String JavaDoc[ archivedLogFiles.length + 1 ];
717                 newArchivedLogFiles[0] = currentFileName;
718                 for( i = 1; i < (archivedLogFiles.length + 1); i++ ) {
719                     newArchivedLogFiles[i] = archivedLogFiles[i - 1];
720                 }
721                 return newArchivedLogFiles;
722             }
723         } catch( Exception JavaDoc e ) {
724             // This will go into System.err Logger. As this failure is in
725
// the log module, we will stick with System.err here.
726
System.err.println(
727                 "Exception in LogMBean.getArchivedLogFiles.." + e );
728             throw new RuntimeException JavaDoc(
729                 "Exception in LogMBean.getArchivedLogFiles.." + e );
730         }
731         return archivedLogFiles;
732     }
733
734     /**
735      * This method rotates the server.log and access log file at this instant.
736      */

737     public void rotateNow( ) {
738         FileandSyslogHandler.getInstance( ).requestRotation( );
739         // Rotate Access Log also
740
this.rotateAccessLog( );
741     }
742
743     /**
744      * This method rotates the accessLog
745      */

746     public void rotateAccessLog( ) {
747         if( accessLogRotator != null ) {
748             accessLogRotator.rotate( );
749        }
750     }
751
752     /**
753      * Setter provided to set the AccessLog Rotator.
754      */

755     public void setAccessLogRotator( LogRotatorSPI logRotator ) {
756         accessLogRotator = logRotator;
757     }
758
759     /**
760      * This method returns the directory where log files are located.
761      */

762     public String JavaDoc getLogFilesDirectory( ) {
763         try {
764             String JavaDoc fileName =
765                 FileandSyslogHandler.getInstance( ).getAbsoluteLogFileName( );
766             return new File JavaDoc( fileName ).getParent( );
767         } catch( Exception JavaDoc e ) {
768             System.err.println( "Exception in LogMBean.getLogFilesDirectory()"
769                 + e );
770         }
771         return null;
772     }
773
774
775     /**
776      * This is an internal SPI to change the file name for FileandSyslogHandler
777      */

778     public void changeLogFileName( String JavaDoc fileName ) {
779         FileandSyslogHandler.getInstance().changeFileName( fileName );
780     }
781
782
783     /**
784      * Provides the exposed attributes and actions of the monitoring MBean using
785      * an MBeanInfo object.
786      * @return An instance of MBeanInfo with all attributes and actions exposed
787      * by this monitoring MBean.
788      */

789     public MBeanInfo JavaDoc getMBeanInfo() {
790         return mBeanInfo;
791     }
792
793
794     /**
795      * Obtains the value of a specific monitored attribute. The LogMBean does
796      * not have any attribute, this method always throws
797      * AttributeNotFoundException when specified attribute is not null.
798      *
799      * @param attribute The name of the attribute to be retrieved
800      * @return The value of the attribute retrieved.
801      * @throws AttributeNotFoundException if attribute name is not valid
802      */

803     public Object JavaDoc getAttribute(String JavaDoc attribute)
804         throws AttributeNotFoundException JavaDoc
805     {
806         Object JavaDoc result = null;
807         
808         if ( ATTR_LOGGER_NAMES.equals( attribute ) ) {
809             result = getLoggerNames();
810         }
811         else if ( ATTR_LOGFILES_DIRECTORY.equals( attribute ) ) {
812             result = getLogFilesDirectory();
813         }
814         else if ( ATTR_ARCHIVED_LOG_FILES.equals( attribute ) ) {
815             result = getArchivedLogFiles();
816         }
817         else if ( ATTR_ERROR_INFORMATION.equals( attribute ) ) {
818             result = getErrorInformation();
819         }
820         else if ( ATTR_KEEP_ERROR_STATISTICS_FOR_INTERVALS.equals( attribute ) ) {
821             result = getKeepErrorStatisticsForIntervals();
822         }
823         else if ( ATTR_ERROR_STATISTICS_INTERVAL_DURATION.equals( attribute ) ) {
824             result = getErrorStatisticsIntervalMinutes();
825         }
826         else if ( ATTR_KEEP_ERROR_STATISTICS_FOR_HOURS.equals( attribute ) ) {
827             result = getKeepErrorStatisticsForHours();
828         }
829         else {
830             if (attribute != null) {
831                 throw new AttributeNotFoundException JavaDoc("Attribute " + attribute
832                         + " not found in LogMBean. There are no attributes.");
833             } else {
834                 throw new IllegalArgumentException JavaDoc("Attribute Name is null");
835             }
836         }
837         
838         return result;
839     }
840
841
842     /**
843      * Get the values of several attributes of the monitoring MBean. LogMBean
844      * does not have any attributes, so this method will always return an
845      * empty attribute list.
846      *
847      * @param attributes A list of the attributes to be retrieved.
848      * @return The list of attributes retrieved.
849      */

850     public AttributeList JavaDoc getAttributes( String JavaDoc[] attributeNames )
851     {
852         final AttributeList JavaDoc attrs = new AttributeList JavaDoc();
853         
854         for( final String JavaDoc name : attributeNames )
855         {
856             try
857             {
858                 final Object JavaDoc value = getAttribute( name );
859                 attrs.add( new Attribute JavaDoc( name, value ) );
860             }
861             catch( Exception JavaDoc e )
862             {
863                 // ignore, per JMX spec
864
}
865         }
866         
867         return attrs;
868     }
869
870     /**
871      * Set the values of several attributes. As LogMBean does not have any
872      * attributes, the method will always return empty attribute list.
873      * @param list A list of attributes. The identification of the attributes
874      * to be set and the values that they are to be set to.
875      * @return the list of attributes that were set, with their new values.
876      */

877     public AttributeList JavaDoc setAttributes( final AttributeList JavaDoc list ) {
878         final AttributeList JavaDoc result = new AttributeList JavaDoc();
879         
880         for( final Object JavaDoc o : list ) {
881             final Attribute JavaDoc attr = (Attribute JavaDoc)o;
882             
883             try {
884                 setAttribute( attr );
885                 result.add( attr );
886             }
887             catch( Throwable JavaDoc t ) {
888                 // OK, per semantics of setAttributes();
889
}
890         }
891         
892         return result;
893     }
894
895     /**
896      * Set the value of specified attribute. This method throws exception as
897      * LogMBean does not have any attributes.
898      */

899     public void setAttribute( final Attribute JavaDoc attribute )
900             throws AttributeNotFoundException JavaDoc {
901         final String JavaDoc name = attribute.getName();
902         final Object JavaDoc value = attribute.getValue();
903         
904         if ( ATTR_KEEP_ERROR_STATISTICS_FOR_INTERVALS.equals( name ) ) {
905             setKeepErrorStatisticsForIntervals( (Integer JavaDoc)value );
906         }
907         else if ( ATTR_ERROR_STATISTICS_INTERVAL_DURATION.equals( name ) ) {
908             setErrorStatisticsIntervalMinutes( (Long JavaDoc)value );
909         }
910         else if ( ATTR_KEEP_ERROR_STATISTICS_FOR_HOURS.equals( name ) ) {
911             setKeepErrorStatisticsForHours( (Integer JavaDoc)value );
912         }
913         else {
914             throw new AttributeNotFoundException JavaDoc( name );
915         }
916     }
917
918     private void raiseAlarm(String JavaDoc type, LogRecord JavaDoc record) {
919         LogAlarm logAlarm = new LogAlarm( type, this, record );
920         sendNotification( logAlarm );
921     }
922
923     /**
924      * This method raises a WARNING type Alarm.
925      */

926     void raiseWarningAlarm(LogRecord JavaDoc record) {
927         raiseAlarm( NOTIFICATION_WARNING_ALARM, record );
928     }
929
930     /**
931      * This method raises a SEVERE type Alarm.
932      */

933     void raiseSevereAlarm(LogRecord JavaDoc record) {
934         raiseAlarm( NOTIFICATION_SEVERE_ALARM, record );
935     }
936
937     // Log error statistics APIs.
938

939     /**
940      * Set the number of intervals error statistics should be maintained.
941      *
942      * @param hours Number of intervals error statistics should be maintained.
943      */

944     public void setKeepErrorStatisticsForIntervals(
945             final int numberOfIntervals) {
946         ErrorStatistics.singleton().setNumOfIntervals(numberOfIntervals);
947     }
948     
949     /**
950      * @return Number of intervals for which error statistics are maintained.
951      */

952     public int getKeepErrorStatisticsForIntervals() {
953         return ErrorStatistics.singleton().getNumOfIntervals();
954     }
955     
956     /**
957      * Set the duration of an interval, in minutes.
958      *
959      * @param minutes The duration of an interval.
960      */

961     public void setErrorStatisticsIntervalMinutes(final long minutes) {
962         ErrorStatistics.singleton().setIntervalDuration(
963                     minutes*MINUTES_TO_MILLISECONDS);
964     }
965     
966     /**
967      * @return The duration of an interval, in minutes.
968      */

969     public long getErrorStatisticsIntervalMinutes() {
970         return ErrorStatistics.singleton().getIntervalDuration() /
971                 MINUTES_TO_MILLISECONDS;
972     }
973
974     /**
975      * Set the number of hours error statistics should be maintained.
976      *
977      * @param hours Number of hours error statistics should be maintained.
978      */

979     public void setKeepErrorStatisticsForHours(final int hours) {
980         ErrorStatistics.singleton().setNumOfIntervals(hours);
981     }
982         
983     /**
984      * @return The number of hours for which error statistics are maintained.
985      */

986     public int getKeepErrorStatisticsForHours() {
987         return ErrorStatistics.singleton().getNumOfIntervals();
988     }
989
990     /**
991      * @return a list of Map objects. Each map object contains
992      * the tuple [TimeStamp, SevereCount, WarningCount].
993      */

994     public List JavaDoc<Map JavaDoc<String JavaDoc,Object JavaDoc>> getErrorInformation() {
995         return ErrorStatistics.singleton().getErrorInformation();
996     }
997     
998     /**
999      * @return a list of Map objects. Each map object contains
1000     * the tuple [ModuleId, SevereCount|WarningCount].
1001     */

1002    public Map JavaDoc<String JavaDoc,Integer JavaDoc> getErrorDistribution(
1003            long timeStamp, Level JavaDoc level) {
1004        return ErrorStatistics.singleton().
1005                getErrorDistribution(timeStamp, level);
1006    }
1007
1008    /**
1009     * @param moduleName a predefined log module name. This name is same as the attribute
1010     * name of <module-log-levels> in <log-service> of domain.xml;
1011     * When null is passed in, it means all log modules.
1012     * @return a ArrayList(!=null) of predefined logger names for this log module.
1013     */

1014    public List JavaDoc getLognames4LogModule(String JavaDoc logModuleName) {
1015        String JavaDoc[] names = ModuleToLoggerNameMapper.getLoggerNames(logModuleName);
1016        return Arrays.asList(names);
1017    }
1018}
1019
Popular Tags