KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > avalon > logging > logkit > DefaultLoggingFactory


1 /*
2  * Copyright 2004 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
18 package org.apache.avalon.logging.logkit;
19
20 import java.io.File JavaDoc;
21 import java.io.InputStream JavaDoc;
22 import java.net.URL JavaDoc;
23 import java.util.Map JavaDoc;
24 import java.util.HashMap JavaDoc;
25 import java.util.ArrayList JavaDoc;
26
27 import org.apache.avalon.framework.logger.Logger;
28 import org.apache.avalon.framework.configuration.Configuration;
29 import org.apache.avalon.framework.configuration.ConfigurationException;
30 import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
31
32 import org.apache.avalon.logging.impl.ConsoleLogger;
33 import org.apache.avalon.logging.impl.DefaultLoggingCriteria;
34
35 import org.apache.avalon.logging.data.CategoriesDirective;
36 import org.apache.avalon.logging.data.CategoryDirective;
37
38 import org.apache.avalon.logging.provider.LoggingCriteria;
39 import org.apache.avalon.logging.provider.LoggingFactory;
40 import org.apache.avalon.logging.provider.LoggingException;
41 import org.apache.avalon.logging.provider.LoggingManager;
42
43 import org.apache.avalon.logging.logkit.factory.FileTargetFactory;
44 import org.apache.avalon.logging.logkit.factory.StreamTargetFactory;
45 import org.apache.avalon.logging.logkit.factory.MulticastTargetFactory;
46 import org.apache.avalon.logging.logkit.factory.PluginTargetFactory;
47
48 import org.apache.avalon.repository.provider.InitialContext;
49
50 import org.apache.avalon.util.i18n.ResourceManager;
51 import org.apache.avalon.util.i18n.Resources;
52
53 import org.apache.excalibur.configuration.ConfigurationUtil;
54
55 import org.apache.log.LogTarget;
56
57 /**
58  * The DefaultLoggingFactory provides support for the establishment of a
59  * new logging system using LogKit as the implementation.
60  */

