View Javadoc
1   /*
2    * @(#)Logger.java	1.6 05/11/17
3    * 
4    * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
5    *
6    * Redistribution and use in source and binary forms, with or without
7    * modification, are permitted provided that the following conditions are met:
8    *
9    * -Redistribution of source code must retain the above copyright notice, this
10   *  list of conditions and the following disclaimer.
11   *
12   * -Redistribution in binary form must reproduce the above copyright notice,
13   *  this list of conditions and the following disclaimer in the documentation
14   *  and/or other materials provided with the distribution.
15   *
16   * Neither the name of Sun Microsystems, Inc. or the names of contributors may
17   * be used to endorse or promote products derived from this software without
18   * specific prior written permission.
19   *
20   * This software is provided "AS IS," without a warranty of any kind. ALL
21   * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
22   * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
23   * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
24   * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
25   * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
26   * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
27   * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
28   * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
29   * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
30   * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
31   *
32   * You acknowledge that this software is not designed, licensed or intended
33   * for use in the design, construction, operation or maintenance of any
34   * nuclear facility.
35   */
36  
37  package jnlp.sample.servlet;
38  
39  import javax.servlet.ServletConfig;
40  import javax.servlet.ServletContext;
41  import java.io.FileWriter;
42  import java.io.IOException;
43  import java.io.PrintWriter;
44  import java.text.MessageFormat;
45  import java.util.MissingResourceException;
46  import java.util.ResourceBundle;
47  
48  /* A loging object used by the servlets */
49  public class Logger
50  {
51      // Logging levels
52      public final static int NONE = 0;
53  
54      public static final String NONE_KEY = "NONE";
55  
56      public final static int FATAL = 1;
57  
58      public static final String FATAL_KEY = "FATAL";
59  
60      public final static int WARNING = 2;
61  
62      public static final String WARNING_KEY = "WARNING";
63  
64      public final static int INFORMATIONAL = 3;
65  
66      public static final String INFORMATIONAL_KEY = "INFORMATIONAL";
67  
68      public final static int DEBUG = 4;
69  
70      public static final String DEBUG_KEY = "DEBUG";
71  
72      // Configuration parameters
73      private final static String LOG_LEVEL = "logLevel";
74  
75      private final static String LOG_PATH = "logPath";
76  
77      private int _loggingLevel = FATAL;
78  
79      private ServletContext _servletContext = null;
80  
81      private String _logFile = null;
82  
83      private String _servletName = null;
84  
85      // Localization
86      ResourceBundle _resources = null;
87  
88  
89      /**
90       * Initialize logging object. It reads the logLevel and pathLevel init parameters.
91       * Default is logging level FATAL, and logging using the ServletContext.log
92       */
93      public Logger( ServletConfig config, ResourceBundle resources )
94      {
95          _resources = resources;
96          _servletContext = config.getServletContext();
97          _servletName = config.getServletName();
98          _logFile = config.getInitParameter( LOG_PATH );
99          if ( _logFile != null )
100         {
101             _logFile = _logFile.trim();
102             if ( _logFile.length() == 0 )
103             {
104                 _logFile = null;
105             }
106         }
107         String level = config.getInitParameter( LOG_LEVEL );
108         if ( level != null )
109         {
110             level = level.trim().toUpperCase();
111             if ( level.equals( NONE_KEY ) )
112             {
113                 _loggingLevel = NONE;
114             }
115             if ( level.equals( FATAL_KEY ) )
116             {
117                 _loggingLevel = FATAL;
118             }
119             if ( level.equals( WARNING_KEY ) )
120             {
121                 _loggingLevel = WARNING;
122             }
123             if ( level.equals( INFORMATIONAL_KEY ) )
124             {
125                 _loggingLevel = INFORMATIONAL;
126             }
127             if ( level.equals( DEBUG_KEY ) )
128             {
129                 _loggingLevel = DEBUG;
130             }
131         }
132     }
133 
134     // Logging API. Fatal, Warning, and Informational are localized    
135     public void addFatal( String key, Throwable throwable )
136     {
137         logEvent( FATAL, getString( key ), throwable );
138     }
139 
140     public void addWarning( String key, String arg )
141     {
142         logL10N( WARNING, key, arg, (Throwable) null );
143     }
144 
145     public void addWarning( String key, String arg, Throwable t )
146     {
147         logL10N( WARNING, key, arg, t );
148     }
149 
150     public void addWarning( String key, String arg1, String arg2 )
151     {
152         logL10N( WARNING, key, arg1, arg2 );
153     }
154 
155     public void addWarning( String key, String arg1, String arg2, String arg3 )
156     {
157         logL10N( WARNING, key, arg1, arg2, arg3 );
158     }
159 
160     public void addInformational( String key )
161     {
162         logEvent( INFORMATIONAL, getString( key ), null );
163     }
164 
165     public void addInformational( String key, String arg )
166     {
167         logL10N( INFORMATIONAL, key, arg, (Throwable) null );
168     }
169 
170     public void addInformational( String key, String arg1, String arg2, String arg3 )
171     {
172         logL10N( INFORMATIONAL, key, arg1, arg2, arg3 );
173     }
174 
175     // Debug messages are not localized
176     public void addDebug( String msg )
177     {
178         logEvent( DEBUG, msg, null );
179     }
180 
181     public void addDebug( String msg, Throwable throwable )
182     {
183         logEvent( DEBUG, msg, throwable );
184     }
185 
186     // Query to test for level
187     boolean isNoneLevel()
188     {
189         return _loggingLevel >= NONE;
190     }
191 
192     boolean isFatalevel()
193     {
194         return _loggingLevel >= FATAL;
195     }
196 
197     boolean isWarningLevel()
198     {
199         return _loggingLevel >= WARNING;
200     }
201 
202     boolean isInformationalLevel()
203     {
204         return _loggingLevel >= INFORMATIONAL;
205     }
206 
207     boolean isDebugLevel()
208     {
209         return _loggingLevel >= DEBUG;
210     }
211 
212     // Returns a string from the resources    
213     private String getString( String key )
214     {
215         try
216         {
217             return _resources.getString( key );
218         }
219         catch ( MissingResourceException mre )
220         {
221             return "Missing resource for: " + key;
222         }
223     }
224 
225     private void logL10N( int level, String key, String arg, Throwable e )
226     {
227         Object[] messageArguments = { arg };
228         logEvent( level, applyPattern( key, messageArguments ), e );
229     }
230 
231     private void logL10N( int level, String key, String arg1, String arg2 )
232     {
233         Object[] messageArguments = { arg1, arg2 };
234         logEvent( level, applyPattern( key, messageArguments ), null );
235     }
236 
237     private void logL10N( int level, String key, String arg1, String arg2, String arg3 )
238     {
239         Object[] messageArguments = { arg1, arg2, arg3 };
240         logEvent( level, applyPattern( key, messageArguments ), null );
241     }
242 
243     /**
244      * Helper function that applies the messageArguments to a message from the resource object
245      */
246     private String applyPattern( String key, Object[] messageArguments )
247     {
248         String message = getString( key );
249 //        MessageFormat formatter = new MessageFormat( message );
250         String output = MessageFormat.format( message, messageArguments );
251         return output;
252     }
253 
254     // The method that actually does the logging */
255     private synchronized void logEvent( int level, String string, Throwable throwable )
256     {
257         // Check if the event should be logged
258         if ( level > _loggingLevel )
259         {
260             return;
261         }
262 
263         if ( _logFile != null )
264         {
265             // No logfile specified, log using servlet context
266             PrintWriter pw = null;
267             try
268             {
269                 pw = new PrintWriter( new FileWriter( _logFile, true ) );
270                 pw.println( _servletName + "(" + level + "): " + string );
271                 if ( throwable != null )
272                 {
273                     throwable.printStackTrace( pw );
274                 }
275                 pw.close();
276                 // Do a return here. An exception will cause a fall through to
277                 // do _servletContex logging API
278                 return;
279             }
280             catch ( IOException ioe )
281             {
282                 /* just ignore */
283             }
284         }
285 
286         // Otherwise, write to servlet context log
287         if ( throwable == null )
288         {
289             _servletContext.log( string );
290         }
291         else
292         {
293             _servletContext.log( string, throwable );
294         }
295     }
296 }
297