excalibur-logger-2.1/ 40755 0 0 0 10304740432 11636 5 ustar 0 0 excalibur-logger-2.1/src/ 40755 0 0 0 10304740432 12425 5 ustar 0 0 excalibur-logger-2.1/src/java/ 40755 0 0 0 10304740432 13346 5 ustar 0 0 excalibur-logger-2.1/src/java/org/ 40755 0 0 0 10304740432 14135 5 ustar 0 0 excalibur-logger-2.1/src/java/org/apache/ 40755 0 0 0 10304740432 15356 5 ustar 0 0 excalibur-logger-2.1/src/java/org/apache/avalon/ 40755 0 0 0 10304740432 16636 5 ustar 0 0 excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/ 40755 0 0 0 10304740432 20614 5 ustar 0 0 excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/ 40755 0 0 0 10304740432 22073 5 ustar 0 0 excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/factory/ 40755 0 0 0 10304740432 23542 5 ustar 0 0 excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/logkit/ 40755 0 0 0 10304740432 23364 5 ustar 0 0 excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/util/ 40755 0 0 0 10304740432 23050 5 ustar 0 0 excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/log4j/ 40755 0 0 0 10304740432 23112 5 ustar 0 0 excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/decorator/ 40755 0 0 0 10304740432 24055 5 ustar 0 0 excalibur-logger-2.1/LICENSE.txt 100644 0 0 23637 10304740432 13611 0 ustar 0 0
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
excalibur-logger-2.1/project.properties 100644 0 0 1314 10304740431 15515 0 ustar 0 0 #
# Copyright 2004 The Apache Software Foundation
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
#
# See the License for the specific language governing permissions and
# limitations under the License.
#
avalon.buildsystem=${basedir}/../buildsystem
# gump integration
project.name = excalibur-logger
excalibur-logger-2.1/project.xml 100644 0 0 5764 10304740431 14136 0 ustar 0 0
* <jms id="name"> * <connection-factory>java:/TopicConectionFactory</connection-factory> * <destination type="topic|queue">jms/LogDestination</destination> * <message type="object|text"> * * -if type="text": * <property> * <category>CATEGORY</category> * <priority>PRIORITY</priority> * <time>TIME</time> * <rtime>RTIME</rtime> * <throwable>THROWABLE</throwable> * <hostname>HOSTNAME</hostname> * <static aux="234523454325">SYSTEM</static> * <context aux="principal">PRINCIPAL</context> * <context aux="ipaddress">IPADDRESS</context> * <context aux="username">USERNAME</context> * </property> * <format type="exteded">%7.7{priority} %5.5{time} [%8.8{category}] (%{context}): %{message}\n%{throwable}</format> * </message> * </jms> ** * @author Avalon Development Team * @version CVS $Revision: 1.7 $ $Date: 2004/03/10 13:54:50 $ */ public class JMSTargetFactory implements LogTargetFactory { public LogTarget createTarget( final Configuration configuration ) throws ConfigurationException { final String factoryName = configuration.getChild( "connection-factory", true ).getValue(); final Configuration destinationConf = configuration.getChild( "destination", true ); final String destinationName = destinationConf.getValue(); final String destinationType = destinationConf.getAttribute( "type", "topic" ); final Configuration messageConf = configuration.getChild( "message", true ); final MessageBuilder messageBuilder = getMessageBuilder( messageConf ); final ConnectionFactory factory; final Destination destination; final LogTarget logTarget; try { Context ctx = new InitialContext(); factory = (ConnectionFactory)ctx.lookup( factoryName ); destination = (Destination)ctx.lookup( destinationName ); } catch( NameNotFoundException nnfe ) { throw new ConfigurationException( "Cannot lookup object", nnfe ); } catch( NamingException ne ) { throw new ConfigurationException( "Cannot get naming context", ne ); } if( "queue".equals( destinationType ) ) { logTarget = new JMSQueueTarget( messageBuilder, (QueueConnectionFactory)factory, (Queue)destination ); } else { logTarget = new JMSTopicTarget( messageBuilder, (TopicConnectionFactory)factory, (Topic)destination ); } return logTarget; } private MessageBuilder getMessageBuilder( final Configuration configuration ) throws ConfigurationException { final String messageType = configuration.getAttribute( "type", "object" ); if( "text".equals( messageType ) ) { final Configuration[] propertyConf = configuration.getChild( "property", true ).getChildren(); final Configuration formatterConf = configuration.getChild( "format" ); final PropertyInfo[] properties = new PropertyInfo[ propertyConf.length ]; for( int i = 0; i < properties.length; i++ ) { final String name = propertyConf[ i ].getValue(); final int type = PropertyType.getTypeIdFor( propertyConf[ i ].getName() ); final String aux = propertyConf[ i ].getAttribute( "aux", null ); properties[ i ] = new PropertyInfo( name, type, aux ); } final Formatter formatter = getFormatter( formatterConf ); return new TextMessageBuilder( properties, formatter ); } return new ObjectMessageBuilder(); } protected Formatter getFormatter( final Configuration conf ) { Formatter formatter = null; if( null != conf ) { final FormatterFactory formatterFactory = new FormatterFactory(); formatter = formatterFactory.createFormatter( conf ); } return formatter; } } excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/factory/FileTargetFactory.java 100644 0 0 33513 10304740432 30105 0 ustar 0 0 /* * Copyright 2002-2005 The Apache Software Foundation * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avalon.excalibur.logger.factory; import java.io.File; import java.io.IOException; import java.util.StringTokenizer; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.avalon.framework.context.ContextException; import org.apache.log.LogTarget; import org.apache.log.format.Formatter; import org.apache.log.output.io.FileTarget; import org.apache.log.output.io.rotate.FileStrategy; import org.apache.log.output.io.rotate.OrRotateStrategy; import org.apache.log.output.io.rotate.RevolvingFileStrategy; import org.apache.log.output.io.rotate.RotateStrategy; import org.apache.log.output.io.rotate.RotateStrategyByDate; import org.apache.log.output.io.rotate.RotateStrategyBySize; import org.apache.log.output.io.rotate.RotateStrategyByTime; import org.apache.log.output.io.rotate.RotateStrategyByTimeOfDay; import org.apache.log.output.io.rotate.RotatingFileTarget; import org.apache.log.output.io.rotate.UniqueFileStrategy; /** * FileTargetFactory class. * * This factory is able to create different FileLogTargets according to the following * configuration syntax: * *
* <file id="foo"> * <filename>${context-key}/real-name/...</filename> * <format type="avalon|raw|pattern|extended">pattern to be used if needed</format> * <append>true|false</append> * <rotation type="revolving" init="5" max="10"> * * or * * <rotation type="unique" pattern="yyyy-MM-dd-hh-mm-ss" suffix=".log"> * <or> * <size>10000000</size> * <time>24:00:00</time> * <time>12:00:00</time> * </or> * </rotation> * </file> ** *
Some explanations about the Elements used in the configuration:
** %7.7{priority} %5.5{time} [%8.8{category}] (%{context}): %{message}\\n%{throwable} *
*The initial rotation * can be set to -1 in which case the system will first create the maximum * number of file rotations by selecting the next available rotation and thereafter * will overwrite the oldest log file. *
* Configuration syntax: *
* <socket-target id="target-id"> * <address hostname="hostname" port="4455" /> * </socket-target> ** *
* This factory creates a SocketOutputTarget object which will * TCP/IP socket to communicate with the server. The name of the target is specified by the * hostname attribute of the <address> element and the port by the port attribute. * In the config file above the formatting for the log messages is not embedded as it should * be specified on the server side *
* * * @author Avalon Development Team */ public class SocketTargetFactory extends AbstractTargetFactory { /** * Creates a log target based on Configuration * * @param conf Configuration requied for creating the log target * @throws ConfigurationException if something goes wrong while reading from * configuration */ public LogTarget createTarget( final Configuration conf ) throws ConfigurationException { final InetAddress address; final Configuration configChild = conf.getChild( "address", false ); if( null == configChild ) { throw new ConfigurationException( "target address not specified in the config" ); } try { address = InetAddress.getByName( configChild.getAttribute( "hostname" ) ); } catch( UnknownHostException uhex ) { throw new ConfigurationException( "Host specified in socket target adress is unknown!", uhex ); } final int port = configChild.getAttributeAsInteger( "port" ); try { return new SocketOutputTarget( address, port ); } catch( final IOException ioex ) { throw new ConfigurationException( "Failed to create target!", ioex.fillInStackTrace() ); } } } excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/factory/ConsoleTargetFactory.java 100644 0 0 5172 10304740432 30610 0 ustar 0 0 /* * Copyright 2002-2004 The Apache Software Foundation * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avalon.excalibur.logger.factory; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.log.LogTarget; import org.apache.log.format.Formatter; import org.apache.log.output.io.StreamTarget; /** * ConsoleTargetFactory class. * * This factory is able to create a console target which can be used for * debugging components. * ** <console id="console"> * <format type="avalon|raw|pattern|extended">pattern to be used if needed</format> * </console> ** *
Some explanations about the Elements used in the configuration:
** %7.7{priority} %5.5{time} [%8.8{category}] (%{context}): %{message}\\n%{throwable} *
** <jdbc id="database"> * <datasource>java:/LogTargetDataSource</datasource> * <normalized>true</normalized> * <table name="LOG"> * <category>CATEGORY</category> * <priority>PRIORITY</priority> * <message>MESSAGE</message> * <time>TIME</time> * <rtime>RTIME</rtime> * <throwable>THROWABLE</throwable> * <hostname>HOSTNAME</hostname> * <static aux="-">STATIC</static> * <context aux="principal">PRINCIPAL</context> * <context aux="ipaddress">IPADDRESS</context> * <context aux="username">USERNAME</context> * </table> * </jdbc> ** * @author Avalon Development Team * @version CVS $Revision: 1.10 $ $Date: 2004/03/10 13:54:50 $ */ public class JDBCTargetFactory implements LogTargetFactory { public LogTarget createTarget( Configuration configuration ) throws ConfigurationException { final String dataSourceName = configuration.getChild( "datasource", true ).getValue(); final boolean normalized = configuration.getChild( "normalized", true ).getValueAsBoolean( false ); final Configuration tableConfiguration = configuration.getChild( "table" ); final String table = tableConfiguration.getAttribute( "name" ); final Configuration[] conf = tableConfiguration.getChildren(); final ColumnInfo[] columns = new ColumnInfo[ conf.length ]; for( int i = 0; i < conf.length; i++ ) { final String name = conf[ i ].getValue(); final int type = ColumnType.getTypeIdFor( conf[ i ].getName() ); final String aux = conf[ i ].getAttribute( "aux", null ); columns[ i ] = new ColumnInfo( name, type, aux ); } final DataSource dataSource; try { Context ctx = new InitialContext(); dataSource = (DataSource)ctx.lookup( dataSourceName ); } catch( final NamingException ne ) { throw new ConfigurationException( "Cannot lookup data source", ne ); } final LogTarget logTarget; if( normalized ) { logTarget = new NormalizedJDBCTarget( dataSource, table, columns ); } else { logTarget = new DefaultJDBCTarget( dataSource, table, columns ); } return logTarget; } } excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/factory/SMTPTargetFactory.java 100644 0 0 22546 10304740432 30015 0 ustar 0 0 /* * Copyright 2002-2004 The Apache Software Foundation * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avalon.excalibur.logger.factory; import javax.mail.Address; import javax.mail.Session; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.avalon.framework.context.ContextException; import org.apache.avalon.framework.parameters.Parameters; import org.apache.log.LogTarget; import org.apache.log.format.Formatter; import org.apache.log.output.net.SMTPOutputLogTarget; /** * SMTPTargetFactory class. * *
* This factory creates SMTPOutputLogTarget's. It uses the
* context-key attribute to locate the required JavaMail Session from
* the Context object passed to this factory. The default context-key
* is session-context
.
*
*
* <smtp id="target-id" context-key="context-key-to-session-object"> * <format type="raw|pattern|extended">pattern to be used if needed</format> * <to>address-1@host</to> * <to>address-N@host</to> * <from>address@host</from> * <subject>subject line</subject> * <maximum-size>number</maximum-size> * <maximum-delay-time>seconds</maximum-delay-time> * </smtp> ** * The Factory will look for a javax.mail.Session instance in the Context using * the specified context-key. If your needs are simple, then it is also possible * to define a Session within the configuration by replacing the context-key * attribute with a session child element as follows: *
*
* <session> * <parameter name="mail.host" value="mail.apache.com"/> * </session> ** The Session is created by calling Session.getInstance, providing a Properties * object whose values are defined in the above block. Any valid name value * pair can be specified. *
* *
* %7.7{priority} %5.5{time} [%8.8{category}] (%{context}): %{message}\\n%{throwable} *
*
*
* @author Avalon Development Team
* @version CVS $Revision: 1.14 $ $Date: 2004/03/10 13:54:50 $
* @since 4.1
*/
public class SMTPTargetFactory
extends AbstractTargetFactory
{
/**
* Creates an SMTPOutputLogTarget based on a Configuration
*
* @param config a Configuration
instance
* @return LogTarget
instance
* @exception ConfigurationException if an error occurs
*/
public final LogTarget createTarget( final Configuration config )
throws ConfigurationException
{
try
{
return new SMTPOutputLogTarget(
getSession( config ),
getToAddresses( config ),
getFromAddress( config ),
getSubject( config ),
getMaxSize( config ),
getMaxDelayTime( config ),
getFormatter( config )
);
}
catch( final ContextException ce )
{
throw new ConfigurationException( "Cannot find Session object in " +
"application context", ce );
}
catch( final AddressException ae )
{
throw new ConfigurationException( "Cannot create address", ae );
}
}
/**
* Helper method to obtain a formatter for this factory.
*
* @param config a Configuration
instance
* @return a Formatter
instance
*/
protected Formatter getFormatter( final Configuration config )
{
final Configuration confFormat = config.getChild( "format" );
if( null != confFormat )
{
final FormatterFactory formatterFactory = new FormatterFactory();
return formatterFactory.createFormatter( confFormat );
}
return null;
}
/**
* Helper method to create a JavaMail Session
object.
*
* If your session object has simple needs, you can nest a configuration element
* named session containing name-value pairs that are passed to
* Session.getInstance()
.
*
* If no configuration is found, a Session
will be loaded from this
* factory's context object.
*
* You can override this method if you need ot obtain the JavaMail session using
* some other means.
*
* @return JavaMail Session
instance
* @exception ContextException if an error occurs
* @exception ConfigurationException if invalid session configuration
*/
protected Session getSession( Configuration config )
throws ContextException, ConfigurationException
{
final Configuration sessionConfig = config.getChild( "session", false );
if( null == sessionConfig )
{
final String contextkey =
m_configuration.getAttribute( "context-key", "session-context" );
if( m_context == null )
{
throw new ConfigurationException( "Context not available" );
}
return (Session)m_context.get( contextkey );
}
else
{
return Session.getInstance(
Parameters.toProperties(
Parameters.fromConfiguration( sessionConfig ) ) );
}
}
/**
* Helper method to obtain the subject line to use from the given
* configuration object.
*
* @param config a Configuration
instance
* @return subject line
*/
private String getSubject( Configuration config )
throws ConfigurationException
{
return config.getChild( "subject" ).getValue();
}
/**
* Helper method to obtain the maximum size any particular SMTP
* message can be from a given configuration object.
*
* @param config a Configuration
instance
* @return maximum SMTP mail size
*/
private int getMaxSize( Configuration config )
throws ConfigurationException
{
return config.getChild( "maximum-size" ).getValueAsInteger( 1 );
}
/**
* Helper method to obtain the maximum delay time any particular SMTP
* message can be queued from a given configuration object.
*
* @param config a Configuration
instance
* @return maximum SMTP mail delay time
*/
private int getMaxDelayTime( Configuration config )
throws ConfigurationException
{
return config.getChild( "maximum-delay-time" ).getValueAsInteger( 0 );
}
/**
* Helper method to obtain the to address/es from the
* given configuration.
*
* @param config Configuration
instance
* @return an array of Address
objects
* @exception ConfigurationException if a configuration error occurs
* @exception AddressException if a addressing error occurs
*/
private Address[] getToAddresses( final Configuration config )
throws ConfigurationException, AddressException
{
final Configuration[] toAddresses = config.getChildren( "to" );
final Address[] addresses = new Address[ toAddresses.length ];
for( int i = 0; i < toAddresses.length; ++i )
{
addresses[ i ] = createAddress( toAddresses[ i ].getValue() );
}
return addresses;
}
/**
* Helper method to obtain the from address from
* the given configuration.
*
* @param config a Configuration
instance
* @return an Address
object
* @exception ConfigurationException if a configuration error occurs
* @exception AddressException if a addressing error occurs
*/
private Address getFromAddress( final Configuration config )
throws ConfigurationException, AddressException
{
return createAddress( config.getChild( "from" ).getValue() );
}
/**
* Helper factory method to create a new Address
* object. Override this method in a subclass if you wish to
* create other Address types rather than
* InternetAddress
(eg. NewsAddress
)
*
* @param address address string from configuration
* @return an Address
object
* @exception AddressException if an error occurs
*/
protected Address createAddress( final String address )
throws AddressException
{
return new InternetAddress( address );
}
}
excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/factory/StreamTargetFactory.java 100644 0 0 7737 10304740432 30452 0 ustar 0 0 /*
* Copyright 2002-2004 The Apache Software Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avalon.excalibur.logger.factory;
import java.io.OutputStream;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.context.Context;
import org.apache.avalon.framework.context.ContextException;
import org.apache.avalon.framework.context.Contextualizable;
import org.apache.avalon.framework.context.DefaultContext;
import org.apache.log.LogTarget;
import org.apache.log.format.Formatter;
import org.apache.log.output.io.StreamTarget;
/**
* TargetFactory for {@link org.apache.log.output.io.StreamTarget}.
*
* This factory is able to create different StreamTargets according to the following
* configuration syntax:
*
* <stream id="foo"> * <stream>stream-context-name</stream> * <format type="raw|pattern|extended">pattern to be used if needed</format> * </stream> ** *
The "stream-context-name" is the name of an java.io.OutputStream
that
* is fetched in the context. This context contains two predefined streams :
*
System.out
" for the system output stream,System.err
" for the system error stream.The syntax of "format" is the same as in FileTargetFactory
.
* * <async-target id="target-id" queue-size=".." priority="MIN|NORM|MAX|n"> * <any-target-definition/> * </async-target> * **
* This factory creates a AsyncLogTarget object with a specified queue-size * attribute (which defaults to what the AsyncLogTarget uses if absent). * The LogTarget to wrap is described in a child element of the configuration (in * the sample above named as <any-target-definition/>). * The Thread of the created AsyncLogTarget will have a priority specified by the * priotity attribute (which defaults to Thread.MIN_PRIORITY). The priority values * corresponds to those defined in the Thread class which are: *
**
* MIN=Thread.MIN_PRIORITY* * * @author Avalon Development Team * @version CVS $Revision: 1.8 $ $Date: 2004/03/10 13:54:50 $ * @since 4.0 */ public final class AsyncLogTargetFactory extends AbstractTargetFactory implements LogTargetFactoryManageable { /** The LogTargetFactoryManager */ protected LogTargetFactoryManager m_logTargetFactoryManager; /** * create a LogTarget based on a Configuration */ public final LogTarget createTarget( final Configuration configuration ) throws ConfigurationException { final int queuesize = configuration.getAttributeAsInteger( "queue-size", -1 ); final Configuration config = configuration.getChildren()[ 0 ]; final LogTargetFactory factory = m_logTargetFactoryManager.getLogTargetFactory( config.getName() ); final LogTarget target = factory.createTarget( config ); final AsyncLogTarget asyncTarget; if( queuesize == -1 ) { asyncTarget = new AsyncLogTarget( target ); } else { asyncTarget = new AsyncLogTarget( target, queuesize ); } final String priority = configuration.getAttribute( "priority", null ); final int threadPriority; if( "MIN".equalsIgnoreCase( priority ) ) { threadPriority = Thread.MIN_PRIORITY; } else if( "NORM".equalsIgnoreCase( priority ) ) { threadPriority = Thread.NORM_PRIORITY; } else { threadPriority = configuration.getAttributeAsInteger( "priority", 1 ); } final Thread thread = new Thread( asyncTarget ); thread.setPriority( threadPriority ); thread.setDaemon( true ); thread.start(); return asyncTarget; } /** * get the LogTargetFactoryManager */ public final void setLogTargetFactoryManager( LogTargetFactoryManager logTargetFactoryManager ) { m_logTargetFactoryManager = logTargetFactoryManager; } } ././@LongLink 100644 0 0 152 10304740432 10246 L ustar 0 0 excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/factory/PriorityFilterTargetFactory.java excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/factory/PriorityFilterTargetFactory100644 0 0 7414 10304740432 31256 0 ustar 0 0 /* * Copyright 2002-2004 The Apache Software Foundation * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avalon.excalibur.logger.factory; import org.apache.avalon.excalibur.logger.LogTargetFactory; import org.apache.avalon.excalibur.logger.LogTargetFactoryManageable; import org.apache.avalon.excalibur.logger.LogTargetFactoryManager; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.log.LogTarget; import org.apache.log.Priority; import org.apache.log.output.PriorityFilteringTarget; /** * PriorityFilterTargetFactory class. * * This factory creates LogTargets with a wrapped PriorityFilteringTarget * around it: * *
* NORM=Thread.NORM_PRIORITY
* MAX=Thread.MAX_PRIORITY
* number=priority number (see class java.lang.Thread)
*
* * <priority-filter id="target-id" log-level="ERROR"> * <any-target-definition/> * ... * <any-target-definition/> * </priority-filter> * **
* This factory creates a PriorityFilteringTarget object with a logging Priority set * to the value of the log-level attribute (which defaults to INFO if absent). * The LogTarget to filter is described in child elements of the configuration (in * the sample above named as <any-target-definition/>). *
* * @author Avalon Development Team * @version CVS $Revision: 1.10 $ $Date: 2004/03/13 03:48:55 $ * @since 4.0 */ public final class PriorityFilterTargetFactory extends AbstractTargetFactory implements LogTargetFactoryManageable { /** The LogTargetFactoryManager */ protected LogTargetFactoryManager m_logTargetFactoryManager; /** * create a LogTarget based on a Configuration */ public final LogTarget createTarget( final Configuration configuration ) throws ConfigurationException { final String loglevel = configuration.getAttribute( "log-level", "INFO" ); getLogger().debug( "loglevel is " + loglevel ); final boolean closeWrappedTargets = configuration.getAttributeAsBoolean( "close-wrapped-targets", true ); final PriorityFilteringTarget filter = new PriorityFilteringTarget( Priority.getPriorityForName( loglevel ), closeWrappedTargets ); final Configuration[] configs = configuration.getChildren(); for( int i = 0; i < configs.length; i++ ) { final LogTargetFactory factory = m_logTargetFactoryManager.getLogTargetFactory( configs[ i ].getName() ); if( null == factory ) { throw new ConfigurationException( "Unknown target type '" + configs[ i ].getName() + "' at " + configs[ i ].getLocation() ); } getLogger().debug( "creating target " + configs[ i ].getName() + ": " + configs[ i ].toString() ); final LogTarget logtarget = factory.createTarget( configs[ i ] ); filter.addTarget( logtarget ); } return filter; } /** * get the LogTargetFactoryManager */ public final void setLogTargetFactoryManager( LogTargetFactoryManager logTargetFactoryManager ) { m_logTargetFactoryManager = logTargetFactoryManager; } } excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/factory/LF5TargetFactory.java 100644 0 0 3775 10304740432 27603 0 ustar 0 0 /* * Copyright 2002-2004 The Apache Software Foundation * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avalon.excalibur.logger.factory; import org.apache.avalon.excalibur.logger.LogTargetFactory; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.log.LogTarget; import org.apache.log.output.lf5.LF5LogTarget; /** * A factory for the LogFactor5 * Swing GUI. ** Configuration : *
* <lf5 id="target-id"> * <NDC-format type="raw|pattern|extended">pattern to be used</NDC-format> * </lf5> ** * The optional "NDC-pattern" configuration defines the pattern that will be used to * format the log event for display on the "NDC" line in the Swing GUI. * * @author Avalon Development Team * @version CVS $Revision: 1.8 $ $Date: 2004/03/10 13:54:50 $ */ public class LF5TargetFactory implements LogTargetFactory { public LogTarget createTarget( final Configuration configuration ) throws ConfigurationException { LF5LogTarget result = new LF5LogTarget(); Configuration child = configuration.getChild( "NDC-pattern", false ); if( null != child ) { result.setNDCFormatter( new FormatterFactory().createFormatter( child ) ); } return result; } } excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/factory/ServletTargetFactory.java 100644 0 0 6607 10304740432 30636 0 ustar 0 0 /* * Copyright 2002-2004 The Apache Software Foundation * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avalon.excalibur.logger.factory; import javax.servlet.ServletContext; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.avalon.framework.context.ContextException; import org.apache.log.LogTarget; import org.apache.log.format.Formatter; import org.apache.log.output.ServletOutputLogTarget; /** * ServletTargetFactory class. * * This factory creates a ServletOutputLogTargets. It uses the * context-key attribute to locate the required ServletContext from * the Context object passed to this factory. The default context-key * is
servlet-context
.
*
* * * <servlet id="target-id" context-key="context-key-to-servlet-context-object"> * <format type="raw|pattern|extended">pattern to be used if needed</format> * </servlet> * **
* %7.7{priority} %5.5{time} [%8.8{category}] (%{context}): %{message}\\n%{throwable} *
** Configuration syntax: *
* <datagram-target id="target-id"> * <address hostname="hostname" port="4455" /> * <format type="extended"> * %7.7{priority} %23.23{time:yyyy-MM-dd HH:mm:ss:SSS} [%25.25{category}] : %{message}\n%{throwable} * </format> * </datagram-target> ** *
* This factory creates a DatagramOutputTarget object which will * sends datagrams to the specified address. The name of the target is specified by the hostname attribute * of the <address> element and the port by the port attribute.The <address> element * wraps the format to output the log. *
* * * @author Avalon Development Team */ public class DatagramTargetFactory extends AbstractTargetFactory { /** Default format */ private static final String FORMAT = "%7.7{priority} %5.5{time} [%8.8{category}] (%{context}): %{message}\\n%{throwable}"; /** * Create a LogTarget based on a Configuration */ public LogTarget createTarget( final Configuration conf ) throws ConfigurationException { InetAddress address; final Configuration configChild = conf.getChild( "address", false ); if( null == configChild ) { throw new ConfigurationException( "target address not specified in the config" ); } try { address = InetAddress.getByName( configChild.getAttribute( "hostname" ) ); } catch( UnknownHostException uhex ) { throw new ConfigurationException( "Host specified in datagram target adress is unknown!", uhex ); } int port = configChild.getAttributeAsInteger( "port" ); final Formatter formatter = getFormatter( conf.getChild( "format", false ) ); try { return new DatagramOutputTarget( address, port, formatter ); } catch( IOException ioex ) { throw new ConfigurationException( "Failed to create target!", ioex ); } } /** * Returns the Formatter * * @param conf Configuration for the formatter */ protected Formatter getFormatter( final Configuration conf ) { final String type = conf.getAttribute( "type", "pattern" ); final String format = conf.getValue( FORMAT ); if( "extended".equals( type ) ) { return new ExtendedPatternFormatter( format ); } else if( "raw".equals( type ) ) { return new RawFormatter(); } /** default formatter */ return new PatternFormatter( format ); } } excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/factory/FormatterFactory.java 100644 0 0 5633 10304740432 30004 0 ustar 0 0 /* * Copyright 2002-2004 The Apache Software Foundation * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avalon.excalibur.logger.factory; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.logger.AvalonFormatter; import org.apache.log.format.ExtendedPatternFormatter; import org.apache.log.format.Formatter; import org.apache.log.format.PatternFormatter; import org.apache.log.format.RawFormatter; import org.apache.log.format.SyslogFormatter; import org.apache.log.format.XMLFormatter; /** * Factory for Formatters. * * @author Avalon Development Team */ public class FormatterFactory { //Format of default formatter private static final String FORMAT = "%7.7{priority} %5.5{time} [%8.8{category}] (%{context}): %{message}\\n%{throwable}"; public Formatter createFormatter( final Configuration conf ) { final String type = conf.getAttribute( "type", "pattern" ); final String format = conf.getValue( FORMAT ); if( "avalon".equals( type ) ) { final int depth = conf.getAttributeAsInteger( "depth", AvalonFormatter.DEFAULT_STACK_DEPTH ); final boolean printCascading = conf.getAttributeAsBoolean( "cascading", AvalonFormatter.DEFAULT_PRINT_CASCADING ); return new AvalonFormatter( format, depth, printCascading ); } else if( "extended".equals( type ) ) { /*Normally ExtendPatternFormatter would look for callers *of Logger.class. But when Excalibur Logger provides a *facade, the user class/method is actually one-level deeper. *We therefore create the pattern-formatter with an *additional depth-offset of 1. */ return new ExtendedPatternFormatter( format, 1 ); } else if( "raw".equals( type ) ) { return new RawFormatter(); } else if( "xml".equals( type ) ) { return new XMLFormatter(); } else if( "syslog".equals( type ) ) { return new SyslogFormatter(); } else if( "pattern".equals( type ) ) { return new PatternFormatter( format ); } else { throw new IllegalArgumentException( "Unknown formatter type " + type ); } } } excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/factory/AbstractTargetFactory.java 100644 0 0 4114 10304740432 30744 0 ustar 0 0 /* * Copyright 2002-2004 The Apache Software Foundation * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avalon.excalibur.logger.factory; import org.apache.avalon.excalibur.logger.LogTargetFactory; import org.apache.avalon.framework.configuration.Configurable; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.avalon.framework.context.Context; import org.apache.avalon.framework.context.ContextException; import org.apache.avalon.framework.context.Contextualizable; import org.apache.avalon.framework.logger.AbstractLogEnabled; /** * AbstractTargetFactory class. * * This factory implements basic functionality for LogTargetFactories * * @author Avalon Development Team * @version CVS $Revision: 1.8 $ $Date: 2004/03/10 13:54:50 $ * @since 4.0 */ public abstract class AbstractTargetFactory extends AbstractLogEnabled implements LogTargetFactory, Configurable, Contextualizable { /** The Configuration object */ protected Configuration m_configuration; /** The Context object */ protected Context m_context; /** * Get the Configuration object */ public void configure( Configuration configuration ) throws ConfigurationException { m_configuration = configuration; } /** * Get the Context object */ public void contextualize( Context context ) throws ContextException { m_context = context; } } excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/logkit/LogKitConfHelper.java 100644 0 0 24253 10304740432 27511 0 ustar 0 0 /* * Copyright 2002-2004 The Apache Software Foundation * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avalon.excalibur.logger.logkit; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.apache.avalon.excalibur.logger.DefaultLogTargetFactoryManager; import org.apache.avalon.excalibur.logger.DefaultLogTargetManager; import org.apache.avalon.excalibur.logger.LogTargetFactoryManager; import org.apache.avalon.excalibur.logger.LogTargetManager; import org.apache.avalon.excalibur.logger.util.LoggerUtil; import org.apache.avalon.framework.activity.Disposable; import org.apache.avalon.framework.configuration.Configurable; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.avalon.framework.container.ContainerUtil; import org.apache.avalon.framework.context.Context; import org.apache.avalon.framework.context.ContextException; import org.apache.avalon.framework.context.Contextualizable; import org.apache.avalon.framework.logger.AbstractLogEnabled; import org.apache.log.Hierarchy; import org.apache.log.LogTarget; import org.apache.log.Priority; import org.apache.log.util.Closeable; /** * Tie this object to a LoggerManagerTee, give it the Hierachy * that LogKitAdapter operates upon and it will populate it * from the Configuration object passed via configure(). * Note: this class assumes that this is a new Hierarchy, * freshly created with new Hierarchy() not populated before. * * @author Avalon Development Team * @version CVS $Revision: 1.6 $ $Date: 2004/03/10 13:54:51 $ * @since 4.0 */ public class LogKitConfHelper extends AbstractLogEnabled implements Contextualizable, Configurable, Disposable { /* The hierarchy to operate upon */ private final Hierarchy m_hierarchy; /* Creates an instance of LogKitLoggerHelper. */ public LogKitConfHelper( final Hierarchy hierarchy ) { if ( hierarchy == null ) throw new NullPointerException( "hierarchy" ); m_hierarchy = hierarchy; } /** Set of log targets */ final private Set m_targets = new HashSet(); /** The context object */ private Context m_context; /** * Reads a context object that will be supplied to the log target factory manager. * * @param context The context object. * @throws ContextException if the context is malformed */ public final void contextualize( final Context context ) throws ContextException { m_context = context; } /** * Populates the underlyingHierarchy
.
*
* @param configuration The configuration object.
* @throws ConfigurationException if the configuration is malformed
*/
public final void configure( final Configuration configuration )
throws ConfigurationException
{
final Configuration factories = configuration.getChild( "factories" );
final LogTargetFactoryManager targetFactoryManager = setupTargetFactoryManager( factories );
final Configuration targets = configuration.getChild( "targets" );
final LogTargetManager targetManager = setupTargetManager( targets, targetFactoryManager );
final Configuration categories = configuration.getChild( "categories" );
setupLoggers( targetManager,
null,
categories,
true,
categories.getAttributeAsBoolean( "additive", false ) );
}
/**
* Setup a LogTargetFactoryManager
*
* @param configuration The configuration object.
* @throws ConfigurationException if the configuration is malformed
*/
private final LogTargetFactoryManager setupTargetFactoryManager(
final Configuration configuration )
throws ConfigurationException
{
final DefaultLogTargetFactoryManager targetFactoryManager = new DefaultLogTargetFactoryManager();
ContainerUtil.enableLogging( targetFactoryManager, getLogger() );
try
{
ContainerUtil.contextualize( targetFactoryManager, m_context );
}
catch( final ContextException ce )
{
throw new ConfigurationException( "cannot contextualize default factory manager", ce );
}
ContainerUtil.configure( targetFactoryManager, configuration );
return targetFactoryManager;
}
/**
* Setup a LogTargetManager
*
* @param configuration The configuration object.
* @throws ConfigurationException if the configuration is malformed
*/
private final LogTargetManager setupTargetManager( final Configuration configuration,
final LogTargetFactoryManager targetFactoryManager )
throws ConfigurationException
{
final DefaultLogTargetManager targetManager = new DefaultLogTargetManager();
ContainerUtil.enableLogging( targetManager, getLogger() );
targetManager.setLogTargetFactoryManager( targetFactoryManager );
ContainerUtil.configure( targetManager, configuration );
return targetManager;
}
/**
* Setup Loggers
*
* @param parentElement The array object of configurations for categories.
* @param root shows if we're processing the root of the configuration
* @throws ConfigurationException if the configuration is malformed
*/
private final void setupLoggers( final LogTargetManager targetManager,
final String parentCategory,
final Configuration parentElement,
boolean root,
final boolean defaultAdditive )
throws ConfigurationException
{
boolean rootLoggerConfigured = false;
final Configuration[] categories = parentElement.getChildren( "category" );
if( null != categories )
{
for( int i = 0; i < categories.length; i++ )
{
final Configuration category = categories[ i ];
final String name = category.getAttribute( "name" );
final String loglevel = category.getAttribute( "log-level" ).toUpperCase();
final boolean additive = category.
getAttributeAsBoolean( "additive", defaultAdditive );
final Configuration[] targets = category.getChildren( "log-target" );
final LogTarget[] logTargets = new LogTarget[ targets.length ];
for( int j = 0; j < targets.length; j++ )
{
final String id = targets[ j ].getAttribute( "id-ref" );
logTargets[ j ] = targetManager.getLogTarget( id );
if( !m_targets.contains( logTargets[ j ] ) )
{
m_targets.add( logTargets[ j ] );
}
}
final String fullCategory;
final org.apache.log.Logger logger;
if ( "".equals( name ) )
{
if ( !root )
{
final String message = "'category' element with empty name not " +
"at the root level: " + category.getLocation();
throw new ConfigurationException( message );
}
if ( logTargets.length == 0 )
{
final String message = "At least one log-target should be " +
"specified for the root category " + category.getLocation();
throw new ConfigurationException( message );
}
fullCategory = null;
logger = m_hierarchy.getRootLogger();
rootLoggerConfigured = true;
}
else
{
fullCategory = LoggerUtil.getFullCategoryName( parentCategory, name );
logger = m_hierarchy.getLoggerFor( fullCategory );
}
if( getLogger().isDebugEnabled() )
{
/**
* We have to identify ourselves now via 'LogKitConfHelper:'
* because we are likely to be logging to a shared bootstrap
* logger, not to a dedicated category Logger.
*/
final String message = "LogKitConfHelper: adding logger for category '" +
( fullCategory != null ? fullCategory : "" ) + "'";
getLogger().debug( message );
}
logger.setPriority( Priority.getPriorityForName( loglevel ) );
logger.setLogTargets( logTargets );
logger.setAdditivity( additive );
setupLoggers( targetManager, fullCategory, category, false, defaultAdditive );
}
}
if ( root && !rootLoggerConfigured )
{
final String message =
"No configuration for root category (LogKitAdapter
to operate
* of a certain LogKit Hierarchy
.
*/
public LogKitAdapter( final Hierarchy hierarchy )
{
if ( hierarchy == null ) throw new NullPointerException( "hierarchy" );
m_hierarchy = hierarchy;
}
/**
* Return the Logger for the specified category.
* * * In LogKit getRootLogger() and getLoggerFor("") * unless the logger for category "" has been explicitly * configured return identically configured but different * loggers. * *
* Our LogKitConfHelper configures getRootLogger(), not getLoggerFor(""). * We think this is a reasonable behavior and expect that LogKit * Hierarchies configured by other means then LogKitConfHelper are * configured in the same way. * *
* This justifies our decision to return getRootLogger() when given * "" category name. */ public Logger getLoggerForCategory( final String categoryName ) { if ( categoryName == null || categoryName.length() == 0 ) { return getDefaultLogger(); } else { return new LogKitLogger( m_hierarchy.getLoggerFor( categoryName ) ); } } /** * Return the default Logger. This is basically the same * as getting the Logger for the "" category. */ public Logger getDefaultLogger() { return new LogKitLogger( m_hierarchy.getRootLogger() ); } } excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/LogTargetManager.java 100644 0 0 2045 10304740432 26217 0 ustar 0 0 /* * Copyright 2002-2004 The Apache Software Foundation * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avalon.excalibur.logger; import org.apache.log.LogTarget; /** * LogTargetManager Interface. * * @author Avalon Development Team * @version CVS $Revision: 1.7 $ $Date: 2004/03/10 13:54:50 $ * @since 4.0 */ public interface LogTargetManager { /** * Find a logger based on a category name. */ LogTarget getLogTarget( String targetId ); } excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/LogKitManageable.java 100644 0 0 2365 10304740432 26167 0 ustar 0 0 /* * Copyright 2002-2004 The Apache Software Foundation * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avalon.excalibur.logger; /** * LogKitManageable Interface, use this to set the LogKitManagers for child * Components. * * @author Avalon Development Team * @version CVS $Revision: 1.8 $ $Date: 2004/03/10 13:54:50 $ * @since 4.0 */ public interface LogKitManageable { /** * Sets the LogKitManager for child components. Can be for special * purpose components, however it is used mostly internally. * * @param logKitManager The LogKitManager fot child components. */ void setLogKitManager( final LogKitManager logKitManager ); } ././@LongLink 100644 0 0 145 10304740432 10250 L ustar 0 0 excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/DefaultLogTargetFactoryManager.java excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/DefaultLogTargetFactoryManager.java100644 0 0 13653 10304740432 31103 0 ustar 0 0 /* * Copyright 2002-2004 The Apache Software Foundation * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avalon.excalibur.logger; import java.util.HashMap; import java.util.Map; import org.apache.avalon.framework.configuration.Configurable; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.avalon.framework.container.ContainerUtil; import org.apache.avalon.framework.context.Context; import org.apache.avalon.framework.context.ContextException; import org.apache.avalon.framework.context.Contextualizable; import org.apache.avalon.framework.logger.AbstractLogEnabled; /** * Default LogTargetFactoryManager implementation. It populates the LogTargetFactoryManager * from a configuration file. * * @author Avalon Development Team * @version CVS $Revision: 1.15 $ $Date: 2004/03/10 13:54:50 $ * @since 4.0 */ public class DefaultLogTargetFactoryManager extends AbstractLogEnabled implements LogTargetFactoryManager, Contextualizable, Configurable { /** Map for name to logger mapping */ private final Map m_factories = new HashMap(); /** The context object */ private Context m_context; /** * The classloader to use to load target factorys. */ private ClassLoader m_classLoader; /** * Retrieves a LogTargetFactory from a name. Usually * the factory name refers to a element name. If * this LogTargetFactoryManager does not have the match a null * will be returned. * * @param factoryName The name of a configured LogTargetFactory. * @return the LogTargetFactory or null if none is found. */ public final LogTargetFactory getLogTargetFactory( final String factoryName ) { return (LogTargetFactory)m_factories.get( factoryName ); } /** * Reads a context object. * * @param context The context object. */ public final void contextualize( final Context context ) { m_context = context; try { m_classLoader = (ClassLoader)m_context.get( ClassLoader.class.getName() ); } catch( ContextException ce ) { try { m_classLoader = (ClassLoader)m_context.get( "classloader" ); } catch( ContextException e ) { m_classLoader = Thread.currentThread().getContextClassLoader(); } } } /** * Reads a configuration object and creates the category mapping. * * @param configuration The configuration object. * @throws ConfigurationException if the configuration is malformed */ public final void configure( final Configuration configuration ) throws ConfigurationException { final Configuration[] confs = configuration.getChildren( "factory" ); for( int i = 0; i < confs.length; i++ ) { final String factoryClass = confs[ i ].getAttribute( "class" ); final String factoryType = confs[ i ].getAttribute( "type" ); final LogTargetFactory logTargetFactory; try { Class clazz = null; try { clazz = m_classLoader.loadClass( factoryClass ); } catch( final ClassNotFoundException cnfe ) { clazz = getClass().getClassLoader().loadClass( factoryClass ); } logTargetFactory = (LogTargetFactory)clazz.newInstance(); } catch( final ClassNotFoundException cnfe ) { final String message = "Cannot instantiate LogTargetFactory class " + factoryClass; throw new ConfigurationException( message, cnfe ); } catch( final InstantiationException ie ) { final String message = "Cannot instantiate LogTargetFactory class " + factoryClass; throw new ConfigurationException( message, ie ); } catch( final IllegalAccessException iae ) { final String message = "Cannot access LogTargetFactory class " + factoryClass; throw new ConfigurationException( message, iae ); } ContainerUtil.enableLogging( logTargetFactory, getLogger() ); try { ContainerUtil.contextualize( logTargetFactory, m_context ); } catch( final ContextException ce ) { final String message = "Cannot contextualize LogTargetFactory " + factoryClass; throw new ConfigurationException( message, ce ); } ContainerUtil.configure( logTargetFactory, confs[ i ] ); if( logTargetFactory instanceof LogTargetFactoryManageable ) { ( (LogTargetFactoryManageable)logTargetFactory ).setLogTargetFactoryManager( this ); } if( getLogger().isDebugEnabled() ) { final String message = "Added new LogTargetFactory of type " + factoryType; getLogger().debug( message ); } m_factories.put( factoryType, logTargetFactory ); } } } excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/LoggerLoggerManager.java 100644 0 0 2400 10304740432 26701 0 ustar 0 0 /* * Copyright 2002-2004 The Apache Software Foundation * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avalon.excalibur.logger; import org.apache.avalon.framework.logger.Logger; /** * A LoggerManager that operates off of an existing Logger instance. * * @author Avalon Development Team */ public class LoggerLoggerManager implements LoggerManager { private final Logger logger; public LoggerLoggerManager( Logger logger ) { this.logger = logger; } public Logger getLoggerForCategory( String categoryName ) { return logger.getChildLogger( categoryName ); } public Logger getDefaultLogger() { return logger; } } excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/LogKitManager.java 100644 0 0 2512 10304740432 25517 0 ustar 0 0 /* * Copyright 2002-2004 The Apache Software Foundation * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avalon.excalibur.logger; import org.apache.log.Hierarchy; import org.apache.log.Logger; /** * LogKitManager Interface. * * @deprecated we should use the new LoggerManager interface that directly * supports the new framework Logger interface. * * @author Avalon Development Team * @version CVS $Revision: 1.7 $ $Date: 2004/03/10 13:54:50 $ */ public interface LogKitManager { /** * Find a logger based on a category name. */ Logger getLogger( String categoryName ); /** * Retrieve Hierarchy for Loggers configured by the system. * * @return the Hierarchy */ Hierarchy getHierarchy(); } excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/Facade.java 100644 0 0 6557 10304740432 24213 0 ustar 0 0 /* * Copyright 2002-2004 The Apache Software Foundation * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avalon.excalibur.logger; import org.apache.avalon.excalibur.logger.LoggerManager; import org.apache.avalon.excalibur.logger.logkit.LogKitAdapter; import org.apache.avalon.excalibur.logger.logkit.LogKitLoggerHelper; import org.apache.avalon.excalibur.logger.logkit.LogKitConfHelper; import org.apache.avalon.excalibur.logger.log4j.Log4JConfAdapter; import org.apache.avalon.excalibur.logger.decorator.LogToSelfDecorator; import org.apache.avalon.excalibur.logger.decorator.PrefixDecorator; import org.apache.avalon.excalibur.logger.decorator.CachingDecorator; import org.apache.avalon.excalibur.logger.util.LoggerManagerTee; import org.apache.log.Hierarchy; /** * A facade to the modularized *LoggerManager building system. * Add methods here to create LoggerManagers to your preference. * * @author Avalon Development Team * @version CVS $Revision: 1.3 $ $Date: 2004/03/10 13:54:50 $ * @since 4.0 */ public class Facade { /** * Assemble a new LoggerManager running on top of LogKit * configured from a configuration file logging to a supplied * logger as a fallback. * Use this method as a sample showing how to assemble your * own LoggerManager running on top of LogKit flavour. */ public static LoggerManager createLogKitConfigurable( final String prefix, final String switchTo ) { final org.apache.log.Hierarchy hierarchy = new Hierarchy(); final LoggerManager bare = new LogKitAdapter( hierarchy ); final LoggerManager decorated = applyDecorators( bare, prefix, switchTo ); final LoggerManagerTee tee = new LoggerManagerTee( decorated ); tee.addTee( new LogKitLoggerHelper( hierarchy ) ); tee.addTee( new LogKitConfHelper( hierarchy ) ); tee.makeReadOnly(); return tee; } /** * Assemble LoggerManager for Log4J system configured * via a configuration file. All the logging errors * will go to System.err however. */ public static LoggerManager createLog4JConfigurable( final String prefix, final String switchTo ) { final LoggerManager bare = new Log4JConfAdapter(); final LoggerManager decorated = applyDecorators( bare, prefix, switchTo ); return decorated; } private static LoggerManager applyDecorators( LoggerManager target, final String prefix, final String switchTo ) { if ( switchTo != null ) { target = new LogToSelfDecorator( target, switchTo ); } if ( prefix != null && prefix.length() > 0 ) { target = new PrefixDecorator( target, prefix ); } target = new CachingDecorator( target ); return target; } } excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/util/LoggerUtil.java 100644 0 0 3416 10304740432 26071 0 ustar 0 0 /* * Copyright 2002-2004 The Apache Software Foundation * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avalon.excalibur.logger.util; /** * This class implements utility methods for building LoggerManager-s. * * @author Avalon Development Team * @version CVS $Revision: 1.3 $ $Date: 2004/03/10 13:54:51 $ * @since 4.0 */ public class LoggerUtil { /** * Generates a full category name given a prefix and category. Either may be * null. * * @param prefix Prefix or parent category. * @param category Child category name. */ public static String getFullCategoryName( final String prefix, final String category ) { if( ( null == prefix ) || ( prefix.length() == 0 ) ) { if( category == null ) { return ""; } else { return category; } } else { if( ( null == category ) || ( category.length() == 0 ) ) { return prefix; } else { return prefix + org.apache.log.Logger.CATEGORY_SEPARATOR + category; } } } } excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/util/LoggerManagerTee.java 100644 0 0 4252 10304740432 27163 0 ustar 0 0 /* * Copyright 2002-2004 The Apache Software Foundation * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avalon.excalibur.logger.util; import org.apache.avalon.excalibur.logger.LoggerManager; import org.apache.avalon.framework.logger.Logger; /** * An AvalonTee object is not usefull by itself as it does not * implement any component interface. Its primary use is to * serve as a base class for objects proxing not only * lifecycle but also some "meaningfull" interfaces. * This object proxies LoggerManager interface. * * @author Avalon Development Team * @version CVS $Revision: 1.3 $ $Date: 2004/03/10 13:54:51 $ * @since 4.0 */ public class LoggerManagerTee extends AvalonTee implements LoggerManager { /* The wrapped LoggerManager to delegate all the work to.*/ private final LoggerManager m_loggerManager; /** * Creates a new instance of LoggerManagerTee. Adds the supplied * LoggerManager as the first tee. (It will receive the lifecycle * events first of all tees). */ public LoggerManagerTee( final LoggerManager loggerManager ) { addTee( loggerManager ); m_loggerManager = loggerManager; } /** * Return the Logger for the specified category. */ public Logger getLoggerForCategory( final String categoryName ) { return m_loggerManager.getLoggerForCategory( categoryName ); } /** * Return the default Logger. This is basically the same * as getting the Logger for the "" category. */ public Logger getDefaultLogger() { return m_loggerManager.getDefaultLogger(); } } excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/util/LoggerSwitch.java 100644 0 0 21534 10304740432 26436 0 ustar 0 0 /* * Copyright 2002-2004 The Apache Software Foundation * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avalon.excalibur.logger.util; import org.apache.avalon.framework.logger.Logger; import org.apache.avalon.framework.logger.NullLogger; /** * A proxy logger that switches between two underlying loggers * with recursive invocation detection. *
* This class is intended to be used by o.a.a.e.logger.AbstractLoggerManager. * all the logger switching is done in it during the "warm-up" phase * (constructor, enableLogging, contextualize, configure, start). * All these operations are held our on a single thread and the * object is not exposed to other threads untill (in strict synchronization * sense) it has been fully configured. That's why there is no synchronization * in this class. If the switching was to occur in a mulitythreaded * fasion we would have to synchronize access to m_fallback and m_preferred. * * @author Avalon Development Team */ public class LoggerSwitch { protected final static Logger SHARED_NULL = new NullLogger(); private final static class BooleanThreadLocal extends ThreadLocal { public Object initialValue() { return Boolean.FALSE; } public boolean value() { return ((Boolean)this.get()).booleanValue(); } } private static class SwitchingLogger implements Logger { Logger m_fallback; Logger m_preferred; BooleanThreadLocal m_recursionOnPreferred = new BooleanThreadLocal(); BooleanThreadLocal m_recursionOnFallback = new BooleanThreadLocal(); SwitchingLogger( final Logger fallback, final Logger preferred ) { m_fallback = fallback != null ? fallback : SHARED_NULL; m_preferred = preferred; } void setFallback( final Logger fallback ) { m_fallback = fallback != null ? fallback : SHARED_NULL; } void setPreferred( final Logger preferred ) { m_preferred = preferred; } /** * Retrieve m_preferred or if that is null m_fallback. * Safeguard against recursion. That is possible if * try to log something via a Logger that is failing * and trying to log its own error via itself. */ private Logger getLogger() { if ( m_recursionOnFallback.value() ) { throw new IllegalStateException( "infinite recursion" ); } else if ( m_recursionOnPreferred.value() || m_preferred == null ) { m_recursionOnFallback.set( Boolean.TRUE ); return m_fallback; } else { m_recursionOnPreferred.set( Boolean.TRUE ); return m_preferred; } } private Logger getLoggerLight() { return m_preferred != null ? m_preferred : m_fallback; } private void releaseLogger() { if ( m_recursionOnFallback.value() ) { m_recursionOnFallback.set( Boolean.FALSE ); } else if ( m_recursionOnPreferred.value() ) { m_recursionOnPreferred.set( Boolean.FALSE ); } else { throw new IllegalStateException( "no recursion" ); } } public void debug( final String message ) { final Logger logger = getLogger(); try { logger.debug( message ); } finally { releaseLogger(); } } public void debug( final String message, final Throwable throwable ) { final Logger logger = getLogger(); try { logger.debug( message, throwable ); } finally { releaseLogger(); } } /** * This and similar method may probably be optimized in the * future by caching the boolean in our instance variables. * Each time setPreferred() or setFallback() is called they * will be cached. Maybe in the future. :-) */ public boolean isDebugEnabled() { final Logger logger = getLoggerLight(); return logger.isDebugEnabled(); } public void info( final String message ) { final Logger logger = getLogger(); try { logger.info( message ); } finally { releaseLogger(); } } public void info( final String message, final Throwable throwable ) { final Logger logger = getLogger(); try { logger.info( message, throwable ); } finally { releaseLogger(); } } public boolean isInfoEnabled() { final Logger logger = getLoggerLight(); return logger.isInfoEnabled(); } public void warn( final String message ) { final Logger logger = getLogger(); try { logger.warn( message ); } finally { releaseLogger(); } } public void warn( final String message, final Throwable throwable ) { final Logger logger = getLogger(); try { logger.warn( message, throwable ); } finally { releaseLogger(); } } public boolean isWarnEnabled() { final Logger logger = getLoggerLight(); return logger.isWarnEnabled(); } public void error( final String message ) { final Logger logger = getLogger(); try { logger.error( message ); } finally { releaseLogger(); } } public void error( final String message, final Throwable throwable ) { final Logger logger = getLogger(); try { logger.error( message, throwable ); } finally { releaseLogger(); } } public boolean isErrorEnabled() { final Logger logger = getLoggerLight(); return logger.isErrorEnabled(); } public void fatalError( final String message ) { final Logger logger = getLogger(); try { logger.fatalError( message ); } finally { releaseLogger(); } } public void fatalError( final String message, final Throwable throwable ) { final Logger logger = getLogger(); try { logger.fatalError( message, throwable ); } finally { releaseLogger(); } } public boolean isFatalErrorEnabled() { final Logger logger = getLoggerLight(); return logger.isFatalErrorEnabled(); } public Logger getChildLogger( final String name ) { return this; } } private SwitchingLogger m_switch; /** * We create a logger with no methods for changing * m_fallback and m_preferred for security reasons. * All the control is done by the parent class * that does not implement Logger itself. */ public Logger get() { return m_switch; } public LoggerSwitch( final Logger fallback ) { this( fallback, null ); } public LoggerSwitch( final Logger fallback, final Logger preferred ) { m_switch = new SwitchingLogger( fallback, preferred ); } public void setFallback( final Logger fallback ) { m_switch.setFallback( fallback ); } public void setPreferred( final Logger preferred ) { m_switch.setPreferred( preferred ); } } excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/util/AvalonTee.java 100644 0 0 10331 10304740432 25704 0 ustar 0 0 /* * Copyright 2002-2004 The Apache Software Foundation * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avalon.excalibur.logger.util; import org.apache.avalon.framework.logger.Logger; import org.apache.avalon.framework.logger.LogEnabled; import org.apache.avalon.framework.context.Context; import org.apache.avalon.framework.context.Contextualizable; import org.apache.avalon.framework.context.ContextException; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.Configurable; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.avalon.framework.activity.Startable; import org.apache.avalon.framework.activity.Disposable; import org.apache.avalon.framework.container.ContainerUtil; import java.util.ArrayList; /** * This class broadcasts Avalon lifestyle events to several * destination objects, somewhat like Unix 'tee' command * directing its input both to file and to its output. * * The current implementation is incomplete and handles * only LogEnabled, Contextutalizable, Configurable and Disposable * interfaces. * * @author Avalon Development Team * @version CVS $Revision: 1.4 $ $Date: 2004/03/10 13:54:51 $ * @since 4.0 */ public class AvalonTee implements LogEnabled, Contextualizable, Configurable, Startable, Disposable { /* The objects we direct our events to */ private ArrayList m_listeners = new ArrayList( 10 ); /** * The number of these objects. This variable is here * is to save a line of code in every reactor method * rather then to optimize speed. */ private int m_len = 0; /* Has adding new tees been prohibited? */ private boolean m_readOnly = false; /** * Disallow adding more tees. */ public void makeReadOnly() { m_readOnly = true; } /** * Adds an object to the list of objects receiving events. * @param obj the object to add; can not be null. */ public void addTee( final Object obj ) { if ( m_readOnly ) { throw new IllegalStateException( "makeReadOnly() already invoked" ); } if ( obj == null ) throw new NullPointerException( "obj" ); if ( m_listeners.contains( obj ) ) { // should we complain? better not, probably } else { // adds to the end of the array m_listeners.add( obj ); m_len = m_listeners.size(); } } public void enableLogging( final Logger logger ) { for( int i = 0; i < m_len; ++i ) { ContainerUtil.enableLogging( m_listeners.get( i ), logger ); } } public void contextualize( final Context context ) throws ContextException { for( int i = 0; i < m_len; ++i ) { ContainerUtil.contextualize( m_listeners.get( i ), context ); } } public void configure( final Configuration config ) throws ConfigurationException { for( int i = 0; i < m_len; ++i ) { ContainerUtil.configure( m_listeners.get( i ), config ); } } public void start() throws Exception { for( int i = 0; i < m_len; ++i ) { ContainerUtil.start( m_listeners.get( i ) ); } } public void stop() throws Exception { for( int i = 0; i < m_len; ++i ) { ContainerUtil.stop( m_listeners.get( i ) ); } } public void dispose() { for( int i = 0; i < m_len; ++i ) { ContainerUtil.dispose( m_listeners.get( i ) ); } } } excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/LoggerManageable.java 100644 0 0 2447 10304740432 26216 0 ustar 0 0 /* * Copyright 2005 The Apache Software Foundation * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avalon.excalibur.logger; /** * LoggerManageable interface, use this to set the {@link LoggerManager} * for the child components. * *
Replaces LogKitManageable.
* * @author Avalon Development Team * @version CVS $Revision: 1.8 $ $Date: 2004/03/10 13:54:50 $ * @since 4.0 */ public interface LoggerManageable { /** * Sets the LoggerManager for child components. Can be used for special * purpose components, however it is used mostly internally. * * @param loggerManager The LoggerManager for child components. */ void setLoggerManager( final LoggerManager loggerManager ); } excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/LoggerManager.java 100644 0 0 2562 10304740432 25552 0 ustar 0 0 /* * Copyright 2002-2004 The Apache Software Foundation * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avalon.excalibur.logger; import org.apache.avalon.framework.logger.Logger; /** * LoggerManager Interface. This is the interface used to get instances of * a Logger for your system. * * @author Avalon Development Team * @version CVS $Revision: 1.9 $ $Date: 2004/03/10 13:54:50 $ */ public interface LoggerManager { public static final String ROLE = LoggerManager.class.getName(); /** * Return the Logger for the specified category. */ public Logger getLoggerForCategory( String categoryName ); /** * Return the default Logger. This is basically the same * as getting the Logger for the "" category. */ public Logger getDefaultLogger(); } excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/LogTargetFactoryManager.java 100644 0 0 2051 10304740432 27544 0 ustar 0 0 /* * Copyright 2002-2004 The Apache Software Foundation * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avalon.excalibur.logger; /** * LogTargetFactoryManager Interface. * * @author Avalon Development Team * @version CVS $Revision: 1.7 $ $Date: 2004/03/10 13:54:50 $ * @since 4.0 */ public interface LogTargetFactoryManager { /** * Find a factory for LogTargets based on a name. */ LogTargetFactory getLogTargetFactory( String factoryName ); } excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/Log4JLogger.java 100644 0 0 15323 10304740432 25136 0 ustar 0 0 /* * Copyright 2002-2004 The Apache Software Foundation * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avalon.excalibur.logger; import org.apache.avalon.framework.logger.Logger; import org.apache.log4j.Level; /** * The default Log4J wrapper class for Logger. * This implementation replaces the implementation from Avalon framework. * It "caches" the log levels for improved performance. * * @author Avalon Development Team * @version CVS $Revision: 1.21 $ $Date: 2004/05/04 13:08:00 $ */ public class Log4JLogger implements Logger { /** * Constant for name of class to use when recording caller * of log method. */ private static final String FQCN = Log4JLogger.class.getName(); /** underlying implementation */ private final org.apache.log4j.Logger m_logger; private final boolean m_isDebugEnabled; private final boolean m_isInfoEnabled; private final boolean m_isWarnEnabled; private final boolean m_isErrorEnabled; private final boolean m_isFatalErrorEnabled; /** * Create a logger that delegates to specified category. * * @param logImpl the category to delegate to */ public Log4JLogger( final org.apache.log4j.Logger logImpl ) { m_logger = logImpl; m_isDebugEnabled = logImpl.isDebugEnabled(); m_isInfoEnabled = logImpl.isInfoEnabled(); m_isWarnEnabled = logImpl.isEnabledFor( Level.WARN ); m_isErrorEnabled = logImpl.isEnabledFor( Level.ERROR ); m_isFatalErrorEnabled = logImpl.isEnabledFor( Level.FATAL ); } /** * Log a debug message. * * @param message the message */ public final void debug( final String message ) { if ( m_isDebugEnabled ) m_logger.log( FQCN, Level.DEBUG, message, null ); } /** * Log a debug message. * * @param message the message * @param throwable the throwable */ public final void debug( final String message, final Throwable throwable ) { if ( m_isDebugEnabled ) m_logger.log( FQCN, Level.DEBUG, message, throwable ); } /** * Determine if messages of priority "debug" will be logged. * * @return true if "debug" messages will be logged */ public final boolean isDebugEnabled() { return m_isDebugEnabled; } /** * Log a info message. * * @param message the message */ public final void info( final String message ) { if ( m_isInfoEnabled ) m_logger.log( FQCN, Level.INFO, message, null ); } /** * Log a info message. * * @param message the message * @param throwable the throwable */ public final void info( final String message, final Throwable throwable ) { if ( m_isInfoEnabled ) m_logger.log( FQCN, Level.INFO, message, throwable ); } /** * Determine if messages of priority "info" will be logged. * * @return true if "info" messages will be logged */ public final boolean isInfoEnabled() { return m_isInfoEnabled; } /** * Log a warn message. * * @param message the message */ public final void warn( final String message ) { if ( m_isWarnEnabled ) m_logger.log( FQCN, Level.WARN, message, null ); } /** * Log a warn message. * * @param message the message * @param throwable the throwable */ public final void warn( final String message, final Throwable throwable ) { if ( m_isWarnEnabled ) m_logger.log( FQCN, Level.WARN, message, throwable ); } /** * Determine if messages of priority "warn" will be logged. * * @return true if "warn" messages will be logged */ public final boolean isWarnEnabled() { return m_isWarnEnabled; } /** * Log a error message. * * @param message the message */ public final void error( final String message ) { if ( m_isErrorEnabled ) m_logger.log( FQCN, Level.ERROR, message, null ); } /** * Log a error message. * * @param message the message * @param throwable the throwable */ public final void error( final String message, final Throwable throwable ) { if ( m_isErrorEnabled ) m_logger.log( FQCN, Level.ERROR, message, throwable ); } /** * Determine if messages of priority "error" will be logged. * * @return true if "error" messages will be logged */ public final boolean isErrorEnabled() { return m_isErrorEnabled; } /** * Log a fatalError message. * * @param message the message */ public final void fatalError( final String message ) { if ( m_isFatalErrorEnabled ) m_logger.log( FQCN, Level.FATAL, message, null ); } /** * Log a fatalError message. * * @param message the message * @param throwable the throwable */ public final void fatalError( final String message, final Throwable throwable ) { if ( m_isFatalErrorEnabled ) m_logger.log( FQCN, Level.ERROR, message, throwable ); } /** * Determine if messages of priority "fatalError" will be logged. * * @return true if "fatalError" messages will be logged */ public final boolean isFatalErrorEnabled() { return m_isFatalErrorEnabled; } /** * Create a new child logger. * The name of the child logger is [current-loggers-name].[passed-in-name] * ThrowsIllegalArgumentException
if name has an empty element name
*
* @param name the subname of this logger
* @return the new logger
*/
public final Logger getChildLogger( final String name )
{
return new Log4JLogger( org.apache.log4j.Logger.getLogger( m_logger.getName() + "." + name ) );
}
}
excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/LogTargetFactory.java 100644 0 0 2334 10304740432 26255 0 ustar 0 0 /*
* Copyright 2002-2004 The Apache Software Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avalon.excalibur.logger;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.log.LogTarget;
/**
* LogTargetFactory Interface.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.7 $ $Date: 2004/03/10 13:54:50 $
* @since 4.0
*/
public interface LogTargetFactory
{
/**
* Create a LogTarget based on a Configuration
*/
LogTarget createTarget( Configuration configuration ) throws ConfigurationException;
}
excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/DefaultLoggerManager.java 100644 0 0 17543 10304740432 27104 0 ustar 0 0 /*
* Copyright 2002-2004 The Apache Software Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avalon.excalibur.logger;
import org.apache.avalon.framework.activity.Disposable;
import org.apache.avalon.framework.configuration.Configurable;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.container.ContainerUtil;
import org.apache.avalon.framework.context.Context;
import org.apache.avalon.framework.context.ContextException;
import org.apache.avalon.framework.context.Contextualizable;
import org.apache.avalon.framework.logger.LogEnabled;
import org.apache.avalon.framework.logger.Logger;
import org.apache.avalon.framework.parameters.ParameterException;
import org.apache.avalon.framework.parameters.Parameterizable;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.avalon.framework.service.ServiceException;
import org.apache.avalon.framework.service.ServiceManager;
import org.apache.avalon.framework.service.Serviceable;
import org.apache.avalon.framework.thread.ThreadSafe;
/**
* This logger manager is a wrapper around all other "real" logger managers.
* The idea is to have one single configuration file where you can
* define, which logger manager (Log4J, LogKit etc.) you want to use, so
* you don't have to hard-code this.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.9 $ $Date: 2004/03/10 13:54:49 $
*/
public final class DefaultLoggerManager
implements LoggerManager,
ThreadSafe,
LogEnabled,
Contextualizable,
Configurable,
Serviceable,
Disposable
{
/** The used LoggerManager */
private LoggerManager m_loggermanager;
/** The context object */
private Context m_context;
/** The logger used to log output from the logger manager. */
private Logger m_logger;
/** The prefix */
private String m_prefix;
/** The service manager */
private ServiceManager m_manager;
/** Do we have to dispose the manager */
private boolean m_disposeManager = false;
/**
* Creates a new DefaultLoggerManager
. .
*/
public DefaultLoggerManager()
{
}
/**
* Creates a new DefaultLoggerManager
. .
*/
public DefaultLoggerManager( String prefix )
{
m_prefix = prefix;
}
/**
* Provide a logger.
*
* @param logger the logger
**/
public void enableLogging( final Logger logger )
{
m_logger = logger;
}
/**
* Return the Logger for the specified category.
*/
public final Logger getLoggerForCategory( final String categoryName )
{
return m_loggermanager.getLoggerForCategory( categoryName );
}
/**
* Return the default Logger. This is basically the same
* as getting the Logger for the "" category.
*/
public final Logger getDefaultLogger()
{
return m_loggermanager.getDefaultLogger();
}
/**
* Reads a context object that will be supplied to the logger manager.
*
* @param context The context object.
* @throws ContextException if the context is malformed
*/
public final void contextualize( final Context context )
throws ContextException
{
m_context = context;
}
/**
* Reads a configuration object and creates the category mapping.
*
* @param configuration The configuration object.
* @throws ConfigurationException if the configuration is malformed
*/
public final void configure( final Configuration configuration )
throws ConfigurationException
{
// first we test for the class name to use
final String className = configuration.getAttribute( "manager-class", null );
if( null != className )
{
// is a prefix available?
final String prefix = configuration.getAttribute( "prefix", m_prefix );
// create logger manager
try
{
if( null == prefix )
{
m_loggermanager = (LoggerManager)Class.forName( className ).newInstance();
}
else
{
m_loggermanager = (LoggerManager)Class.forName( className )
.getConstructor( new Class[]{String.class} )
.newInstance( new Object[]{prefix} );
}
}
catch( Exception e )
{
throw new ConfigurationException( "Unable to create new logger manager for class " + className, e );
}
// now test for some lifecycle interfaces
ContainerUtil.enableLogging(m_loggermanager, m_logger );
try
{
ContainerUtil.contextualize( m_loggermanager, m_context );
}
catch( ContextException ce )
{
throw new ConfigurationException( "Unable to contextualize new logger manager.", ce );
}
try
{
ContainerUtil.service( m_loggermanager, m_manager );
}
catch (ServiceException se )
{
throw new ConfigurationException("Unable to service new logger manager.", se);
}
if( m_loggermanager instanceof Configurable )
{
( (Configurable)m_loggermanager ).configure( configuration.getChildren()[ 0 ] );
}
else if( m_loggermanager instanceof Parameterizable )
{
try
{
( (Parameterizable)m_loggermanager ).parameterize( Parameters.fromConfiguration( configuration.getChildren()[ 0 ] ) );
}
catch( ParameterException pe )
{
throw new ConfigurationException( "Unable to parameterize new logger manager.", pe );
}
}
try
{
ContainerUtil.initialize( m_loggermanager );
}
catch (Exception e )
{
throw new ConfigurationException("Unable to initialize new logger manager.");
}
}
else
{
// now test for role name
final String roleName = configuration.getAttribute( "manager-role", null );
if( null == roleName )
{
throw new ConfigurationException( "The LoggerManager needs either a manager-role or a manager-class" );
}
try
{
m_loggermanager = (LoggerManager)m_manager.lookup( roleName );
m_disposeManager = true;
}
catch( ServiceException e )
{
throw new ConfigurationException( "Unable to lookup logger manager with role " + roleName );
}
}
}
public void service( ServiceManager manager )
throws ServiceException
{
m_manager = manager;
}
public void dispose()
{
if( m_disposeManager && null != m_manager )
{
m_manager.release( m_loggermanager );
}
m_manager = null;
m_loggermanager = null;
m_disposeManager = false;
}
}
excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/SimpleLogKitManager.java 100644 0 0 21354 10304740432 26716 0 ustar 0 0 /*
* Copyright 2002-2004 The Apache Software Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avalon.excalibur.logger;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import org.apache.avalon.framework.activity.Disposable;
import org.apache.avalon.framework.configuration.Configurable;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.context.Context;
import org.apache.avalon.framework.context.ContextException;
import org.apache.avalon.framework.context.Contextualizable;
import org.apache.avalon.framework.logger.AbstractLogEnabled;
import org.apache.avalon.framework.logger.AvalonFormatter;
import org.apache.avalon.framework.logger.LogKitLogger;
import org.apache.log.Hierarchy;
import org.apache.log.LogTarget;
import org.apache.log.Logger;
import org.apache.log.Priority;
import org.apache.log.output.io.FileTarget;
import org.apache.log.util.Closeable;
/**
* A {@link LoggerManager} that supports the old <logs version="1.0"/>
* style logging configuration from
* Phoenix.
*
* @author Avalon Development Team
*/
public class SimpleLogKitManager
extends AbstractLogEnabled
implements LoggerManager, Contextualizable, Configurable, Disposable
{
private static final String DEFAULT_FORMAT =
"%7.7{priority} %23.23{time:yyyy-MM-dd' 'HH:mm:ss.SSS} [%8.8{category}] (%{context}): "
+ "%{message}\n%{throwable}";
///Base directory of applications working directory
private File m_baseDirectory;
/**
* Hierarchy of Application logging
*/
private final Hierarchy m_hierarchy = new Hierarchy();
/**
* The root logger in hierarchy.
*/
private final Logger m_logkitLogger = m_hierarchy.getLoggerFor( "" );
/**
* The root logger wrapped using AValons Logging Facade.
*/
private org.apache.avalon.framework.logger.Logger m_logger =
new LogKitLogger( m_logkitLogger );
private Collection m_targets;
/**
* Contextualize the manager. Requires that the "app.home" entry
* be set to a File object that points at the base directory for logs.
*
* @param context the context
* @throws ContextException if missing context entry
*/
public void contextualize( final Context context )
throws ContextException
{
try
{
m_baseDirectory = (File)context.get( "app.home" );
}
catch( ContextException e )
{
m_baseDirectory = new File( "." );
}
}
/**
* Interpret configuration to build loggers.
*
* @param configuration the configuration
* @throws ConfigurationException if malformed configuration
*/
public void configure( final Configuration configuration )
throws ConfigurationException
{
final Configuration[] targets = configuration.getChildren( "log-target" );
final HashMap targetSet = configureTargets( targets );
m_targets = targetSet.values();
final Configuration[] categories = configuration.getChildren( "category" );
configureCategories( categories, targetSet );
}
/**
* Close any closable log targets opened by LoggerManager.
*/
public void dispose()
{
final Iterator iterator = m_targets.iterator();
while( iterator.hasNext() )
{
final LogTarget logTarget = (LogTarget)iterator.next();
if( logTarget instanceof Closeable )
{
( (Closeable)logTarget ).close();
}
}
}
/**
* Retrieve a logger by name.
*
* @param name the name of logger
* @return the specified Logger
*/
public org.apache.avalon.framework.logger.Logger
getLoggerForCategory( final String name )
{
return m_logger.getChildLogger( name );
}
/**
* Retrieve the root logger.
*
* @return the root Logger
*/
public org.apache.avalon.framework.logger.Logger getDefaultLogger()
{
return m_logger;
}
/**
* Configure a set of logtargets based on config data.
*
* @param targets the target configuration data
* @return a Map of target-name to target
* @throws ConfigurationException if an error occurs
*/
private HashMap configureTargets( final Configuration[] targets )
throws ConfigurationException
{
final HashMap targetSet = new HashMap();
for( int i = 0; i < targets.length; i++ )
{
final Configuration target = targets[ i ];
final String name = target.getAttribute( "name" );
String location = target.getAttribute( "location" ).trim();
final String format = target.getAttribute( "format", DEFAULT_FORMAT );
final boolean append = target.getAttributeAsBoolean( "append", true );
if( '/' == location.charAt( 0 ) )
{
location = location.substring( 1 );
}
final AvalonFormatter formatter = new AvalonFormatter( format );
//Specify output location for logging
final File file = new File( m_baseDirectory, location );
//Setup logtarget
FileTarget logTarget = null;
try
{
logTarget = new FileTarget( file.getAbsoluteFile(), append, formatter );
}
catch( final IOException ioe )
{
final String message =
"Error creating LogTarget named \"" + name + "\" for file " +
file + ". (Reason: " + ioe.getMessage() + ").";
throw new ConfigurationException( message, ioe );
}
targetSet.put( name, logTarget );
}
return targetSet;
}
/**
* Configure Logging categories.
*
* @param categories configuration data for categories
* @param targets a hashmap containing the already existing taregt
* @throws ConfigurationException if an error occurs
*/
private void configureCategories( final Configuration[] categories, final HashMap targets )
throws ConfigurationException
{
for( int i = 0; i < categories.length; i++ )
{
final Configuration category = categories[ i ];
final String name = category.getAttribute( "name", "" );
final String target = category.getAttribute( "target" );
final String priorityName = category.getAttribute( "priority" );
final Logger logger =
m_logkitLogger.getChildLogger( name );
final LogTarget logTarget = (LogTarget)targets.get( target );
if( null == target )
{
final String message =
"Unable to locate LogTarget named \"" + target +
"\" for Logger named \"" + name + "\".";
throw new ConfigurationException( message );
}
final Priority priority = Priority.getPriorityForName( priorityName );
if( !priority.getName().equals( priorityName ) )
{
final String message =
"Unknown priority \"" + priorityName + "\" for Logger named \"" +
name + "\".";
throw new ConfigurationException( message );
}
if( getLogger().isDebugEnabled() )
{
final String message =
"Creating a log category named \"" + name +
"\" that writes to \"" + target + "\" target at priority \"" +
priorityName + "\".";
getLogger().debug( message );
}
if( name.equals( "" ) )
{
m_logkitLogger.setPriority( priority );
m_logkitLogger.setLogTargets( new LogTarget[] {logTarget} );
}
else
{
logger.setPriority( priority );
logger.setLogTargets( new LogTarget[]{logTarget} );
}
}
}
}
excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/LogKitLoggerManager.java 100644 0 0 60243 10304740432 26704 0 ustar 0 0 /*
* Copyright 2002-2005 The Apache Software Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avalon.excalibur.logger;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.apache.avalon.excalibur.logger.util.LoggerUtil;
import org.apache.avalon.framework.activity.Disposable;
import org.apache.avalon.framework.configuration.Configurable;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.container.ContainerUtil;
import org.apache.avalon.framework.context.Context;
import org.apache.avalon.framework.context.ContextException;
import org.apache.avalon.framework.context.Contextualizable;
import org.apache.avalon.framework.logger.LogKitLogger;
import org.apache.avalon.framework.logger.Logger;
import org.apache.log.ErrorHandler;
import org.apache.log.Hierarchy;
import org.apache.log.LogEvent;
import org.apache.log.LogTarget;
import org.apache.log.Priority;
import org.apache.log.util.Closeable;
/**
* LogKitLoggerManager implementation. It populates the LoggerManager
* from a configuration file.
*
* @author Avalon Development Team
* @version SVN $Id$
* @since 4.0
*/
public class LogKitLoggerManager extends AbstractLoggerManager
implements LoggerManager, Contextualizable, Configurable, Disposable
{
/** Set of log targets */
final private Set m_targets = new HashSet();
/** The context object */
private Context m_context;
/** The hierarchy private to LogKitManager */
private final Hierarchy m_hierarchy;
/**
* Creates a new LogKitLoggerManager
;
* one of the preferred constructors.
* Please also invoke enableLogging()
* to supply a fallback logger.
*/
public LogKitLoggerManager()
{
this( (String)null, (Hierarchy)null, (String)null, (Logger)null, (Logger)null );
}
/**
* Creates a new LogKitLoggerManager
;
* one of the preferred constructors.
* Please also invoke enableLogging()
* to supply a fallback logger.
*
* @param prefix to prepended to category name on each
* invocation of getLoggerForCategory()
.
*/
public LogKitLoggerManager( final String prefix )
{
this( prefix, (Hierarchy)null, (String)null, (Logger)null, (Logger)null );
}
/**
* Creates a new LogKitLoggerManager
;
* one of the preferred constructors,
* intended for the widest usage.
*
* Please also invoke enableLogging()
* to supply a fallback logger.
* * Example: *
* LogKitLoggerManager l = new LogKitLoggerManager( "fortress", "system.logkit" ); * l.enableLogging( bootstrapLogger ); * l.configure( loggerManagerConfiguration ); ** * @param prefix to prepended to category name on each * invocation of
getLoggerForCategory()
.
* @param switchToCategory if this parameter is not null
* after start()
* LogKitLoggerManager
will start
* to log its own debug and error messages to
* a logger obtained via
* this.getLoggerForCategory( switchToCategory )
.
* Note that prefix will be prepended to
* the value of switchToCategory
also.
*/
public LogKitLoggerManager( final String prefix, final String switchToCategory )
{
this( prefix, (Hierarchy)null, switchToCategory, (Logger)null, (Logger)null );
}
/**
* Creates a new LogKitLoggerManager
* with an existing Hierarchy
;
* use with caution.
*
* Please also invoke enableLogging()
* to supply a fallback logger.
* See comments on the root constructor
* for details on why constructors supplying an existing hierarchy
* should be used with caution.
*
* @param prefix to prepended to category name on each
* invocation of getLoggerForCategory()
.
* @param switchToCategory if this parameter is not null
* after start()
* LogKitLoggerManager
will start
* to log its own debug and error messages to
* a logger obtained via
* this.getLoggerForCategory( switchToCategory )
.
* Note that prefix will be prepended to
* the value of switchToCategory
also.
*/
public LogKitLoggerManager( final String prefix, final Hierarchy hierarchy,
final String switchToCategory )
{
this( prefix, hierarchy, switchToCategory, (Logger)null, (Logger)null );
}
/**
* Creates a new LogKitLoggerManager
* with an existing Hierarchy
;
* use with caution.
*
* Please also invoke enableLogging()
* to supply a fallback logger.
* See comments on the root constructor
* for details on why constructors supplying an existing hierarchy
* should be used with caution.
*/
public LogKitLoggerManager( final Hierarchy hierarchy )
{
this( (String)null, hierarchy, (String)null, (Logger)null, (Logger)null );
}
/**
* Creates a new LogKitLoggerManager
* with an existing Hierarchy
;
* use with caution.
*
* Please also invoke enableLogging()
* to supply a fallback logger.
* See comments on the root constructor
* for details on why constructors supplying an existing hierarchy
* should be used with caution.
*
* @param prefix to prepended to category name on each
* invocation of getLoggerForCategory()
.
*/
public LogKitLoggerManager( final String prefix, final Hierarchy hierarchy )
{
this( prefix, hierarchy, (String)null, (Logger)null, (Logger)null );
}
/**
* Creates a new LogKitLoggerManager
* with an existing Hierarchy
using
* specified logger name as a fallback logger and to
* forcibly override the root logger;
* compatibility constructor.
*
* The configuration for the ""
* category in the configuration will supply the defaults for
* all other categories, but getDefaultLogger()
* and getLoggerForCategory()
will still
* use logger supplied by this constructor.
*
* * See comments on the root constructor * for details on why constructors supplying an existing hierarchy * should be used with caution. * *
* As this constructor provides a logger to be used as a fallback
* a subsequent enableLogging()
stage is unnecessary.
* Moreover, it will fail.
*
* @param prefix to prepended to category name on each
* invocation of getLoggerForCategory()
.
* @param defaultOverrideAndFallback the logger used to
* a) forcibly
* override the root logger that will further be obtained from
* the configuration and b) as the fallback logger. Note that
* specifying a logger as this parameter crucially differs from
* supplying it via enableLogging()
. The logger
* supplied via enableLogging
will only be used
* as the fallback logger and to log messages during initialization
* while this constructor argument also has the described
* override semantics.
*/
public LogKitLoggerManager( final String prefix, final Hierarchy hierarchy,
final Logger defaultOverrideAndFallback )
{
this( prefix, hierarchy, (String)null,
defaultOverrideAndFallback, defaultOverrideAndFallback );
}
/**
* Creates a new LogKitLoggerManager
* with an existing Hierarchy
using
* specified loggers to forcibly override
* the default logger and to provide a fallback logger;
* compatibility constructor.
*
* See comments on the root constructor
* for details on why constructors supplying an existing hierarchy
* should be used with caution.
*
* As this constructor provides a logger to be used as a fallback
* a subsequent enableLogging()
stage is unnecessary.
* Moreover, it will fail.
*
* @param prefix to prepended to category name on each
* invocation of getLoggerForCategory()
.
* @param defaultLoggerOverride the logger to be used to forcibly
* override the root logger that will further be obtained from
* the configuration
* @param fallbackLogger the logger to as a fallback logger
* (passing non-null as this argument eliminates the need
* to invoke enableLogging()
)
*/
public LogKitLoggerManager( final String prefix, final Hierarchy hierarchy,
final Logger defaultLoggerOverride,
final Logger fallbackLogger )
{
this( prefix, hierarchy, (String)null, defaultLoggerOverride, fallbackLogger );
}
/**
*
*
* Creates a new LogKitLoggerManager
;
* "root" constructor invoked by all other constructors.
*
*
* If the hierarchy
parameter is not null
* this instructs this constructor to use an existing hierarchy
* instead of creating a new one. This also disables removing
* the default log target configured by the Hierarchy()
* constructor (this target logs to System.out
) and
* installing our own ErrorHandler
for our
* Hierarchy
(the default ErrorHandler
* writes to System.err
).
*
* The configuration of the resulting Hierarchy
* is a combination of the original configuraiton that
* existed when this Hierarchy
was handled to us
* and the configuration supplied to use via configure()
.
* LogTarget
s for those categories for which a
* configuration node has been supplied in the configuration
* supplied via configure()
are replaced during
* the configure()
process. LogTargets
* for those categories for which configuration nodes have
* not been supplied are left as they were. A special case
* is when a node in configuration for a category exists but
* it does not enlist log targets. In this case the original
* targets if any are left as they were.
*
*
* Generally it is preferrable to *
Hierarchy
be configured
* from top to bottom via the configurationErrorHandler
reporting
* errors via the fallback logger (supplied either as
* the fallbackLogger
to this constructor or
* via the enableLogging()
method) installednull
* for the hierarchy
parameter of this constructor
* or, which is easier to read but has the same effect, to
* invoke a constructor which does not accept a Hierarchy
* argument.
*
*
* The defaultLoggerOverride
and fallbackLogger
* are a special case too. defaultLoggerOverride
* forcibly overrides
* the root logger configured via configure()
.
* As there is little reason to take away users's freedom to configure
* whatever he likes as the default logger, it is preferrable to pass
* null
for this parameter or better still to invoke
* a constructor without Logger
parameters at all.
There is nothing wrong with passing fallbackLogger
* via this constructor, but as this constructor is not convinient to
* be invoked (too many arguments, some of them likely to be null) and the
* {@link #LogKitLoggerManager(String,Hierarchy,Logger)}
* constructor is broken
* in using its Logger
argument both as
* fallbackLogger
(which is okay) and as
* a defaultLoggerOverride
(which is probably not
* desired for the reasons given above) it is preferrable not to
* specify a logger
* as a constructor argument but rather supply it via
* enableLogging()
call, like this happens with all
* other normal Avalon components after all.
*
* @param prefix to prepended to category name on each
* invocation of getLoggerForCategory()
.
* @param switchToCategory if this parameter is not null
* after start()
* LogKitLoggerManager
will start
* to log its own debug and error messages to
* a logger obtained via
* this.getLoggerForCategory( switchToCategory )
.
* Note that prefix will be prepended to
* the value of switchToCategory
also.
* @param defaultLoggerOverride the logger to be used to
* forcibly override
* the root logger that would further be obtained from
* the configuration
* @param fallbackLogger the logger to as a fallback logger
* (passing non-null as this argument eliminates the need
* to invoke enableLogging()
)
*/
public LogKitLoggerManager( final String prefix, final Hierarchy hierarchy,
final String switchToCategory,
final Logger defaultLoggerOverride,
final Logger fallbackLogger )
{
super( prefix, switchToCategory, defaultLoggerOverride );
m_prefix = prefix;
if ( hierarchy == null )
{
m_hierarchy = new Hierarchy();
m_hierarchy.getRootLogger().unsetLogTargets( true );
final ErrorHandler errorHandler = new OurErrorHandler( getLogger() );
m_hierarchy.setErrorHandler( errorHandler );
}
else
{
m_hierarchy = hierarchy;
}
if ( fallbackLogger != null )
{
this.enableLogging( fallbackLogger );
}
}
/**
* Reads a context object that will be supplied to the log target factory manager.
*
* @param context The context object.
* @throws ContextException if the context is malformed
*/
public final void contextualize( final Context context )
throws ContextException
{
m_context = context;
}
/**
* Actually create a logger for the given category.
* The result will be cached by
* AbstractLoggerManager.getLoggerForCategory()
.
*/
protected Logger doGetLoggerForCategory( final String fullCategoryName )
{
return new LogKitLogger( m_hierarchy.getLoggerFor( fullCategoryName ) );
}
/**
* Reads a configuration object and creates the category mapping.
*
* @param configuration The configuration object.
* @throws ConfigurationException if the configuration is malformed
*/
public void configure( final Configuration configuration )
throws ConfigurationException
{
final Configuration factories = configuration.getChild( "factories" );
final LogTargetFactoryManager targetFactoryManager = setupTargetFactoryManager( factories );
final Configuration targets = configuration.getChild( "targets" );
final LogTargetManager targetManager = setupTargetManager( targets, targetFactoryManager );
final Configuration categories = configuration.getChild( "categories" );
final Configuration[] category = categories.getChildren( "category" );
setupLoggers( targetManager,
m_prefix,
category,
true,
categories.getAttributeAsBoolean( "additive", false ) );
}
/**
* Setup a LogTargetFactoryManager
*
* @param configuration The configuration object.
* @throws ConfigurationException if the configuration is malformed
*/
private final LogTargetFactoryManager setupTargetFactoryManager( final Configuration configuration )
throws ConfigurationException
{
final DefaultLogTargetFactoryManager targetFactoryManager = new DefaultLogTargetFactoryManager();
ContainerUtil.enableLogging( targetFactoryManager, getLogger() );
try
{
ContainerUtil.contextualize( targetFactoryManager, m_context );
}
catch( final ContextException ce )
{
throw new ConfigurationException( "cannot contextualize default factory manager", ce );
}
ContainerUtil.configure( targetFactoryManager, configuration );
return targetFactoryManager;
}
/**
* Setup a LogTargetManager
*
* @param configuration The configuration object.
* @throws ConfigurationException if the configuration is malformed
*/
private final LogTargetManager setupTargetManager( final Configuration configuration,
final LogTargetFactoryManager targetFactoryManager )
throws ConfigurationException
{
final DefaultLogTargetManager targetManager = new DefaultLogTargetManager();
ContainerUtil.enableLogging( targetManager, getLogger() );
targetManager.setLogTargetFactoryManager( targetFactoryManager );
ContainerUtil.configure( targetManager, configuration );
return targetManager;
}
/**
* Setup Loggers
*
* @param categories [] The array object of configurations for categories.
* @param root shows if we're processing the root of the configuration
* @throws ConfigurationException if the configuration is malformed
*/
private final void setupLoggers( final LogTargetManager targetManager,
final String parentCategory,
final Configuration[] categories,
boolean root,
final boolean defaultAdditive )
throws ConfigurationException
{
boolean rootLoggerAlive = false;
for( int i = 0; i < categories.length; i++ )
{
final String category = categories[ i ].getAttribute( "name" );
final String fullCategory =
LoggerUtil.getFullCategoryName( parentCategory, category );
final String loglevel = categories[ i ].getAttribute( "log-level" ).toUpperCase();
final boolean additive = categories[ i ].
getAttributeAsBoolean( "additive", defaultAdditive );
final Configuration[] targets = categories[ i ].getChildren( "log-target" );
final LogTarget[] logTargets = new LogTarget[ targets.length ];
for( int j = 0; j < targets.length; j++ )
{
final String id = targets[ j ].getAttribute( "id-ref" );
logTargets[ j ] = targetManager.getLogTarget( id );
if (logTargets[ j ] == null)
{
throw new ConfigurationException("Category <" + fullCategory + ">: " +
"Target <" + id + "> is not defined.");
}
if( !m_targets.contains( logTargets[ j ] ) )
{
m_targets.add( logTargets[ j ] );
}
}
if( root && "".equals( category ) && logTargets.length > 0 )
{
m_hierarchy.setDefaultPriority( Priority.getPriorityForName( loglevel ) );
m_hierarchy.setDefaultLogTargets( logTargets );
rootLoggerAlive = true;
}
final org.apache.log.Logger logger = m_hierarchy.getLoggerFor( fullCategory );
m_loggers.put( fullCategory, new LogKitLogger( logger ) );
if( getLogger().isDebugEnabled() )
{
getLogger().debug( "added logger for category " + fullCategory );
}
logger.setPriority( Priority.getPriorityForName( loglevel ) );
logger.setLogTargets( logTargets );
logger.setAdditivity( additive );
final Configuration[] subCategories = categories[ i ].getChildren( "category" );
if( null != subCategories )
{
setupLoggers( targetManager, fullCategory, subCategories, false, defaultAdditive );
}
}
if ( root && !rootLoggerAlive )
{
final String message = "No log targets configured for the root logger.";
throw new ConfigurationException( message );
}
}
/**
* Closes all our LogTargets.
*/
public void dispose()
{
final Iterator iterator = m_targets.iterator();
while( iterator.hasNext() )
{
final LogTarget target = (LogTarget)iterator.next();
if( target instanceof Closeable )
{
( (Closeable)target ).close();
}
}
}
private static class OurErrorHandler implements ErrorHandler
{
/**
* This will be initialized to an instance of LoggerSwitch.SwitchingLogger;
* that is really reliable.
*/
private Logger m_reliableLogger;
OurErrorHandler( final Logger reliableLogger )
{
if ( reliableLogger == null )
{
throw new NullPointerException( "reliableLogger" );
}
m_reliableLogger = reliableLogger;
}
public void error( final String message, final Throwable throwable, final LogEvent event )
{
// let them know we're not OK
m_reliableLogger.fatalError( message, throwable );
// transmit the original error
final Priority p = event.getPriority();
final String nestedMessage = "nested log event: " + event.getMessage();
if ( p == Priority.DEBUG )
{
m_reliableLogger.debug( nestedMessage, event.getThrowable() );
}
else if ( p == Priority.INFO )
{
m_reliableLogger.info( nestedMessage, event.getThrowable() );
}
else if ( p == Priority.WARN )
{
m_reliableLogger.warn( nestedMessage, event.getThrowable() );
}
else if ( p == Priority.ERROR )
{
m_reliableLogger.error( nestedMessage, event.getThrowable() );
}
else if ( p == Priority.FATAL_ERROR)
{
m_reliableLogger.fatalError( nestedMessage, event.getThrowable() );
}
else
{
/** This just plainly can't happen :-)*/
m_reliableLogger.error( "unrecognized priority " + nestedMessage,
event.getThrowable() );
}
}
}
}
excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/Log4JConfLoggerManager.java 100644 0 0 6761 10304740432 27225 0 ustar 0 0 /*
* Copyright 2002-2004 The Apache Software Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avalon.excalibur.logger;
import org.apache.avalon.excalibur.logger.log4j.Log4JConfigurator;
import org.apache.avalon.framework.configuration.Configurable;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.configuration.ConfigurationUtil;
import org.apache.avalon.framework.context.Context;
import org.apache.avalon.framework.context.ContextException;
import org.apache.avalon.framework.context.Contextualizable;
import org.apache.log4j.LogManager;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* A LoggerManager for Log4j that will configure the Log4j subsystem
* using specified configuration.
*
* @author Avalon Development Team
* @version $Revision: 1.8 $ $Date: 2004/05/04 11:14:28 $
*/
public class Log4JConfLoggerManager
extends Log4JLoggerManager
implements Configurable, Contextualizable
{
private Context m_context;
/* (non-Javadoc)
* @see org.apache.avalon.framework.context.Contextualizable#contextualize(org.apache.avalon.framework.context.Context)
*/
public void contextualize(Context context) throws ContextException
{
m_context = context;
}
/**
* Work around a weird compilation problem. Can not call
* the constructor from fortress/ContextManager, get a
* file org\apache\log4j\spi\LoggerRepository.class not found
* new Log4JConfLoggerManager( lmDefaultLoggerName, lmLoggerName );
*/
public static Log4JConfLoggerManager newInstance( final String prefix,
final String switchToCategory )
{
return new Log4JConfLoggerManager( prefix, switchToCategory );
}
public Log4JConfLoggerManager( final String prefix, final String switchToCategory )
{
super( prefix, switchToCategory );
}
public Log4JConfLoggerManager()
{
}
public void configure( final Configuration configuration )
throws ConfigurationException
{
final Element element = ConfigurationUtil.toElement( configuration );
final Document document = element.getOwnerDocument();
final Element newElement = document.createElement( "log4j:configuration" );
final NodeList childNodes = element.getChildNodes();
final int length = childNodes.getLength();
for( int i = 0; i < length; i++ )
{
final Node node = childNodes.item( i );
final Node newNode = node.cloneNode( true );
newElement.appendChild( newNode );
}
document.appendChild( newElement );
Log4JConfigurator configurator = new Log4JConfigurator(m_context);
configurator.doConfigure( newElement, LogManager.getLoggerRepository());
}
}
excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/DefaultLogTargetManager.java 100644 0 0 7235 10304740432 27532 0 ustar 0 0 /*
* Copyright 2002-2004 The Apache Software Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avalon.excalibur.logger;
import java.util.HashMap;
import java.util.Map;
import org.apache.avalon.framework.configuration.Configurable;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.logger.AbstractLogEnabled;
import org.apache.log.LogTarget;
/**
* Default LogTargetManager implementation. It populates the LogTargetManager
* from a configuration file.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.14 $ $Date: 2004/03/10 13:54:50 $
* @since 4.0
*/
public class DefaultLogTargetManager
extends AbstractLogEnabled
implements LogTargetManager, LogTargetFactoryManageable, Configurable
{
/** Map for ID to LogTarget mapping */
final private Map m_targets = new HashMap();
/** The LogTargetFactoryManager object */
private LogTargetFactoryManager m_factoryManager;
/**
* Retrieves a LogTarget for an ID. If this LogTargetManager
* does not have the match a null will be returned.
*
* @param id The LogTarget ID
* @return the LogTarget or null if none is found.
*/
public final LogTarget getLogTarget( final String id )
{
return (LogTarget)m_targets.get( id );
}
/**
* Gets the LogTargetFactoryManager.
*/
public final void setLogTargetFactoryManager( final LogTargetFactoryManager logTargetFactoryManager )
{
m_factoryManager = logTargetFactoryManager;
}
/**
* Reads a configuration object and creates the log targets.
*
* @param configuration The configuration object.
* @throws ConfigurationException if the configuration is malformed
*/
public final void configure( final Configuration configuration )
throws ConfigurationException
{
if( null == m_factoryManager )
{
final String message = "LogTargetFactory not received.";
throw new ConfigurationException( message );
}
final Configuration[] confs = configuration.getChildren();
for( int i = 0; i < confs.length; i++ )
{
final String targetName = confs[ i ].getName();
final LogTargetFactory logTargetFactory = m_factoryManager.getLogTargetFactory( targetName );
if( logTargetFactory == null )
{
final String message =
"Factory definition for '" + targetName +
"' missing from logger configuration.";
throw new ConfigurationException( message );
}
final LogTarget logTarget = logTargetFactory.createTarget( confs[ i ] );
final String targetId = confs[ i ].getAttribute( "id" );
if( getLogger().isDebugEnabled() )
{
final String message = "Added new LogTarget of id " + targetId;
getLogger().debug( message );
}
m_targets.put( targetId, logTarget );
}
}
}
excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/ConsoleLoggerManager.java 100644 0 0 3225 10304740432 27072 0 ustar 0 0 /*
* Copyright 2002-2004 The Apache Software Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avalon.excalibur.logger;
import org.apache.avalon.framework.logger.ConsoleLogger;
import org.apache.avalon.framework.logger.Logger;
/**
* This is a very simple logger manager for debugging purpose
* that uses always the ConsoleLogger
*
* @author Avalon Development Team
* @version CVS $Revision: 1.1 $ $Date: 2004/03/10 13:54:49 $
*/
public class ConsoleLoggerManager implements LoggerManager
{
protected Logger m_logger;
/**
* Constructor
*/
public ConsoleLoggerManager()
{
m_logger = new ConsoleLogger();
}
/* (non-Javadoc)
* @see org.apache.avalon.excalibur.logger.LoggerManager#getDefaultLogger()
*/
public Logger getDefaultLogger()
{
return m_logger;
}
/* (non-Javadoc)
* @see org.apache.avalon.excalibur.logger.LoggerManager#getLoggerForCategory(java.lang.String)
*/
public Logger getLoggerForCategory(String categoryName)
{
return m_logger;
}
}
excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/AbstractLoggerManager.java 100644 0 0 20757 10304740432 27264 0 ustar 0 0 /*
* Copyright 2002-2004 The Apache Software Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avalon.excalibur.logger;
import java.util.HashMap;
import java.util.Map;
import org.apache.avalon.excalibur.logger.util.LoggerSwitch;
import org.apache.avalon.excalibur.logger.util.LoggerUtil;
import org.apache.avalon.framework.logger.LogEnabled;
import org.apache.avalon.framework.logger.Logger;
/**
*
* This abstract class implements LogEnabled.
* A derived class is expected to obtain a logger via
* getLogger()
and live with it.
* The Logger
supplied via enableLogging
* will be used both as the "initial" and as the "fallback" logger.
*
start()
the messages logger via
* getLogger().xxx()
will go to this loggerstart
* a recursive invocation of getLogger().xxx()
will be detected
* the message will be logged via the initial logger as a fallback.start()
.
*/
private String m_switchTo;
/** safeguards against double enableLogging()
invocation. */
private boolean m_enableLoggingInvoked = false;
/** safeguards against double start()
invocation. */
private boolean m_startInvoked = false;
/**
* The logger used to be returned from getDefaultLogger()
* and getLoggerForCategory("")
,
* if one has been forcibly set via a constructor.
*/
final private Logger m_defaultLoggerOverride;
/**
* Derived LoggerManager implementations should obtain
* a logger to log their own messages via this call.
* It is also safe to log messages about logging failures
* via this logger as it safeguards internally gainst
* recursion.
*/
protected Logger getLogger()
{
return m_logger;
}
/**
* Initializes AbstractLoggerManager.
* @param prefix the prefix to prepended to the category name
* on each invocation of getLoggerForCategory before
* passing the category name on to the underlying logging
* system (currently LogKit or Log4J).
* @param switchTo fuel for the start()
method;
* if null start()
will do nothing;
* if empty start()
will switch to
* getLoggerForCategory("")
.
*/
public AbstractLoggerManager( final String prefix, final String switchTo,
Logger defaultLoggerOverride )
{
m_prefix = prefix;
m_switchTo = switchTo;
m_switch = new LoggerSwitch( null, null );
m_logger = m_switch.get();
m_defaultLoggerOverride = defaultLoggerOverride;
}
/**
* Accept the logger we shall use as the initial and the fallback logger.
*/
public void enableLogging( final Logger fallbackLogger )
{
if ( m_enableLoggingInvoked )
{
throw new IllegalStateException( "enableLogging() already called" );
}
m_switch.setFallback( fallbackLogger );
m_enableLoggingInvoked = true;
}
/**
* Get a logger from ourselves and pass it to m_switch
.
*/
public void start()
{
if ( m_startInvoked )
{
throw new IllegalStateException( "start() already invoked" );
}
if ( m_switchTo != null )
{
if ( m_logger.isDebugEnabled() )
{
final String message = "LoggerManager: switching logging to " +
"this.getLoggerForCategory('" +
LoggerUtil.getFullCategoryName( m_prefix, m_switchTo) + "').";
m_logger.debug( message );
}
final Logger ourOwn = this.getLoggerForCategory( m_switchTo );
if ( ourOwn == null )
{
throw new NullPointerException( "ourOwn" );
}
m_switch.setPreferred( ourOwn );
if ( m_logger.isDebugEnabled() )
{
final String message = "LoggerManager: have switched logging to " +
"this.getLoggerForCategory('" +
LoggerUtil.getFullCategoryName( m_prefix, m_switchTo) + "').";
m_logger.debug( message );
}
}
else
{
if ( m_logger.isDebugEnabled() )
{
final String message = "LoggerManager: switchTo is null, " +
"no switch of our own logging.";
m_logger.debug( message );
}
}
m_startInvoked = true;
}
/** Startable.stop() empty implementation. */
public void stop(){}
/**
* Retruns the logger for the ""
category.
*/
public final Logger getDefaultLogger()
{
return getLoggerForCategory( null );
}
/**
* Actually create a logger wrapping underlying logger
* backed implementation for a give category. Bypasses the caching.
* Derived LoggerManager implementations should provide an implementation
* of this method.
*/
protected abstract Logger doGetLoggerForCategory( final String fullCategoryName );
/**
* Retrieves a Logger from a category name. Usually
* the category name refers to a configuration attribute name. If
* this LogKitManager does not have the match the default Logger will
* be returned and a warning is issued.
*/
public final Logger getLoggerForCategory( final String categoryName )
{
if ( m_defaultLoggerOverride != null &&
( categoryName == null || categoryName.length() == 0 ) )
{
return m_defaultLoggerOverride;
}
final String fullCategoryName =
LoggerUtil.getFullCategoryName( m_prefix, categoryName );
final Logger logger;
final Logger newLogger;
synchronized( m_loggers )
{
logger = (Logger)m_loggers.get( fullCategoryName );
if ( logger == null )
{
newLogger = doGetLoggerForCategory( fullCategoryName );
m_loggers.put( fullCategoryName, newLogger );
}
else
{
/* Let's have no "variable might not have been initialized". */
newLogger = null;
}
}
if( null != logger )
{
if( m_logger.isDebugEnabled() )
{
m_logger.debug( "Logger for category " + fullCategoryName + " returned" );
}
return logger;
}
if( m_logger.isDebugEnabled() )
{
m_logger.debug( "Logger for category " + fullCategoryName + " not defined in "
+ "configuration. New Logger created and returned" );
}
return newLogger;
}
}
excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/DefaultLogKitManager.java 100644 0 0 26410 10304740432 27047 0 ustar 0 0 /*
* Copyright 2002-2004 The Apache Software Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avalon.excalibur.logger;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import org.apache.avalon.framework.configuration.Configurable;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
import org.apache.avalon.framework.container.ContainerUtil;
import org.apache.avalon.framework.context.Context;
import org.apache.avalon.framework.context.ContextException;
import org.apache.avalon.framework.context.Contextualizable;
import org.apache.avalon.framework.logger.AbstractLogEnabled;
import org.apache.avalon.framework.logger.LogKitLogger;
import org.apache.avalon.framework.logger.Loggable;
import org.apache.log.Hierarchy;
import org.apache.log.LogTarget;
import org.apache.log.Logger;
import org.apache.log.Priority;
/**
* Default LogManager implementation. It populates the LogManager
* from a configuration file.
*
* @deprecated we should use the new LogKitLoggerManager interface that directly
* supports the new framework Logger interface.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.12 $ $Date: 2004/03/10 13:54:49 $
* @since 4.0
*/
public class DefaultLogKitManager
extends AbstractLogEnabled
implements LogKitManager, Loggable, Contextualizable, Configurable
{
/** Map for name to logger mapping */
final private Map m_loggers = new HashMap();
/** The context object */
private Context m_context;
/** The hierarchy private to LogKitManager */
private Hierarchy m_hierarchy;
/** The root logger to configure */
private String m_prefix;
/**
* Creates a new DefaultLogKitManager
. It will use a new Hierarchy
.
*/
public DefaultLogKitManager()
{
this( new Hierarchy() );
}
/**
* Creates a new DefaultLogKitManager
with an existing Hierarchy
.
*/
public DefaultLogKitManager( final Hierarchy hierarchy )
{
this( null, hierarchy );
}
/**
* Creates a new DefaultLogKitManager
using
* specified logger name as root logger.
*/
public DefaultLogKitManager( final String prefix )
{
this( prefix, new Hierarchy() );
}
/**
* Creates a new DefaultLogKitManager
with an existing Hierarchy
using
* specified logger name as root logger.
*/
public DefaultLogKitManager( final String prefix, final Hierarchy hierarchy )
{
m_prefix = prefix;
m_hierarchy = hierarchy;
}
public void setLogger( final Logger logger )
{
enableLogging( new LogKitLogger( logger ) );
}
/**
* Retrieves a Logger from a category name. Usually
* the category name refers to a configuration attribute name. If
* this LogKitManager does not have the match the default Logger will
* be returned and a warning is issued.
*
* @param categoryName The category name of a configured Logger.
* @return the Logger.
*/
public final Logger getLogger( final String categoryName )
{
final Logger logger = (Logger)m_loggers.get( categoryName );
if( null != logger )
{
if( getLogger().isDebugEnabled() )
{
getLogger().debug( "Logger for category " + categoryName + " returned" );
}
return logger;
}
if( getLogger().isDebugEnabled() )
{
getLogger().debug( "Logger for category " + categoryName
+ " not defined in configuration. New Logger created and returned" );
}
return m_hierarchy.getLoggerFor( categoryName );
}
/**
* Retrieve Hierarchy for Loggers configured by the system.
*
* @return the Hierarchy
*/
public Hierarchy getHierarchy()
{
return m_hierarchy;
}
/**
* Reads a context object.
*
* @param context The context object.
* @throws ContextException if the context is malformed
*/
public final void contextualize( final Context context )
throws ContextException
{
m_context = context;
}
/**
* Reads a configuration object and creates the category mapping.
* If the <categories/>
element has an attribute
* named debug
, it will try to load a configuration file
* specified by that attribute. The contents of that configuration
* file will be the same as the <categories/>
element.
*
* @param configuration The configuration object.
* @throws ConfigurationException if the configuration is malformed
*/
public final void configure( final Configuration configuration )
throws ConfigurationException
{
final Configuration factories = configuration.getChild( "factories" );
final LogTargetFactoryManager targetFactoryManager = setupTargetFactoryManager( factories );
final Configuration targets = configuration.getChild( "targets" );
final LogTargetManager targetManager = setupTargetManager( targets, targetFactoryManager );
final Configuration categories = configuration.getChild( "categories" );
final String debugURL = configuration.getAttribute( "debug", null );
final Configuration[] category = categories.getChildren( "category" );
setupLoggers( targetManager, m_prefix, category );
if( null != debugURL )
{
try
{
final File rootContext = (File)m_context.get( "context-root" );
DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
Configuration debugCategories = builder.buildFromFile( new File( rootContext, debugURL ) );
final Configuration[] debugCat = debugCategories.getChildren( "category" );
setupLoggers( targetManager, m_prefix, debugCat );
}
catch( ConfigurationException ce )
{
throw ce;
}
catch( Exception e )
{
getLogger().info( "Either there was no \"debug.xlog\" file, or there was a problem reading it." );
getLogger().debug( e.getMessage(), e );
// swallow exception because it is not critical.
}
}
}
/**
* Setup a LogTargetFactoryManager
*
* @param configuration The configuration object.
* @throws ConfigurationException if the configuration is malformed
*/
private final LogTargetFactoryManager setupTargetFactoryManager( final Configuration configuration )
throws ConfigurationException
{
final DefaultLogTargetFactoryManager targetFactoryManager = new DefaultLogTargetFactoryManager();
ContainerUtil.enableLogging( targetFactoryManager, getLogger() );
try
{
ContainerUtil.contextualize( targetFactoryManager, m_context );
}
catch( final ContextException ce )
{
final String message = "cannot contextualize default factory manager";
throw new ConfigurationException( message, ce );
}
ContainerUtil.configure( targetFactoryManager, configuration );
return targetFactoryManager;
}
/**
* Setup a LogTargetManager
*
* @param configuration The configuration object.
* @throws ConfigurationException if the configuration is malformed
*/
private final LogTargetManager setupTargetManager( final Configuration configuration,
final LogTargetFactoryManager targetFactoryManager )
throws ConfigurationException
{
final DefaultLogTargetManager targetManager = new DefaultLogTargetManager();
ContainerUtil.enableLogging( targetManager, getLogger() );
try
{
ContainerUtil.contextualize( targetManager, m_context );
}
catch( final ContextException ce )
{
final String message = "cannot contextualize factory manager";
throw new ConfigurationException( message, ce );
}
targetManager.setLogTargetFactoryManager( targetFactoryManager );
ContainerUtil.configure( targetManager, configuration );
return targetManager;
}
/**
* Setup Loggers
*
* @param categories The array object of configurations for categories.
* @throws ConfigurationException if the configuration is malformed
*/
private final void setupLoggers( final LogTargetManager targetManager,
final String parentCategory,
final Configuration[] categories )
throws ConfigurationException
{
for( int i = 0; i < categories.length; i++ )
{
final String category = categories[ i ].getAttribute( "name" );
final String loglevel = categories[ i ].getAttribute( "log-level" ).toUpperCase();
final Configuration[] targets = categories[ i ].getChildren( "log-target" );
final LogTarget[] logTargets = new LogTarget[ targets.length ];
for( int j = 0; j < targets.length; j++ )
{
final String id = targets[ j ].getAttribute( "id-ref" );
logTargets[ j ] = targetManager.getLogTarget( id );
}
if( "".equals( category ) && logTargets.length > 0 )
{
m_hierarchy.setDefaultPriority( Priority.getPriorityForName( loglevel ) );
m_hierarchy.setDefaultLogTargets( logTargets );
}
final String fullCategory;
if( null == parentCategory )
{
fullCategory = category;
}
else
{
fullCategory = parentCategory + Logger.CATEGORY_SEPARATOR + category;
}
final Logger logger =
m_hierarchy.getLoggerFor( fullCategory );
m_loggers.put( fullCategory, logger );
if( getLogger().isDebugEnabled() )
{
getLogger().debug( "added logger for category " + fullCategory );
}
logger.setPriority( Priority.getPriorityForName( loglevel ) );
logger.setLogTargets( logTargets );
final Configuration[] subCategories = categories[ i ].getChildren( "category" );
if( null != subCategories )
{
setupLoggers( targetManager, fullCategory, subCategories );
}
}
}
}
excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/ServletLogger.java 100644 0 0 20034 10304740432 25636 0 ustar 0 0 /*
* Copyright 2002-2004 The Apache Software Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avalon.excalibur.logger;
import org.apache.avalon.framework.logger.Logger;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
/**
* Logger to bootstrap avalon application iside a servlet.
* Intended to be used as a logger for Fortress
* ContextManager/ContainerManager.
*
* Adapted from ConsoleLogger.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.5 $ $Date: 2004/03/10 13:54:50 $
*/
public class ServletLogger implements Logger
{
/** Typecode for debugging messages. */
public static final int LEVEL_DEBUG = 0;
/** Typecode for informational messages. */
public static final int LEVEL_INFO = 1;
/** Typecode for warning messages. */
public static final int LEVEL_WARN = 2;
/** Typecode for error messages. */
public static final int LEVEL_ERROR = 3;
/** Typecode for fatal error messages. */
public static final int LEVEL_FATAL = 4;
/** Typecode for disabled log levels. */
public static final int LEVEL_DISABLED = 5;
private final ServletContext m_servletContext;
private final int m_logLevel;
private final String m_prompt;
/**
* Creates a new ServletLogger with the priority set to DEBUG.
*/
public ServletLogger( final ServletConfig servletConfig )
{
this( servletConfig, LEVEL_DEBUG );
}
/** Helper method to write the constructors. */
private void checkState()
{
if ( m_servletContext == null )
{
throw new NullPointerException( "servletContext" );
}
if ( m_logLevel < LEVEL_DEBUG || m_logLevel > LEVEL_DISABLED )
{
throw new IllegalArgumentException( "Bad logLevel: " + m_logLevel );
}
}
/**
* Creates a new ServletLogger.
* @param servletContext ServletContext to log messages to
* @param prompt text to prepend to every message
* @param logLevel log level typecode
*/
public ServletLogger( final ServletContext servletContext, final String prompt,
final int logLevel )
{
m_servletContext = servletContext;
m_logLevel = logLevel;
checkState();
m_prompt = prompt;
}
/**
* Creates a new ServletLogger.
* @param servletConfig the servletConfig to extract ServletContext from;
* also the servlet name is extracted to be prepended to every message.
* @param logLevel log level typecode
*/
public ServletLogger( final ServletConfig servletConfig, final int logLevel )
{
m_servletContext = servletConfig.getServletContext();
m_logLevel = logLevel;
checkState();
final String servletName = servletConfig.getServletName();
if ( servletName == null || "".equals( servletName ) )
{
m_prompt = "unknown: ";
}
else
{
m_prompt = servletName + ": ";
}
}
/**
* Logs a debugging message.
*
* @param message a String
value
*/
public void debug( final String message )
{
debug( message, null );
}
/**
* Logs a debugging message and an exception.
*
* @param message a String
value
* @param throwable a Throwable
value
*/
public void debug( final String message, final Throwable throwable )
{
if( m_logLevel <= LEVEL_DEBUG )
{
m_servletContext.log( m_prompt + "[DEBUG] " + message, throwable );
}
}
/**
* Returns true
if debug-level logging is enabled, false otherwise.
*
* @return true
if debug-level logging
*/
public boolean isDebugEnabled()
{
return m_logLevel <= LEVEL_DEBUG;
}
/**
* Logs an informational message.
*
* @param message a String
value
*/
public void info( final String message )
{
info( message, null );
}
/**
* Logs an informational message and an exception.
*
* @param message a String
value
* @param throwable a Throwable
value
*/
public void info( final String message, final Throwable throwable )
{
if( m_logLevel <= LEVEL_INFO )
{
m_servletContext.log( m_prompt + "[INFO] " + message, throwable );
}
}
/**
* Returns true
if info-level logging is enabled, false otherwise.
*
* @return true
if info-level logging is enabled
*/
public boolean isInfoEnabled()
{
return m_logLevel <= LEVEL_INFO;
}
/**
* Logs a warning message.
*
* @param message a String
value
*/
public void warn( final String message )
{
warn( message, null );
}
/**
* Logs a warning message and an exception.
*
* @param message a String
value
* @param throwable a Throwable
value
*/
public void warn( final String message, final Throwable throwable )
{
if( m_logLevel <= LEVEL_WARN )
{
m_servletContext.log( m_prompt + "[WARNING] " + message, throwable );
}
}
/**
* Returns true
if warn-level logging is enabled, false otherwise.
*
* @return true
if warn-level logging is enabled
*/
public boolean isWarnEnabled()
{
return m_logLevel <= LEVEL_WARN;
}
/**
* Logs an error message.
*
* @param message a String
value
*/
public void error( final String message )
{
error( message, null );
}
/**
* Logs an error message and an exception.
*
* @param message a String
value
* @param throwable a Throwable
value
*/
public void error( final String message, final Throwable throwable )
{
if( m_logLevel <= LEVEL_ERROR )
{
m_servletContext.log( m_prompt + "[ERROR] " + message, throwable );
}
}
/**
* Returns true
if error-level logging is enabled, false otherwise.
*
* @return true
if error-level logging is enabled
*/
public boolean isErrorEnabled()
{
return m_logLevel <= LEVEL_ERROR;
}
/**
* Logs a fatal error message.
*
* @param message a String
value
*/
public void fatalError( final String message )
{
fatalError( message, null );
}
/**
* Logs a fatal error message and an exception.
*
* @param message a String
value
* @param throwable a Throwable
value
*/
public void fatalError( final String message, final Throwable throwable )
{
if( m_logLevel <= LEVEL_FATAL )
{
m_servletContext.log( m_prompt + "[FATAL ERROR] " + message, throwable );
}
}
/**
* Returns true
if fatal-level logging is enabled, false otherwise.
*
* @return true
if fatal-level logging is enabled
*/
public boolean isFatalErrorEnabled()
{
return m_logLevel <= LEVEL_FATAL;
}
/**
* Just returns this logger (ServletLogger
is not hierarchical).
*
* @param name ignored
* @return this logger
*/
public Logger getChildLogger( final String name )
{
return this;
}
}
excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/log4j/Log4JAdapter.java 100644 0 0 4462 10304740432 26300 0 ustar 0 0 /*
* Copyright 2002-2004 The Apache Software Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avalon.excalibur.logger.log4j;
import org.apache.avalon.framework.logger.Logger;
import org.apache.avalon.framework.logger.AbstractLogEnabled;
import org.apache.avalon.excalibur.logger.Log4JLogger;
import org.apache.avalon.excalibur.logger.LoggerManager;
import org.apache.log4j.spi.LoggerRepository;
/**
* This class sits on top of an existing Log4J Hierarchy
* and returns logger wrapping Log4J loggers.
*
* Attach PrefixDecorator and/or CachingDecorator if desired.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.4 $ $Date: 2004/03/10 13:54:51 $
* @since 4.0
*/
public class Log4JAdapter extends AbstractLogEnabled implements LoggerManager
{
protected final LoggerRepository m_hierarchy;
public Log4JAdapter( final LoggerRepository hierarchy )
{
if ( hierarchy == null ) throw new NullPointerException( "hierarchy" );
m_hierarchy = hierarchy;
}
/**
* Return the Logger for the specified category.
* Log4J probably won't like the "" category name
* so we shall better return its getRootLogger() instead.
*/
public Logger getLoggerForCategory( final String categoryName )
{
if ( null == categoryName || categoryName.length() == 0 )
{
return getDefaultLogger();
}
else
{
return new Log4JLogger( m_hierarchy.getLogger( categoryName ) );
}
}
/**
* Return the default Logger. This is basically the same
* as getting the Logger for the "" category.
*/
public Logger getDefaultLogger()
{
return new Log4JLogger( m_hierarchy.getRootLogger() );
}
}
excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/log4j/Log4JConfAdapter.java 100644 0 0 10070 10304740432 27116 0 ustar 0 0 /*
* Copyright 2002-2004 The Apache Software Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avalon.excalibur.logger.log4j;
import org.apache.avalon.framework.configuration.Configurable;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.configuration.ConfigurationUtil;
import org.apache.avalon.framework.context.Context;
import org.apache.avalon.framework.context.ContextException;
import org.apache.avalon.framework.context.Contextualizable;
import org.apache.log4j.Hierarchy;
import org.apache.log4j.Level;
import org.apache.log4j.spi.RootCategory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* A LoggerManager for Log4j that will configure the Log4j subsystem
* using specified configuration.
* * Note that in case of logging errors Log4J will (via the * org.apache.log4j.helpers.LogLog class) write to System.err. * This can be switched off but we can not substitute our * own handler to log erros the way we prefer to do this. :-( * *
* So, unlike the LogKit case we have no Log4JLogger helper to * implement and hence a different architecture: this class * is not a helper but a regular subclass of Log4JAdapter. * *
* Attach PrefixDecorator and/or CachingDecorator if desired. * * @author Avalon Development Team * @version CVS $Revision: 1.4 $ $Date: 2004/03/10 13:54:51 $ * @since 4.0 */ public class Log4JConfAdapter extends Log4JAdapter implements Configurable, Contextualizable { private Context m_context; /* (non-Javadoc) * @see org.apache.avalon.framework.context.Contextualizable#contextualize(org.apache.avalon.framework.context.Context) */ public void contextualize(Context context) throws ContextException { m_context = context; } /** * This constructor creates a completely independent * Log4J hierarchy. If you want to log to an existing * Log4J hierarchy please use Log4JAdapter. This class * always creates a new private hierarchy and configures * it all by itself. */ public Log4JConfAdapter() { /** * Copied from org.apache.log4j.LogManager. */ super( new Hierarchy( new RootCategory( Level.ALL ) ) ); } /** * Feed our configuration to Log4J. */ public void configure( final Configuration configuration ) throws ConfigurationException { final Element element = ConfigurationUtil.toElement( configuration ); final Document document = element.getOwnerDocument(); final Element newElement = document.createElement( "log4j:configuration" ); final NodeList childNodes = element.getChildNodes(); final int length = childNodes.getLength(); for( int i = 0; i < length; i++ ) { final Node node = childNodes.item( i ); final Node newNode = node.cloneNode( true ); newElement.appendChild( newNode ); } document.appendChild( newElement ); /** * Copied from org.apache.log4j.xml.DomConfigurator configure(). * We want our own hierarchy to be configured, so we shall * be a bit more elaborate then just calling configure(). */ final Log4JConfigurator domConfigurator = new Log4JConfigurator( m_context ); domConfigurator.doConfigure( newElement, m_hierarchy ); } } excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/log4j/Log4JConfigurator.java 100644 0 0 10772 10304740432 27403 0 ustar 0 0 /* * Copyright 1999-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avalon.excalibur.logger.log4j; import org.apache.avalon.framework.context.Context; import org.apache.avalon.framework.context.ContextException; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.xml.DOMConfigurator; /** * This is a configurator for log4j that supports variable substitution * * @version CVS $Id: Log4JConfigurator.java,v 1.2 2004/06/14 14:07:09 cziegeler Exp $ */ public class Log4JConfigurator extends DOMConfigurator { protected Context context; public Log4JConfigurator(Context context) { this.context = context; } protected String subst(String value) { try { return this.substVars(value); } catch (IllegalArgumentException e) { LogLog.warn("Could not perform variable substitution.", e); return value; } } static String DELIM_START = "${"; static char DELIM_STOP = '}'; static int DELIM_START_LEN = 2; static int DELIM_STOP_LEN = 1; /** * This is directly copied from log4j's OptionConverter class. * The only difference is the getting of a property. */ public String substVars(String val) throws IllegalArgumentException { StringBuffer sbuf = new StringBuffer(); int i = 0; int j, k; while(true) { j=val.indexOf(DELIM_START, i); if (j == -1) { // no more variables if(i==0) { // this is a simple string return val; } else { // add the tail string which contails no variables and return the result. sbuf.append(val.substring(i, val.length())); return sbuf.toString(); } } else { sbuf.append(val.substring(i, j)); k = val.indexOf(DELIM_STOP, j); if(k == -1) { throw new IllegalArgumentException('"'+val+ "\" has no closing brace. Opening brace at position " + j + '.'); } else { j += DELIM_START_LEN; String key = val.substring(j, k); // first try in System properties String replacement = this.getSystemProperty(key); // then try props parameter if (replacement == null && this.context != null) { try { Object o = this.context.get(key); if ( o != null ) { replacement = o.toString(); } } catch (ContextException ce) { LogLog.debug("Was not allowed to read context property \""+key+"\"."); } } if (replacement != null) { // Do variable substitution on the replacement string // such that we can solve "Hello ${x2}" as "Hello p1" // the where the properties are // x1=p1 // x2=${x1} String recursiveReplacement = substVars(replacement); sbuf.append(recursiveReplacement); } i = k + DELIM_STOP_LEN; } } } } /** * This is directly copied from log4j's OptionConverter class. * The only difference is the getting of a property. */ public String getSystemProperty(String key) { try { return System.getProperty(key, null); } catch(Throwable e) { // MS-Java throws com.ms.security.SecurityExceptionEx LogLog.debug("Was not allowed to read system property \""+key+"\"."); return null; } } } excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/LogTargetFactoryManageable.java 100644 0 0 2351 10304740432 30211 0 ustar 0 0 /* * Copyright 2002-2004 The Apache Software Foundation * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avalon.excalibur.logger; /** * LogTargetFactoryManageable Interface, use this to set the LogTargetFactoryManager * for child Components. * * @author Avalon Development Team * @version CVS $Revision: 1.7 $ $Date: 2004/03/10 13:54:50 $ * @since 4.0 */ public interface LogTargetFactoryManageable { /** * Sets the LogTargetFactoryManager for child components. Can be for special * purpose components, however it is used mostly internally. */ void setLogTargetFactoryManager( LogTargetFactoryManager logTargetFactoryManager ); } ././@LongLink 100644 0 0 147 10304740432 10252 L ustar 0 0 excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/decorator/LoggerManagerDecorator.java excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/decorator/LoggerManagerDecorator.ja100644 0 0 11204 10304740432 31061 0 ustar 0 0 /* * Copyright 2002-2004 The Apache Software Foundation * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avalon.excalibur.logger.decorator; import org.apache.avalon.excalibur.logger.LoggerManager; import org.apache.avalon.framework.activity.Disposable; import org.apache.avalon.framework.activity.Startable; import org.apache.avalon.framework.configuration.Configurable; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.avalon.framework.container.ContainerUtil; import org.apache.avalon.framework.context.Context; import org.apache.avalon.framework.context.ContextException; import org.apache.avalon.framework.context.Contextualizable; import org.apache.avalon.framework.logger.LogEnabled; import org.apache.avalon.framework.logger.Logger; /** * This is the base class to create LoggerManager decorators. * It passes all lifecycle and LoggerManagerc * calls onto the wrapped object. * *
Decorators are expected to be slim - be able to run * for instance both with and without having their * enableLogging() method called. * *
This constraint is imposed to allow decorators to * be applicable to an object both at its burth, like * *
* C c = new C(); * DecoratorX d = new DecoratorX( c ); * x.enableLogging( logger ); ** * and after the object has been completely configured * *
* C c = (C)manager.lookup( C.ROLE ); * DecoratorX d = new DecoratorX( c ); ** * If this constrianed is not obeyed this should be clearly * stated in the javadocs. For instance, LogToSelfDecorator * _only_ makes sense if it passes the
enableLogging
* call through it.
*
*
* This implementation is incomplete,
* it passes only those calls that are needed in
*
* org.apache.avalon.excalibur.logger.decorator.*
and
* org.apache.avalon.excalibur.logger.adapter.*
:
*
* LogEnabled * Contextualizable * Configurable * Startable * Disposable ** * This object differes from LoggerManagerTee by being abstract, * by absence of addTee() public method and by implementation. * LoggerManagerTee might be used instead of this but maintaining * it as a separate class seemed cleaner. * * @author Avalon Development Team * @version CVS $Revision: 1.4 $ $Date: 2004/03/10 13:54:50 $ * @since 4.0 */ public abstract class LoggerManagerDecorator implements LoggerManager, LogEnabled, Contextualizable, Configurable, Startable, Disposable { /** * The wrapped-in LoggerManager. */ protected final LoggerManager m_loggerManager; public LoggerManagerDecorator( final LoggerManager loggerManager ) { if ( loggerManager == null ) throw new NullPointerException( "loggerManager" ); m_loggerManager = loggerManager; } public void enableLogging( final Logger logger ) { ContainerUtil.enableLogging( m_loggerManager, logger ); } public void contextualize( final Context context ) throws ContextException { ContainerUtil.contextualize( m_loggerManager, context ); } public void configure( final Configuration configuration ) throws ConfigurationException { ContainerUtil.configure( m_loggerManager, configuration ); } public void start() throws Exception { ContainerUtil.start( m_loggerManager ); } public void stop() throws Exception { ContainerUtil.stop( m_loggerManager ); } public void dispose() { ContainerUtil.dispose( m_loggerManager ); } /** * Return the Logger for the specified category. */ public Logger getLoggerForCategory( final String categoryName ) { return m_loggerManager.getLoggerForCategory( categoryName ); } /** * Return the default Logger. This is basically the same * as getting the Logger for the "" category. */ public Logger getDefaultLogger() { return m_loggerManager.getDefaultLogger(); } } excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/decorator/PrefixDecorator.java 100644 0 0 5136 10304740432 30122 0 ustar 0 0 /* * Copyright 2002-2004 The Apache Software Foundation * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avalon.excalibur.logger.decorator; import org.apache.avalon.framework.logger.Logger; import org.apache.avalon.excalibur.logger.LoggerManager; import org.apache.avalon.excalibur.logger.util.LoggerUtil; /** * This class implements LoggerManager interface by * prepending a prefix to all requests and letting the * wrapped LoggerManager actually create the loggers. * * @author Avalon Development Team * @version CVS $Revision: 1.3 $ $Date: 2004/03/10 13:54:50 $ * @since 4.0 */ public class PrefixDecorator extends LoggerManagerDecorator implements LoggerManager { private final String m_prefix; /** * Creates a PrefixDecorator instance. * @param prefix the prefix to prepend; * can be neither null nor empty. * This is done to avoid ambiguity * in the getDefaultLogger() method - what would we call * in such case getDefaultLogger() or getLoggerForCategory("") ? * */ public PrefixDecorator( final LoggerManager loggerManager, final String prefix ) { super( loggerManager ); if ( prefix == null ) throw new NullPointerException( "prefix" ); if ( "".equals( prefix ) ) throw new IllegalArgumentException( "prefix can't be empty" ); m_prefix = prefix; } /** * Return the Logger for the specified category. */ public Logger getLoggerForCategory( final String categoryName ) { final String fullCategoryName = LoggerUtil.getFullCategoryName( m_prefix, categoryName ); return m_loggerManager.getLoggerForCategory( fullCategoryName ); } /** * Return the default Logger. This is basically the same * as getting the Logger for the "" category. */ public Logger getDefaultLogger() { final String fullCategoryName = LoggerUtil.getFullCategoryName( m_prefix, null ); return m_loggerManager.getLoggerForCategory( fullCategoryName ); } } ././@LongLink 100644 0 0 151 10304740432 10245 L ustar 0 0 excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/decorator/OverrideDefaultDecorator.java excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/decorator/OverrideDefaultDecorator.100644 0 0 4720 10304740432 31105 0 ustar 0 0 /* * Copyright 2002-2004 The Apache Software Foundation * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avalon.excalibur.logger.decorator; import org.apache.avalon.framework.logger.Logger; import org.apache.avalon.excalibur.logger.LoggerManager; /** * Overrides the value passed from getDefaultLogger(). * * @author Avalon Development Team * @version CVS $Revision: 1.3 $ $Date: 2004/03/10 13:54:50 $ * @since 4.0 */ public class OverrideDefaultDecorator extends LoggerManagerDecorator { /** * The override value for getDefaultLogger() and for * getLoggerForCategory(""), getLoggerForCategory( null ); */ private final Logger m_defaultLogger; /** * Creates an
OverrideDecorator
instance.
* @param defaultLogger OverrideDecorator
is unique in that
* it won't tolerate a null extra argument: if this
* argument is null
a NullPointerException will
* be thrown. This ensures that no logging surprises will occur.
*/
public OverrideDefaultDecorator(
final LoggerManager loggerManager, final Logger defaultLogger )
{
super( loggerManager );
if ( defaultLogger == null ) throw new NullPointerException( "defaultLogger" );
m_defaultLogger = defaultLogger;
}
/**
* Return the Logger for the specified category.
*/
public Logger getLoggerForCategory( final String categoryName )
{
if ( categoryName == null || categoryName.length() == 0 )
{
return m_defaultLogger;
}
else
{
return m_loggerManager.getLoggerForCategory( categoryName );
}
}
/**
* Return the default Logger. This is basically the same
* as getting the Logger for the "" category.
*/
public Logger getDefaultLogger()
{
return m_defaultLogger;
}
}
excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/decorator/CachingDecorator.java 100644 0 0 6732 10304740432 30224 0 ustar 0 0 /*
* Copyright 2002-2004 The Apache Software Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avalon.excalibur.logger.decorator;
import org.apache.avalon.framework.logger.Logger;
import org.apache.avalon.excalibur.logger.LoggerManager;
import java.util.Map;
import java.util.HashMap;
/**
* This class implements LoggerManager interface by
* passing all the job to a wrapped LoggerManager,
* but the returened Loggers are cached.
*
* All operations of this class are synchronized via
* a single lock. As the LoggerManager
is
* not expected to be a performance bottleneck probably
* this design will be good enough.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.3 $ $Date: 2004/03/10 13:54:50 $
* @since 4.0
*/
public class CachingDecorator extends LoggerManagerDecorator
{
/**
* Logger-s cache.
* All access synchronized( m_loggers ).
*/
private final Map m_loggers = new HashMap();
/**
* This variable caches the result of
* getDefaultLogger(). This class will
* treat getDefaultLogger() and getLoggerForCategory("")
* on our wrapped LoggerManager as being potentially
* different, although all of the existing adapters
* probably return the same Logger for both.
*
* Access synchronized( this );
*/
private Logger m_defaultLogger = null;
/**
* Creates a CachingDecorator
instance.
*/
public CachingDecorator( final LoggerManager loggerManager )
{
super( loggerManager );
}
/**
* Return the Logger for the specified category.
*/
public Logger getLoggerForCategory( final String categoryName )
{
synchronized( m_loggers )
{
Logger logger = (Logger) m_loggers.get( categoryName );
if ( logger == null )
{
logger = m_loggerManager.getLoggerForCategory( categoryName );
if ( logger == null )
{
final String message = "getLoggerForCategory('" +
categoryName + "')";
throw new NullPointerException( message );
}
m_loggers.put( categoryName, logger );
}
return logger;
}
}
/**
* Return the default Logger. Although it is expected
* that the wrapped loggerManager will return the same
* as getLoggerForCategory("") we cache the value separtely.
*/
public Logger getDefaultLogger()
{
synchronized( this )
{
if ( m_defaultLogger == null )
{
m_defaultLogger = m_loggerManager.getDefaultLogger();
if ( m_defaultLogger == null )
{
throw new NullPointerException ( "getDefaultLogger()" );
}
}
return m_defaultLogger;
}
}
}
excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/decorator/LogToSelfDecorator.java 100644 0 0 11734 10304740432 30544 0 ustar 0 0 /*
* Copyright 2002-2004 The Apache Software Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avalon.excalibur.logger.decorator;
import org.apache.avalon.framework.logger.Logger;
import org.apache.avalon.framework.container.ContainerUtil;
import org.apache.avalon.excalibur.logger.LoggerManager;
import org.apache.avalon.excalibur.logger.util.LoggerSwitch;
/**
*
* This class intercepts the class passed to us via
* enableLogging()
and substibutes it
* by LoggerSwitch.get()
logger.
*
* Later on at the start()
stage
* we assume that our wrapped LoggerManager has already
* completely initialized itself and extract
* a Logger
from it.
*
* LoggerSwitch
allowes us to supply this
* logger to it via LoggerSwitch.setPreferred()
.
* This has the effect of all the log messages directed
* to LoggerSwitch.get()
obtained logger
* being directed to the new Logger
unless
* a recursion error happens.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.4 $ $Date: 2004/03/10 13:54:50 $
* @since 4.0
*/
public class LogToSelfDecorator extends LoggerManagerDecorator
{
/* The category to switch our logging to. */
private final String m_switchTo;
/* The LoggerSwitch object controlling our substitute Logger. */
private LoggerSwitch m_switch;
/**
* Our substitute logger obtained from m_switch.
* Used for our own logging.
*/
private Logger m_logger;
/**
* Creates a LogToSelfDecorator instance.
* @param switchTo the name of the category we should extract
* a Logger and switch our logging to at the
* start()
stage; can not be null;
* empty value causes logging to be switched to the
* "" category.
*/
public LogToSelfDecorator( final LoggerManager loggerManager, final String switchTo )
{
super( loggerManager );
if ( switchTo == null ) throw new NullPointerException( "switchTo" );
m_switchTo = switchTo;
}
/**
* Substitutes the supplied logger by m_switch.get()
.
* The substiting logger is used both for our own logging and
* passed onto our decorated LoggerManager
.
* @param logger the logger supplied for us and our wrapped
* LoggerManager; we chould survive with a null logger
* (LoggerSwitch create a NullLogger in this case), but
* for better error detection we shall rather blow up.
*/
public void enableLogging( final Logger logger )
{
if ( m_switch != null )
{
throw new IllegalStateException( "enableLogging() already called" );
}
if ( logger == null )
{
throw new NullPointerException( "logger" );
}
m_switch = new LoggerSwitch( logger );
m_logger = m_switch.get();
ContainerUtil.enableLogging( m_loggerManager, m_logger );
}
/**
* Invokes start()
on our wrapped
* LoggerManager
and swithces the
* logger used by us and all objects that we
* decorate for a logger extracted from our
* wrapped LoggerManager
.
*/
public void start() throws Exception
{
/**
* If our LoggerManager is Startable
* its start()
will be invoked now.
*/
super.start();
final Logger preferred = m_loggerManager.getLoggerForCategory( m_switchTo );
if ( m_logger.isDebugEnabled() )
{
/**
* We have to identify ourselves now via 'LogToSelfDecorator:'
* because we are likely to be logging to a shared bootstrap
* logger, not to a dedicated category Logger.
*/
final String message = "LogToSelfDecorator: switching logging to '" +
m_switchTo + "'";
m_logger.debug( message );
}
m_switch.setPreferred( preferred );
if ( m_logger.isDebugEnabled() )
{
/**
* We do not have to identify ourselves now, we're already logging
* to a proper category.
*/
final String message = "Have switched logging to '" +
m_switchTo + "'";
m_logger.debug( message );
}
}
}
excalibur-logger-2.1/src/java/org/apache/avalon/excalibur/logger/Log4JLoggerManager.java 100644 0 0 14405 10304740432 26431 0 ustar 0 0 /*
* Copyright 2002-2004 The Apache Software Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avalon.excalibur.logger;
import org.apache.avalon.framework.logger.Logger;
import org.apache.log4j.LogManager;
import org.apache.log4j.spi.LoggerRepository;
/**
* Log4JLoggerManager implementation. This is the interface used to get instances of
* a Logger for your system. This manager does not set up the categories--it
* leaves that as an excercise for Log4J's construction.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.21 $ $Date: 2004/05/04 13:08:00 $
* @since 4.1
*/
public class Log4JLoggerManager extends AbstractLoggerManager
implements LoggerManager
{
/** The hierarchy private to Log4JManager */
private final LoggerRepository m_hierarchy;
/**
* Creates a new DefaultLog4JManager
. It will use a new Hierarchy
.
*/
public Log4JLoggerManager()
{
this( LogManager.getLoggerRepository() );
}
/**
* Creates a new DefaultLog4JManager
with an existing Hierarchy
.
*/
public Log4JLoggerManager( final LoggerRepository hierarchy )
{
this( (String) null, hierarchy, (String) null, (Logger) null, (Logger) null );
}
/**
* Creates a new DefaultLog4JManager
using
* specified logger name as root logger.
*/
public Log4JLoggerManager( final String prefix )
{
this( prefix, (LoggerRepository) null, (String) null, (Logger) null, (Logger) null );
}
/**
* Creates a new DefaultLog4JManager
with an existing Hierarchy
using
* specified logger name as root logger.
*/
public Log4JLoggerManager( final String prefix,
final LoggerRepository hierarchy )
{
this( prefix, hierarchy, (String) null, (Logger) null, (Logger) null );
}
/**
* Creates a new DefaultLog4JManager
using
* specified logger name as root logger.
*/
public Log4JLoggerManager( final String prefix, final String switchToCategory )
{
this( prefix, (LoggerRepository) null, switchToCategory, (Logger) null, (Logger) null );
}
/**
* Creates a new DefaultLog4JManager
with an existing Hierarchy
using
* specified logger name as root logger.
*/
public Log4JLoggerManager( final String prefix,
final LoggerRepository hierarchy,
final String switchToCategory )
{
this( prefix, hierarchy, switchToCategory, (Logger) null, (Logger) null );
}
/**
* Creates a new DefaultLog4JManager
with an existing Hierarchy
using
* specified logger name as root logger.
*/
public Log4JLoggerManager( final String prefix,
final LoggerRepository hierarchy,
final Logger defaultLogger )
{
this( prefix, hierarchy, (String) null, defaultLogger, defaultLogger );
}
/**
* Creates a new DefaultLog4JManager
with an existing Hierarchy
using
* specified logger name as root logger.
*/
public Log4JLoggerManager( final String prefix,
final LoggerRepository hierarchy,
final Logger defaultLogger,
final Logger logger )
{
this( prefix, hierarchy, (String) null, defaultLogger, logger );
}
/**
* Creates a new DefaultLog4JManager
.
* @param prefix to prepend to every category name on
* getLoggerForCategory()
* @param hierarchy a Log4J LoggerRepository to run with
* @param switchToCategory if this parameter is not null
* after start()
* LogKitLoggerManager
will start
* to log its own debug and error messages to
* a logger obtained via
* this.getLoggerForCategory( switchToCategory )
.
* Note that prefix will be prepended to
* the value of switchToCategory
also.
* @param defaultLogger the logger to override the default
* logger configured by Log4J; probably should be
* null to allow users set up whatever logger they
* like as the root logger via Log4J configuration
* @param logger the logger to log our own initialization
* messages (currently we have none) and to log
* errors (currently this functionality is not used
* either)
*/
public Log4JLoggerManager( final String prefix,
final LoggerRepository hierarchy,
final String switchToCategory,
final Logger defaultLogger,
final Logger logger )
{
super( prefix, switchToCategory, defaultLogger );
if ( hierarchy == null )
{
// is this an analog of new Hierarchy() or an
// analog of Hierarchy.getDefaultHierarchy()?
// we should have an analog of new Hierarchy() here
// I guess - Anton Tagunov
m_hierarchy = LogManager.getLoggerRepository();
}
else
{
m_hierarchy = hierarchy;
}
if ( logger != null )
{
this.enableLogging( logger );
}
}
/* Actaully create the Logger */
protected Logger doGetLoggerForCategory( final String fullCategoryName )
{
return new Log4JLogger( m_hierarchy.getLogger( fullCategoryName ) );
}
}
excalibur-logger-2.1/NOTICE.txt 100644 0 0 154 10304740432 13435 0 ustar 0 0 This product includes software developed by
The Apache Software Foundation (http://www.apache.org/).
excalibur-logger-2.1/build.xml 100644 0 0 15115 10304740432 13577 0 ustar 0 0