KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > tools > admingui > PlainFormatter


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
24 package com.sun.enterprise.tools.admingui;
25
26
27 import java.util.logging.Formatter JavaDoc;
28 import java.util.logging.LogRecord JavaDoc;
29 import java.util.logging.LogManager JavaDoc;
30 import java.util.logging.Logger JavaDoc;
31 import java.util.logging.Level JavaDoc;
32 import java.util.logging.ErrorManager JavaDoc;
33 import java.util.ResourceBundle JavaDoc;
34 import java.util.HashMap JavaDoc;
35 import java.util.Date JavaDoc;
36 import java.util.Map JavaDoc;
37 import java.util.Iterator JavaDoc;
38 import java.text.SimpleDateFormat JavaDoc;
39 import java.text.MessageFormat JavaDoc;
40 import java.text.FieldPosition JavaDoc;
41 import java.io.StringWriter JavaDoc;
42 import java.io.PrintWriter JavaDoc;
43
44 /**
45  * UniformLogFormatter conforms to the logging format defined by the
46  * Log Working Group in Java Webservices Org.
47  * The specified format is
48  * "[#|DATETIME|LOG_LEVEL|PRODUCT_ID|LOGGER NAME|OPTIONAL KEY VALUE PAIRS|
49  * MESSAGE|#]\n"
50  *
51  * @author Hemanth Puttaswamy
52  *
53  * TODO:
54  * 1. Performance improvement. We can Cache the the LOG_LEVEL|PRODUCT_ID strings
55  * and minimize the concatenations and revisit for more performance
56  * improvements
57  * 2. Need to use Product Name and Version based on the version string
58  * that is part of the product.
59  * 3. Stress testing
60  * 4. If there is a Map as the last element, need to scan the message to
61  * distinguish key values with the message argument.
62  */