61 public class DefaultLoggingFactory implements LoggingFactory
62 {
63     //--------------------------------------------------------------------------
64
// static
65
//--------------------------------------------------------------------------
66

67     private static final Resources REZ =
68       ResourceManager.getPackageResources( DefaultLoggingFactory.class );
69
70     private static final FormatterFactory FORMATTER =
71       new DefaultFormatterFactory();
72
73     //--------------------------------------------------------------------------
74
// immutable state
75
//--------------------------------------------------------------------------
76

77     private final ClassLoader JavaDoc m_classloader;
78     private final InitialContext m_context;
79     
80     //--------------------------------------------------------------------------
81
// state
82
//--------------------------------------------------------------------------
83

84     private Logger m_logger;
85     private File JavaDoc m_basedir;
86     private LogTargetFactoryManager m_factories;
87     private LogTargetManager m_targets;
88     private LogTargetFactoryBuilder m_builder;
89
90     //--------------------------------------------------------------------------
91
// constructor
92
//--------------------------------------------------------------------------
93

94    /**
95     * Creation of a new default factory.
96     * @param context the repository inital context
97     * @param classloader the factory classloader
98     */

99     public DefaultLoggingFactory( InitialContext context, ClassLoader JavaDoc classloader )
100     {
101         m_context = context;
102         m_classloader = classloader;
103     }
104
105     //--------------------------------------------------------------------------
106
// LoggingFactory
107
//--------------------------------------------------------------------------
108

109    /**
110     * Return of map containing the default parameters.
111     *
112     * @return the default parameters
113     */

114     public LoggingCriteria createDefaultLoggingCriteria()
115     {
116         return new DefaultLoggingCriteria( m_context );
117     }
118
119    /**
120     * Create a new LoggingManager using the supplied logging criteria.
121     *
122     * @param criteria the logging system factory criteria
123     * @exception LoggingException is a logging system creation error occurs
124     */

125     public LoggingManager createLoggingManager( LoggingCriteria criteria )
126       throws LoggingException
127     {
128         try
129         {
130             return (LoggingManager) create( criteria );
131         }
132         catch( Throwable JavaDoc e )
133         {
134             final String JavaDoc error =
135               "Cannot build logging manager.";
136             throw new LoggingException( error, e );
137         }
138     }
139
140     //--------------------------------------------------------------------------
141
// Factory
142
//--------------------------------------------------------------------------
143

144    /**
145     * Return of map containing the default parameters.
146     *
147     * @return the default parameters
148     */

149     public Map JavaDoc createDefaultCriteria()
150     {
151         return createDefaultLoggingCriteria();
152     }
153
154    /**
155     * Creation of a new kernel using the default criteria.
156     *
157     * @return the kernel instance
158     * @exception Exception if an error occurs during root block establishment
159     */

160     public Object JavaDoc create() throws Exception JavaDoc
161     {
162         return create( createDefaultCriteria() );
163     }
164
165    /**
166     * Creation of a new logging manager using the supplied criteria.
167     *
168     * @param map the parameters
169     * @return the logging manager instance
170     * @exception Exception if an error occurs
171     */

172     public Object JavaDoc create( final Map JavaDoc map ) throws Exception JavaDoc
173     {
174         if( null == map )
175         {
176             throw new NullPointerException JavaDoc( "map" );
177         }
178
179         final LoggingCriteria criteria = getLoggingCriteria( map );
180
181         //
182
// get the logging system configuration, base directory
183
// and bootstrap logger and setup the primary managers
184
//
185

186         DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
187         
188         URL JavaDoc configURL = criteria.getLoggingConfiguration();
189         Configuration config;
190         if( configURL != null )
191         {
192             config = builder.build( configURL.toExternalForm() );
193         }
194         else
195         {
196             InputStream JavaDoc defaultConf =
197               getClass().getClassLoader().
198                 getResourceAsStream(
199                   "org/apache/avalon/logging/logkit/default-logging.xml"
200                 );
201             config = builder.build( defaultConf );
202         }
203         
204         m_logger = setUpBootstrapLogger( criteria, config );
205         m_basedir = criteria.getBaseDirectory();
206
207         Map JavaDoc factoriesMap = new HashMap JavaDoc();
208         m_factories = new DefaultLogTargetFactoryManager( factoriesMap );
209
210         Map JavaDoc targetsMap = new HashMap JavaDoc();
211         m_targets = new DefaultLogTargetManager( targetsMap );
212
213         m_builder =
214           new DefaultLogTargetFactoryBuilder(
215             m_context, m_classloader, m_logger, m_basedir,
216             m_factories, m_targets );
217
218         //
219
// setup the logging targets
220
//
221

222         final Configuration targetsConfig = config.getChild( "targets" );
223         setupTargets( factoriesMap, targetsMap, targetsConfig );
224
225         //
226
// setup the logging categories directive
227
//
228

229         CategoriesDirective categories =
230           getCategoriesDirective( config.getChild( "categories" ), true );
231
232         //
233
// setup the internal logging channel name
234
//
235

236         String JavaDoc internal =
237           config.getChild( "logger" ).getAttribute( "name", "logger" );
238
239         //
240
// get the debug policy
241
//
242

243         boolean debug = criteria.isDebugEnabled();
244
245         //
246
// create a logkit logging mananager
247
//
248

249         LoggingManager manager =
250           new DefaultLoggingManager( m_logger, m_targets, categories, internal, debug );
251
252         //
253
// setup the default log target
254
//
255

256         return manager;
257     }
258
259     private LoggingCriteria getLoggingCriteria( Map JavaDoc map )
260     {
261         if( map instanceof LoggingCriteria )
262         {
263             return (LoggingCriteria) map;
264         }
265         else
266         {
267             final String JavaDoc error =
268               REZ.getString(
269                 "factory.bad-criteria",
270                 map.getClass().getName() );
271             throw new IllegalArgumentException JavaDoc( error );
272         }
273     }
274
275     private Logger setUpBootstrapLogger( LoggingCriteria criteria, Configuration config )
276     {
277         if( config.getAttribute( "debug", "false" ).equals( "true" ) )
278         {
279             return new ConsoleLogger( ConsoleLogger.LEVEL_DEBUG );
280         }
281         else
282         {
283             return criteria.getBootstrapLogger();
284         }
285     }
286
287    /**
288     * Setup of the log targets declared in the logging configuration.
289     * @param logger the logging channel to log establishment events
290     * @param manager the log factory manager from which target factories
291     * are resolved
292     * @param config the log targets configuration
293     */

294     private void setupTargets(
295       final Map JavaDoc factories, final Map JavaDoc targets, final Configuration config )
296       throws LoggingException
297     {
298         Configuration[] children = config.getChildren();
299         for( int i = 0; i < children.length; i++ )
300         {
301             Configuration child = children[i];
302             final String JavaDoc id = getTargetId( child );
303             try
304             {
305                 final LogTarget target =
306                   createLogTarget( factories, id, child );
307                 targets.put( id, target );
308                 final String JavaDoc message =
309                   REZ.getString( "target.notice.add", id );
310                 m_logger.debug( message );
311             }
312             catch( Throwable JavaDoc e )
313             {
314                 final String JavaDoc error =
315                   REZ.getString( "target.notice.fail", id );
316                 m_logger.error( error, e );
317                 throw new LoggingException( error, e );
318             }
319         }
320     }
321
322    /**
323     * Create a new log target using a supplied configuration.
324     * @param manager the log target factory manager
325     * @param config the target configuration
326     * @return the logging target
327     * @exception Exception if an error occurs during factory creation
328     */

329     private LogTarget createLogTarget(
330       Map JavaDoc factories, final String JavaDoc id, final Configuration config )
331       throws LoggingException
332     {
333         final String JavaDoc key = getTargetFactoryKey( config );
334         final LogTargetFactory factory =
335           getLogTargetFactory( factories, key );
336         return factory.createTarget( config );
337     }
338
339     private LogTargetFactory getLogTargetFactory( Map JavaDoc factories, String JavaDoc key )
340       throws LoggingException
341     {
342         final LogTargetFactory factory =
343           m_factories.getLogTargetFactory( key );
344         if( factory != null )
345         {
346             return factory;
347         }
348         else
349         {
350             Class JavaDoc clazz = getLogTargetFactoryClass( key );
351             LogTargetFactory newFactory =
352               m_builder.buildLogTargetFactory( clazz );
353             factories.put( key, newFactory );
354             return newFactory;
355         }
356     }
357
358     private Class JavaDoc getLogTargetFactoryClass( final String JavaDoc key )
359       throws LoggingException
360     {
361         if( key.equals( "file" ) )
362         {
363             return FileTargetFactory.class;
364         }
365         else if( key.equals( "stream" ) )
366         {
367             return StreamTargetFactory.class;
368         }
369         else if( key.equals( "multicast" ) )
370         {
371             return MulticastTargetFactory.class;
372         }
373         else if( key.equals( "target" ) )
374         {
375             return PluginTargetFactory.class;
376         }
377         else
378         {
379             final String JavaDoc message =
380               REZ.getString( "factory.error.unknown", key );
381             throw new LoggingException( message );
382         }
383     }
384
385    /**
386     * Return the factory key declared by a log target configuration.
387     * @param the target configuration
388     * @return the factory key
389     */

390     private String JavaDoc getTargetFactoryKey( Configuration config )
391       throws LoggingException
392     {
393         return config.getName();
394     }
395
396    /**
397     * Return the id assigned to a target.
398     * @param config the target configuration
399     * @return the target id
400     * @exception LoggingException if the id is not declared
401     */

402     private String JavaDoc getTargetId( Configuration config )
403       throws LoggingException
404     {
405         try
406         {
407             return config.getAttribute( "id" );
408         }
409         catch( ConfigurationException e )
410         {
411             final String JavaDoc listing = ConfigurationUtil.list( config );
412             final String JavaDoc error =
413               REZ.getString(
414                 "target.error.missing-id",
415                 listing );
416             throw new LoggingException( error );
417         }
418     }
419
420     private CategoriesDirective getCategoriesDirective( Configuration config )
421       throws LoggingException
422     {
423         return getCategoriesDirective( config, false );
424     }
425
426     private CategoriesDirective getCategoriesDirective(
427       Configuration config, boolean root )
428       throws LoggingException
429     {
430         final String JavaDoc name = getCategoryName( config, root );
431         final String JavaDoc priority = config.getAttribute( "priority", null );
432         final String JavaDoc target = config.getAttribute( "target", null );
433         CategoryDirective[] categories =
434           getCategoryDirectives( config );
435         return new CategoriesDirective( name, priority, target, categories );
436     }
437
438     private String JavaDoc getCategoryName( Configuration config, boolean root )
439       throws LoggingException
440     {
441         if( root ) return "";
442         final String JavaDoc name = config.getAttribute( "name", null );
443         if( null != name ) return name;
444
445         final String JavaDoc error =
446           REZ.getString( "target.error.missing-category-name" );
447         throw new LoggingException( error );
448     }
449
450     private CategoryDirective[] getCategoryDirectives( Configuration config )
451       throws LoggingException
452     {
453         ArrayList JavaDoc list = new ArrayList JavaDoc();
454         Configuration[] children = config.getChildren();
455         for( int i=0; i<children.length; i++ )
456         {
457             Configuration child = children[i];
458             if( child.getName().equals( "category" ) )
459             {
460                 CategoryDirective directive =
461                   getCategoryDirective( child );
462                 list.add( directive );
463             }
464             else if( child.getName().equals( "categories" ) )
465             {
466                 CategoriesDirective directive =
467                   getCategoriesDirective( child );
468                 list.add( directive );
469             }
470         }
471         return (CategoryDirective[]) list.toArray( new CategoryDirective[0] );
472     }
473
474     private CategoryDirective getCategoryDirective( Configuration config )
475       throws LoggingException
476     {
477         final String JavaDoc name = getCategoryName( config, false );
478         final String JavaDoc priority = config.getAttribute( "priority", null );
479         final String JavaDoc target = config.getAttribute( "target", null );
480         return new CategoryDirective( name, priority, target );
481     }
482 }
483
Popular Tags