KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > log > Hierarchy


1 /*
2  * Copyright 1999-2004 The Apache Software Foundation
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12  * implied.
13  *
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17 package org.apache.log;
18
19 import org.apache.log.format.PatternFormatter;
20 import org.apache.log.output.io.StreamTarget;
21 import org.apache.log.util.DefaultErrorHandler;
22 import org.apache.log.util.LoggerListener;
23
24 /**
25  * This class encapsulates a basic independent log hierarchy.
26  * The hierarchy is essentially a safe wrapper around root logger.
27  *
28  * @author <a HREF="mailto:dev@avalon.apache.org">Avalon Development Team</a>
29  * @author Peter Donald
30  */

31 public class Hierarchy
32 {
33     ///Format of default formatter
34
public static final String JavaDoc DEFAULT_FORMAT =
35         "%7.7{priority} %23.23{time:yyyy-MM-dd' 'HH:mm:ss.SSS} " +
36         "[%8.8{category}] (%{context}): %{message}\n%{throwable}";
37
38     ///The instance of default hierarchy
39
private static final Hierarchy c_hierarchy = new Hierarchy();
40
41     ///Error Handler associated with hierarchy
42
private ErrorHandler m_errorHandler;
43
44     ///The root logger which contains all Loggers in this hierarchy
45
private Logger m_rootLogger;
46
47     ///LoggerListener associated with hierarchy
48
private LoggerListener m_loggerListener;
49
50     /**
51      * Retrieve the default hierarchy.
52      *
53      * <p>In most cases the default LogHierarchy is the only
54      * one used in an application. However when security is
55      * a concern or multiple independent applications will
56      * be running in same JVM it is advantageous to create
57      * new Hierarchies rather than reuse default.</p>
58      *
59      * @return the default Hierarchy
60      */

61     public static Hierarchy getDefaultHierarchy()
62     {
63         return c_hierarchy;
64     }
65
66     /**
67      * Create a hierarchy object.
68      * The default LogTarget writes to stdout.
69      */

70     public Hierarchy()
71     {
72         m_errorHandler = new DefaultErrorHandler();
73         m_rootLogger = new Logger( new InnerErrorHandler(),
74                                    new InnerLoggerListener(),
75                                    "", null, null );
76
77         //Setup default output target to print to console
78
final PatternFormatter formatter = new PatternFormatter( DEFAULT_FORMAT );
79         final StreamTarget target = new StreamTarget( System.out, formatter );
80
81         setDefaultLogTarget( target );
82     }
83
84     /**
85      * Set the default log target for hierarchy.
86      * This is the target inherited by loggers if no other target is specified.
87      *
88      * @param target the default target
89      */

90     public void setDefaultLogTarget( final LogTarget target )
91     {
92         if( null == target )
93         {
94             throw new IllegalArgumentException JavaDoc( "Can not set DefaultLogTarget to null" );
95         }
96
97         final LogTarget[] targets = new LogTarget[]{target};
98         getRootLogger().setLogTargets( targets );
99     }
100
101     /**
102      * Set the default log targets for this hierarchy.
103      * These are the targets inherited by loggers if no other targets are specified
104      *
105      * @param targets the default targets
106      */

107     public void setDefaultLogTargets( final LogTarget[] targets )
108     {
109         if( null == targets || 0 == targets.length )
110         {
111             throw new IllegalArgumentException JavaDoc( "Can not set DefaultLogTargets to null" );
112         }
113
114         for( int i = 0; i < targets.length; i++ )
115         {
116             if( null == targets[ i ] )
117             {
118                 final String JavaDoc message = "Can not set DefaultLogTarget element to null";
119                 throw new IllegalArgumentException JavaDoc( message );
120             }
121         }
122
123         getRootLogger().setLogTargets( targets );
124     }
125
126     /**
127      * Set the default priority for hierarchy.
128      * This is the priority inherited by loggers if no other priority is specified.
129      *
130      * @param priority the default priority
131      */

132     public void setDefaultPriority( final Priority priority )
133     {
134         if( null == priority )
135         {
136             final String JavaDoc message = "Can not set default Hierarchy Priority to null";
137             throw new IllegalArgumentException JavaDoc( message );
138         }
139
140         getRootLogger().setPriority( priority );
141     }
142
143     /**
144      * Set the ErrorHandler associated with hierarchy.
145      *
146      * @param errorHandler the ErrorHandler
147      */

148     public void setErrorHandler( final ErrorHandler errorHandler )
149     {
150         if( null == errorHandler )
151         {
152             final String JavaDoc message = "Can not set default Hierarchy ErrorHandler to null";
153             throw new IllegalArgumentException JavaDoc( message );
154         }
155
156         m_errorHandler = errorHandler;
157     }
158
159     /**
160      * Set the LoggerListener associated with hierarchy. This is a
161      * unicast listener, so only one LoggerListener is allowed.
162      *
163      * @param loggerListener the LoggerListener
164      *
165      * @throws UnsupportedOperationException if no more LoggerListeners are
166      * permitted.
167      */

168     public synchronized void addLoggerListener( final LoggerListener loggerListener )
169     {
170         if( null == loggerListener )
171         {
172             throw new NullPointerException JavaDoc( "loggerListener" );
173         }
174
175         if( null == m_loggerListener )
176         {
177             m_loggerListener = loggerListener;
178         }
179         else
180         {
181             final String JavaDoc message = "LoggerListener already set on a unicast event notifier";
182             throw new UnsupportedOperationException JavaDoc( message );
183         }
184     }
185
186     /**
187      * Remove the LoggerListener associated with hierarchy. Perform this
188      * step before adding a new one if you want to change it.
189      *
190      * @param loggerListener the LoggerListener
191      */

192     public synchronized void removeLoggerListener( final LoggerListener loggerListener )
193     {
194         if( null == loggerListener )
195         {
196             throw new NullPointerException JavaDoc( "loggerListener" );
197         }
198
199         if( null != m_loggerListener && m_loggerListener == loggerListener ) ;
200         {
201             m_loggerListener = null;
202         }
203     }
204
205     /**
206      * Retrieve a logger for named category.
207      *
208      * @param category the context
209      * @return the Logger
210      */

211     public Logger getLoggerFor( final String JavaDoc category )
212     {
213         return getRootLogger().getChildLogger( category );
214     }
215
216     /**
217      * Notify logger listener (if any) that a new logger was created.
218      *
219      * @param category the category of new logger
220      * @param logger the logger
221      */

222     private synchronized void notifyLoggerCreated( final String JavaDoc category,
223                                                    final Logger logger )
224     {
225         if( null != m_loggerListener )
226         {
227             m_loggerListener.loggerCreated( category, logger );
228         }
229     }
230
231     /**
232      * Inner class to redirect to hierarchys real LoggerListener if any.
233      * Used so that all the loggers will not have to be updated
234      * when LoggerListener changes.
235      */

236     private class InnerLoggerListener
237         extends LoggerListener
238     {
239         /**
240          * Notify listener that a logger was created.
241          *
242          * @param category the category of logger
243          * @param logger the logger object
244          */

245         public void loggerCreated( final String JavaDoc category,
246                                    final Logger logger )
247         {
248             notifyLoggerCreated( category, logger );
249         }
250     }
251
252     private class InnerErrorHandler
253         implements ErrorHandler
254     {
255         /**
256          * Log an unrecoverable error.
257          *
258          * @param message the error message
259          * @param throwable the exception associated with error (may be null)
260          * @param event the LogEvent that caused error, if any (may be null)
261          */

262         public void error( final String JavaDoc message,
263                            final Throwable JavaDoc throwable,
264                            final LogEvent event )
265         {
266             m_errorHandler.error( message, throwable, event );
267         }
268     }
269
270     /**
271      * Utility method to retrieve logger for hierarchy.
272      * This method is intended for use by sub-classes
273      * which can take responsibility for manipulating
274      * Logger directly.
275      *
276      * @return the Logger
277      */

278     public final Logger getRootLogger()
279     {
280         return m_rootLogger;
281     }
282 }
283
Popular Tags