63
64 public class PlainFormatter extends Formatter JavaDoc {
65     // loggerResourceBundleTable caches references to all the ResourceBundle
66
// and can be searched using the LoggerName as the key
67
private HashMap JavaDoc loggerResourceBundleTable;
68     private LogManager JavaDoc logManager;
69     // A Dummy Container Date Object is used to format the date
70
private Date JavaDoc date = new Date JavaDoc( );
71     private static String JavaDoc PRODUCTID_CONTEXTID = null;
72     // This is temporary, in the next phase of implementation the product Id
73
// will be obtained from the version object that is part of Sun One AppServ
74
// Bug 4882896: string initialized using Version.java
75
private static final String JavaDoc PRODUCT_VERSION =
76             com.sun.appserv.server.util.Version.getAbbreviatedVersion();
77     private static final int FINE_LEVEL_INT_VALUE = Level.FINE.intValue();
78
79
80
81     private static final String JavaDoc LINE_SEPARATOR =
82         (String JavaDoc) java.security.AccessController.doPrivileged(
83             new sun.security.action.GetPropertyAction("line.separator"));
84
85     private static final String JavaDoc RECORD_BEGIN_MARKER = "[#|";
86     private static final String JavaDoc RECORD_END_MARKER = "|#]" + LINE_SEPARATOR +
87         LINE_SEPARATOR;
88     private static final String JavaDoc FIELD_SEPARATOR = "|";
89     private static final String JavaDoc NVPAIR_SEPARATOR = ";";
90
91     private static final String JavaDoc RFC_3339_DATE_FORMAT =
92         "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
93
94     private static final SimpleDateFormat JavaDoc dateFormatter =
95         new SimpleDateFormat JavaDoc( RFC_3339_DATE_FORMAT );
96
97     public PlainFormatter() {
98         super( );
99         loggerResourceBundleTable = new HashMap JavaDoc( );
100         logManager = LogManager.getLogManager( );
101     }
102
103
104     /**
105      * _REVISIT_: Replace the String Array with an HashMap and do some
106      * benchmark to determine whether StringCat is faster or Hashlookup for
107      * the template is faster.
108      */

109             
110
111     public String JavaDoc format( LogRecord JavaDoc record ) {
112         return uniformLogFormat( record );
113     }
114
115     public String JavaDoc formatMessage( LogRecord JavaDoc record ) {
116         return uniformLogFormat( record );
117     }
118
119
120     /**
121      * Sun One AppServer SE/EE can override to specify their product version
122      */

123     protected String JavaDoc getProductId( ) {
124         return PRODUCT_VERSION;
125     }
126
127     
128     /**
129      * Sun One Appserver SE/EE? can override to specify their product specific
130      * key value pairs.
131      */

132     protected StringBuffer JavaDoc getNameValuePairs( LogRecord JavaDoc record ) {
133         Object JavaDoc[] parameters = record.getParameters( );
134         StringBuffer JavaDoc namevaluePairs = new StringBuffer JavaDoc("");
135         try {
136             if( ( parameters == null )
137               ||( parameters.length == 0 ) )
138             {
139                 return namevaluePairs;
140             }
141             int lastElement = parameters.length - 1;
142             if( parameters[lastElement] instanceof java.util.Map JavaDoc ) {
143                 Iterator JavaDoc iterator = ((Map JavaDoc)(parameters[lastElement])).entrySet(
144                     ).iterator( );
145                 while( iterator.hasNext( ) ) {
146                     Map.Entry JavaDoc entry = (Map.Entry JavaDoc) iterator.next();
147                     namevaluePairs.append( entry.getKey() + "=" +
148                         entry.getValue() + NVPAIR_SEPARATOR );
149                 }
150             }
151         } catch( Exception JavaDoc e ) {
152             new ErrorManager JavaDoc().error(
153                 "Error in extracting Name Value Pairs", e,
154                 ErrorManager.FORMAT_FAILURE );
155         }
156         return namevaluePairs;
157     }
158
159     /**
160      * Note: This method is not synchronized, we are assuming that the
161      * synchronization will happen at the Log Handler.publish( ) method.
162      */

163     private String JavaDoc uniformLogFormat( LogRecord JavaDoc record ) {
164         try {
165             StringBuffer JavaDoc recordBuffer = new StringBuffer JavaDoc();
166             // The following operations are to format the date and time in a
167
// human readable format.
168
// _REVISIT_: Use HiResolution timer to analyze the number of
169
// Microseconds spent on formatting date object
170
//date.setTime( record.getMillis( ) );
171
//dateFormatter.format( date, recordBuffer, new FieldPosition(0) );
172

173             //recordBuffer.append( FIELD_SEPARATOR +
174
// record.getLevel().getLocalizedName() + FIELD_SEPARATOR );
175
//recordBuffer.append( getProductId() + FIELD_SEPARATOR );
176
//recordBuffer.append( record.getLoggerName( ) + FIELD_SEPARATOR );
177
//recordBuffer.append( "_ThreadID=" + record.getThreadID( ) +
178
// NVPAIR_SEPARATOR );
179
//recordBuffer.append( getNameValuePairs( record ) );
180
//recordBuffer.append( FIELD_SEPARATOR );
181
String JavaDoc logMessage = record.getMessage();
182             ResourceBundle JavaDoc rb = getResourceBundle( record.getLoggerName( ) );
183             if( rb != null )
184             {
185                 try {
186                     logMessage = MessageFormat.format(
187                         rb.getString( logMessage ),
188                         record.getParameters( ) );
189                 } catch ( java.util.MissingResourceException JavaDoc e ) {
190                     // If we don't find an entry, then we are covered because
191
// the logMessage is intialized already
192
}
193             }
194             recordBuffer.append( logMessage );
195
196             if (record.getThrown() != null) {
197                 recordBuffer.append( LINE_SEPARATOR );
198                 StringWriter JavaDoc sw = new StringWriter JavaDoc();
199                 PrintWriter JavaDoc pw = new PrintWriter JavaDoc(sw);
200                 record.getThrown().printStackTrace(pw);
201                 pw.close();
202                 recordBuffer.append(sw.toString());
203             }
204             recordBuffer.append( LINE_SEPARATOR );
205
206             return recordBuffer.toString( );
207         } catch( Exception JavaDoc ex ) {
208             new ErrorManager JavaDoc().error(
209                 "Error in formatting Logrecord", ex,
210                 ErrorManager.FORMAT_FAILURE );
211             // We've already notified the exception, the following
212
// return is to keep javac happy
213
return new String JavaDoc("");
214         }
215     }
216  
217     private synchronized ResourceBundle JavaDoc getResourceBundle( String JavaDoc loggerName ) {
218         if( loggerName == null ) {
219             return null;
220         }
221         ResourceBundle JavaDoc rb = (ResourceBundle JavaDoc) loggerResourceBundleTable.get(
222             loggerName );
223  
224         if( rb == null ) {
225             rb = logManager.getLogger( loggerName ).getResourceBundle( );
226             loggerResourceBundleTable.put( loggerName, rb );
227         }
228         return rb;
229     }
230 }
231
232
233
Popular Tags