KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > avalon > excalibur > logger > SimpleLogKitManager


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

19 package org.apache.avalon.excalibur.logger;
20
21 import java.io.File JavaDoc;
22 import java.io.IOException JavaDoc;
23 import java.util.Collection JavaDoc;
24 import java.util.HashMap JavaDoc;
25 import java.util.Iterator JavaDoc;
26 import org.apache.avalon.framework.activity.Disposable;
27 import org.apache.avalon.framework.configuration.Configurable;
28 import org.apache.avalon.framework.configuration.Configuration;
29 import org.apache.avalon.framework.configuration.ConfigurationException;
30 import org.apache.avalon.framework.context.Context;
31 import org.apache.avalon.framework.context.ContextException;
32 import org.apache.avalon.framework.context.Contextualizable;
33 import org.apache.avalon.framework.logger.AbstractLogEnabled;
34 import org.apache.avalon.framework.logger.AvalonFormatter;
35 import org.apache.avalon.framework.logger.LogKitLogger;
36 import org.apache.log.Hierarchy;
37 import org.apache.log.LogTarget;
38 import org.apache.log.Logger;
39 import org.apache.log.Priority;
40 import org.apache.log.output.io.FileTarget;
41 import org.apache.log.util.Closeable;
42
43 /**
44  * A {@link LoggerManager} that supports the old <logs version="1.0"/>
45  * style logging configuration from
46  * <a HREF="http://jakarta.apache.org/avalon/phoenix">Phoenix</a>.
47  *
48  * @author <a HREF="mailto:dev@avalon.apache.org">Avalon Development Team</a>
49  */

50 public class SimpleLogKitManager
51     extends AbstractLogEnabled
52     implements LoggerManager, Contextualizable, Configurable, Disposable
53 {
54     private static final String JavaDoc DEFAULT_FORMAT =
55         "%7.7{priority} %23.23{time:yyyy-MM-dd' 'HH:mm:ss.SSS} [%8.8{category}] (%{context}): "
56         + "%{message}\n%{throwable}";
57
58     ///Base directory of applications working directory
59
private File JavaDoc m_baseDirectory;
60
61     /**
62      * Hierarchy of Application logging
63      */

64     private final Hierarchy m_hierarchy = new Hierarchy();
65
66     /**
67      * The root logger in hierarchy.
68      */

69     private final Logger m_logkitLogger = m_hierarchy.getLoggerFor( "" );
70
71     /**
72      * The root logger wrapped using AValons Logging Facade.
73      */

74     private org.apache.avalon.framework.logger.Logger m_logger =
75         new LogKitLogger( m_logkitLogger );
76     private Collection JavaDoc m_targets;
77
78     /**
79      * Contextualize the manager. Requires that the "app.home" entry
80      * be set to a File object that points at the base directory for logs.
81      *
82      * @param context the context
83      * @throws ContextException if missing context entry
84      */

85     public void contextualize( final Context context )
86         throws ContextException
87     {
88         try
89         {
90             m_baseDirectory = (File JavaDoc)context.get( "app.home" );
91         }
92         catch( ContextException e )
93         {
94             m_baseDirectory = new File JavaDoc( "." );
95         }
96     }
97
98     /**
99      * Interpret configuration to build loggers.
100      *
101      * @param configuration the configuration
102      * @throws ConfigurationException if malformed configuration
103      */

104     public void configure( final Configuration configuration )
105         throws ConfigurationException
106     {
107         final Configuration[] targets = configuration.getChildren( "log-target" );
108         final HashMap JavaDoc targetSet = configureTargets( targets );
109         m_targets = targetSet.values();
110         final Configuration[] categories = configuration.getChildren( "category" );
111         configureCategories( categories, targetSet );
112     }
113
114     /**
115      * Close any closable log targets opened by LoggerManager.
116      */

117     public void dispose()
118     {
119         final Iterator JavaDoc iterator = m_targets.iterator();
120         while( iterator.hasNext() )
121         {
122             final LogTarget logTarget = (LogTarget)iterator.next();
123             if( logTarget instanceof Closeable )
124             {
125                 ( (Closeable)logTarget ).close();
126             }
127         }
128     }
129
130     /**
131      * Retrieve a logger by name.
132      *
133      * @param name the name of logger
134      * @return the specified Logger
135      */

136     public org.apache.avalon.framework.logger.Logger
137         getLoggerForCategory( final String JavaDoc name )
138     {
139         return m_logger.getChildLogger( name );
140     }
141
142     /**
143      * Retrieve the root logger.
144      *
145      * @return the root Logger
146      */

147     public org.apache.avalon.framework.logger.Logger getDefaultLogger()
148     {
149         return m_logger;
150     }
151
152     /**
153      * Configure a set of logtargets based on config data.
154      *
155      * @param targets the target configuration data
156      * @return a Map of target-name to target
157      * @throws ConfigurationException if an error occurs
158      */

159     private HashMap JavaDoc configureTargets( final Configuration[] targets )
160         throws ConfigurationException
161     {
162         final HashMap JavaDoc targetSet = new HashMap JavaDoc();
163
164         for( int i = 0; i < targets.length; i++ )
165         {
166             final Configuration target = targets[ i ];
167             final String JavaDoc name = target.getAttribute( "name" );
168             String JavaDoc location = target.getAttribute( "location" ).trim();
169             final String JavaDoc format = target.getAttribute( "format", DEFAULT_FORMAT );
170             final boolean append = target.getAttributeAsBoolean( "append", true );
171
172             if( '/' == location.charAt( 0 ) )
173             {
174                 location = location.substring( 1 );
175             }
176
177             final AvalonFormatter formatter = new AvalonFormatter( format );
178
179             //Specify output location for logging
180
final File JavaDoc file = new File JavaDoc( m_baseDirectory, location );
181
182             //Setup logtarget
183
FileTarget logTarget = null;
184             try
185             {
186                 logTarget = new FileTarget( file.getAbsoluteFile(), append, formatter );
187             }
188             catch( final IOException JavaDoc ioe )
189             {
190                 final String JavaDoc message =
191                     "Error creating LogTarget named \"" + name + "\" for file " +
192                     file + ". (Reason: " + ioe.getMessage() + ").";
193                 throw new ConfigurationException( message, ioe );
194             }
195
196             targetSet.put( name, logTarget );
197         }
198
199         return targetSet;
200     }
201
202     /**
203      * Configure Logging categories.
204      *
205      * @param categories configuration data for categories
206      * @param targets a hashmap containing the already existing taregt
207      * @throws ConfigurationException if an error occurs
208      */

209     private void configureCategories( final Configuration[] categories, final HashMap JavaDoc targets )
210         throws ConfigurationException
211     {
212         for( int i = 0; i < categories.length; i++ )
213         {
214             final Configuration category = categories[ i ];
215             final String JavaDoc name = category.getAttribute( "name", "" );
216             final String JavaDoc target = category.getAttribute( "target" );
217             final String JavaDoc priorityName = category.getAttribute( "priority" );
218
219             final Logger logger =
220                 m_logkitLogger.getChildLogger( name );
221
222             final LogTarget logTarget = (LogTarget)targets.get( target );
223             if( null == target )
224             {
225                 final String JavaDoc message =
226                     "Unable to locate LogTarget named \"" + target +
227                     "\" for Logger named \"" + name + "\".";
228                 throw new ConfigurationException( message );
229             }
230
231             final Priority priority = Priority.getPriorityForName( priorityName );
232             if( !priority.getName().equals( priorityName ) )
233             {
234                 final String JavaDoc message =
235                     "Unknown priority \"" + priorityName + "\" for Logger named \"" +
236                     name + "\".";
237                 throw new ConfigurationException( message );
238             }
239
240             if( getLogger().isDebugEnabled() )
241             {
242                 final String JavaDoc message =
243                     "Creating a log category named \"" + name +
244                     "\" that writes to \"" + target + "\" target at priority \"" +
245                     priorityName + "\".";
246                 getLogger().debug( message );
247             }
248
249             if( name.equals( "" ) )
250             {
251                 m_logkitLogger.setPriority( priority );
252                 m_logkitLogger.setLogTargets( new LogTarget[] {logTarget} );
253             }
254             else
255             {
256                 logger.setPriority( priority );
257                 logger.setLogTargets( new LogTarget[]{logTarget} );
258             }
259         }
260     }
261 }
262
Popular Tags