avalon-logkit-2.0.dev-0/ 40755 0 0 0 10036267317 12073 5ustar 0 0 avalon-logkit-2.0.dev-0/src/ 40755 0 0 0 10036267317 12662 5ustar 0 0 avalon-logkit-2.0.dev-0/src/java/ 40755 0 0 0 10036267317 13603 5ustar 0 0 avalon-logkit-2.0.dev-0/src/java/org/ 40755 0 0 0 10036267317 14372 5ustar 0 0 avalon-logkit-2.0.dev-0/src/java/org/apache/ 40755 0 0 0 10036267317 15613 5ustar 0 0 avalon-logkit-2.0.dev-0/src/java/org/apache/log/ 40755 0 0 0 10036267317 16374 5ustar 0 0 avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/ 40755 0 0 0 10036267317 17734 5ustar 0 0 avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/io/ 40755 0 0 0 10036267317 20343 5ustar 0 0 avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/io/rotate/ 40755 0 0 0 10036267317 21641 5ustar 0 0 avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/db/ 40755 0 0 0 10036267317 20321 5ustar 0 0 avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/lf5/ 40755 0 0 0 10036267317 20422 5ustar 0 0 avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/jms/ 40755 0 0 0 10036267317 20525 5ustar 0 0 avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/net/ 40755 0 0 0 10036267317 20522 5ustar 0 0 avalon-logkit-2.0.dev-0/src/java/org/apache/log/util/ 40755 0 0 0 10036267317 17351 5ustar 0 0 avalon-logkit-2.0.dev-0/src/java/org/apache/log/format/ 40755 0 0 0 10036267317 17664 5ustar 0 0 avalon-logkit-2.0.dev-0/src/test/ 40755 0 0 0 10036267317 13641 5ustar 0 0 avalon-logkit-2.0.dev-0/src/test/org/ 40755 0 0 0 10036267317 14430 5ustar 0 0 avalon-logkit-2.0.dev-0/src/test/org/apache/ 40755 0 0 0 10036267317 15651 5ustar 0 0 avalon-logkit-2.0.dev-0/src/test/org/apache/log/ 40755 0 0 0 10036267317 16432 5ustar 0 0 avalon-logkit-2.0.dev-0/src/test/org/apache/log/format/ 40755 0 0 0 10036267317 17722 5ustar 0 0 avalon-logkit-2.0.dev-0/src/test/org/apache/log/format/test/ 40755 0 0 0 10036267317 20701 5ustar 0 0 avalon-logkit-2.0.dev-0/src/test/org/apache/log/util/ 40755 0 0 0 10036267317 17407 5ustar 0 0 avalon-logkit-2.0.dev-0/src/test/org/apache/log/util/test/ 40755 0 0 0 10036267317 20366 5ustar 0 0 avalon-logkit-2.0.dev-0/src/test/org/apache/log/output/ 40755 0 0 0 10036267317 17772 5ustar 0 0 avalon-logkit-2.0.dev-0/src/test/org/apache/log/output/test/ 40755 0 0 0 10036267317 20751 5ustar 0 0 avalon-logkit-2.0.dev-0/src/test/org/apache/log/test/ 40755 0 0 0 10036267317 17411 5ustar 0 0 avalon-logkit-2.0.dev-0/src/sql/ 40755 0 0 0 10036267317 13461 5ustar 0 0 avalon-logkit-2.0.dev-0/project.xml100644 0 0 14347 10036267317 14411 0ustar 0 0 3 Avalon LogKit avalon-logkit avalon-logkit 2.0.dev-0 2003 The Avalon LogKit logging utility Avalon LogKit is the logging utility used by default in all Avalon systems. org.apache.log scm:cvs:pserver:anoncvs@cvs.apache.org:/home/cvspublic:avalon-logkit http://cvs.apache.org/viewcvs/avalon-logkit/ log4j 1.2.8 servletapi 2.3 javamail mailapi 1.3.1 jms jms 1.1 The Apache Software Foundation http://avalon.apache.org/ http://avalon.apache.org/images/apache-avalon-logo.png avalon-logkit Avalon Developer List dev-subscribe@avalon.apache.org dev-unsubscribe@avalon.apache.org http://nagoya.apache.org/eyebrowse/SummarizeList?listName=dev@avalon.apache.org Avalon User List users-subscribe@avalon.apache.org users-unsubscribe@avalon.apache.org http://nagoya.apache.org/eyebrowse/SummarizeList?listName=users@avalon.apache.org CVS List cvs-subscribe@avalon.apache.org cvs-unsubscribe@avalon.apache.org Stephen McConnell mcconnell mcconnell@apache.org Leo Simons leosimons leosimons@apache.org Berin Loritsch bloritsch bloritsch@apache.org Peter Royal proyal proyal@apache.org Aaron Far farra@apache.org farra Sony Electronics Alex Karasulu aok123@bellsouth.net akarasulu Niclas Hedhman niclas@apache.org niclas dev@avalon.apache.org ${basedir}/src/java ${basedir}/src/test **/*TestCase* **/Abstract* ${basedir}/src/test **/*.dtd **/*.properties **/*.xinfo **/*.xtype **/*.xprofile **/*.xconfig **/*.xml **/*.xservice **/*.mf **/*.jar ${maven.conf.dir} **/*.properties ${basedir}/src/test/conf **/* ${basedir}/src/java **/*.dtd **/*.properties **/*.xinfo **/*.xtype **/*.xprofile **/*.xconfig **/*.xml **/*.xservice ${basedir}/../ LICENSE.txt ${maven.conf.dir} BLOCK-INF block.xml maven-javadoc-plugin avalon-logkit-2.0.dev-0/README.txt100644 0 0 662 10036267317 13652 0ustar 0 0 LogKit What is it? ----------- It is a lightweight, fast, securely designed logging toolkit. It is designed to integrate into existing applications. Where is it? ------------ http://avalon.apache.org/logkit Requirements ------------ -JDK1.2 or above -To build form CVS you must set JAVA_HOME to the jdk dir (eg:/usr/bin/jdk1.2 or c:\jdk1.3) avalon-logkit-2.0.dev-0/project.properties100644 0 0 2776 10036267317 15770 0ustar 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. # # # ------------------------------------------------------------------- # P R O J E C T P R O P E R T I E S # ------------------------------------------------------------------- maven.repo.remote = http://www.apache.org/dist/avalon,http://www.ibiblio.org/maven maven.repo.central = www.apache.org maven.repo.central.directory = /www/www.apache.org/dist/avalon maven.junit.fork = yes # maven.license.licenseFile = ${basedir}/LICENSE.txt # maven.ui.banner.background = #fff # maven.ui.banner.foreground = #000 maven.xdoc.poweredby.image = maven.xdoc.jsl=file:${basedir}/buildsystem/site.jsl maven.docs.src=${basedir}/xdocs/ maven.javadoc.stylesheet = ${basedir}/xdocs/style/stylesheet.css sun.j2se.link = http://java.sun.com/j2se/1.4/docs/api/ framework.api.link = http://avalon.apache.org/framework/api/ maven.javadoc.links = ${sun.j2se.link},${framework.api.link} # gump integration project.name=avalon-logkit avalon-logkit-2.0.dev-0/LICENSE.txt100644 0 0 23637 10036267317 14046 0ustar 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. avalon-logkit-2.0.dev-0/build.xml100644 0 0 17516 10036267317 14043 0ustar 0 0 avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/io/rotate/package.html100644 0 0 70 10036267317 24154 0ustar 0 0 Log file rotation policies. avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/io/rotate/RotateStrategyByDate.java100644 0 0 4461 10036267317 26660 0ustar 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.log.output.io.rotate; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; /** * Rotation stragety based on SimpleDateFormat. * * @author Avalon Development Team * @author Eung-ju Park * @version $Revision: 1.13 $ $Date: 2004/02/28 11:31:24 $ */ public class RotateStrategyByDate implements RotateStrategy { private SimpleDateFormat m_format; private Date m_date; private String m_current; /** * Creation of a new rotation strategy based on a date policy. */ public RotateStrategyByDate() { this( "yyyyMMdd" ); } /** * Creation of a new rotation strategy based on a date policy * using a supplied pattern. * @param pattern the message formatting pattern */ public RotateStrategyByDate( final String pattern ) { m_format = new SimpleDateFormat( pattern ); m_date = new Date(); m_current = m_format.format( m_date ); } /** * Reset the strategy. */ public void reset() { m_date.setTime( System.currentTimeMillis() ); m_current = m_format.format( m_date ); } /** * Test is a rotation is required. Documentation pending ?? * * @param data not used * @param file not used * @return TRUE if a rotation is required else FALSE */ public boolean isRotationNeeded( final String data, final File file ) { m_date.setTime( System.currentTimeMillis() ); if( m_current.equals( m_format.format( m_date ) ) ) { return false; } return true; } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/io/rotate/RotateStrategy.java100644 0 0 2657 10036267317 25574 0ustar 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.log.output.io.rotate; import java.io.File; /** * Strategy that checks condition under which file rotation is needed. * * @author Leo Sutic * @author Bernhard Huber */ public interface RotateStrategy { /** * Reset cumulative rotation history data. * Called after rotation. */ void reset(); /** * Check if a log rotation is neccessary at this time. * * @param data the serialized version of the message about to be written * to the log system * @param file the File that we are writing to * @return boolean return true if log rotation is neccessary, else false */ boolean isRotationNeeded( String data, File file ); } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/io/rotate/RotatingFileTarget.java100644 0 0 7313 10036267317 26343 0ustar 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.log.output.io.rotate; import java.io.File; import java.io.IOException; import org.apache.log.format.Formatter; import org.apache.log.output.io.FileTarget; /** * This is a basic Output log target that writes to rotating files. * * @author Peter Donald * @author Stephen McConnell * @author Bernhard Huber */ public class RotatingFileTarget extends FileTarget { ///Flag indicating whether or not file should be appended to private boolean m_append; ///The rotation strategy to be used. private RotateStrategy m_rotateStrategy; ///The file strategy to be used. private FileStrategy m_fileStrategy; /** * Construct RotatingFileTarget object. * * @param formatter Formatter to be used * @param rotateStrategy RotateStrategy to be used * @param fileStrategy FileStrategy to be used * @exception IOException if a file access or write related error occurs */ public RotatingFileTarget( final Formatter formatter, final RotateStrategy rotateStrategy, final FileStrategy fileStrategy ) throws IOException { this( false, formatter, rotateStrategy, fileStrategy ); } /** * Construct RotatingFileTarget object. * * @param append true if file is to be appended to, false otherwise * @param formatter Formatter to be used * @param rotateStrategy RotateStrategy to be used * @param fileStrategy FileStrategy to be used * @exception IOException if a file access or write related error occurs */ public RotatingFileTarget( final boolean append, final Formatter formatter, final RotateStrategy rotateStrategy, final FileStrategy fileStrategy ) throws IOException { super( null, append, formatter ); m_append = append; m_rotateStrategy = rotateStrategy; m_fileStrategy = fileStrategy; rotate(); } /** * Rotates the file. * @exception IOException if a file access or write related error occurs */ protected synchronized void rotate() throws IOException { close(); final File file = m_fileStrategy.nextFile(); setFile( file, m_append ); openFile(); } /** * Output the log message, and check if rotation is needed. * @param data the date to write to the target */ protected synchronized void write( final String data ) { // if rotation is needed, close old File, create new File if( m_rotateStrategy.isRotationNeeded( data, getFile() ) ) { try { rotate(); m_rotateStrategy.reset(); } catch( final IOException ioe ) { getErrorHandler().error( "Error rotating file", ioe, null ); } } // write the log message super.write( data ); } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/io/rotate/FileStrategy.java100644 0 0 2065 10036267317 25206 0ustar 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.log.output.io.rotate; import java.io.File; /** * Strategy for naming log files. * For a given base file name an implementation calculates * the real file name. * * @author Bernhard Huber * @author Peter Donald */ public interface FileStrategy { /** * Get the next log file to rotate to. * * @return the file to rotate to */ File nextFile(); } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/io/rotate/RotateStrategyByTime.java100644 0 0 4765 10036267317 26710 0ustar 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.log.output.io.rotate; import java.io.File; /** * rotation stragety based when log writting started. * * @author Bernhard Huber */ public class RotateStrategyByTime implements RotateStrategy { ///time interval when rotation is triggered. private long m_timeInterval; ///time when logging started. private long m_startingTime; ///rotation count. private long m_currentRotation; /** * Rotate logs by time. * By default do log rotation every 24 hours */ public RotateStrategyByTime() { this( 1000 * 60 * 60 * 24 ); } /** * Rotate logs by time. * * @param timeInterval rotate before time-interval [ms] has expired */ public RotateStrategyByTime( final long timeInterval ) { m_startingTime = System.currentTimeMillis(); m_currentRotation = 0; m_timeInterval = timeInterval; } /** * reset interval history counters. */ public void reset() { m_startingTime = System.currentTimeMillis(); m_currentRotation = 0; } /** * Check if now a log rotation is neccessary. * If * (current_time - m_startingTime) / m_timeInterval > m_currentRotation * rotation is needed. * * @param data the last message written to the log system * @param file not used * @return boolean return true if log rotation is neccessary, else false */ public boolean isRotationNeeded( final String data, final File file ) { final long newRotation = ( System.currentTimeMillis() - m_startingTime ) / m_timeInterval; if( newRotation > m_currentRotation ) { m_currentRotation = newRotation; return true; } else { return false; } } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/io/rotate/UniqueFileStrategy.java100644 0 0 6021 10036267317 26371 0ustar 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.log.output.io.rotate; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; /** * Strategy for naming log files based on appending time suffix. * A file name can be based on simply appending the number of miliseconds * since (not really sure) 1/1/1970. * Other constructors accept a pattern of a SimpleDateFormat * to form the appended string to the base file name as well as a suffix * which should be appended last. * * A new UniqueFileStrategy( new File( "foo." ), "yyyy-MM-dd", ".log" ) * object will return File objects with file names like * foo.2001-12-24.log * * @author Bernhard Huber * @author Giacomo Pati */ public class UniqueFileStrategy implements FileStrategy { private File m_baseFile; private SimpleDateFormat m_formatter; private String m_suffix; /** * Creation of a new Unique File Strategy ?? * @param baseFile the base file */ public UniqueFileStrategy( final File baseFile ) { m_baseFile = baseFile; } /** * Creation of a new Unique File Strategy ?? * @param baseFile the base file * @param pattern the format pattern */ public UniqueFileStrategy( final File baseFile, String pattern ) { this( baseFile ); m_formatter = new SimpleDateFormat( pattern ); } /** * Creation of a new Unique File Strategy ?? * @param baseFile the base file * @param pattern the format pattern * @param suffix the suffix ?? */ public UniqueFileStrategy( final File baseFile, String pattern, String suffix ) { this( baseFile, pattern ); m_suffix = suffix; } /** * Calculate the real file name from the base filename. * * @return File the calculated file name */ public File nextFile() { final StringBuffer sb = new StringBuffer(); sb.append( m_baseFile ); if( m_formatter == null ) { sb.append( System.currentTimeMillis() ); } else { final String dateString = m_formatter.format( new Date() ); sb.append( dateString ); } if( m_suffix != null ) { sb.append( m_suffix ); } return new File( sb.toString() ); } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/io/rotate/RotateStrategyBySize.java100644 0 0 4715 10036267317 26717 0ustar 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.log.output.io.rotate; import java.io.File; /** * Rotation strategy based on size written to log file. * The strategy will signal that a rotation is needed if the * size goes above a set limit. Due to performance reasons * the limit is not strictly enforced, however, the strategy has * at most an error of the longest single data message written to the * logging system. The error will occur immediately after a rotation, * when the strategy is reset and the data that triggered the * rotation is written. The strategy's internal counter will then * be off with data.length() bytes. * * @author Leo Sutic * @author Bernhard Huber */ public class RotateStrategyBySize implements RotateStrategy { private long m_maxSize; private long m_currentSize; /** * Rotate logs by size. * By default do log rotation before writing approx. 1MB of messages */ public RotateStrategyBySize() { this( 1024 * 1024 ); } /** * Rotate logs by size. * * @param maxSize rotate before writing maxSize [byte] of messages */ public RotateStrategyBySize( final long maxSize ) { m_currentSize = 0; m_maxSize = maxSize; } /** * Reset log size written so far. */ public void reset() { m_currentSize = 0; } /** * Check if now a log rotation is neccessary. * * @param data the message about to be written to the log system * @return boolean return true if log rotation is neccessary, else false * @param file not used */ public boolean isRotationNeeded( final String data, final File file ) { m_currentSize += data.length(); return m_currentSize >= m_maxSize; } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/io/rotate/RotateStrategyByTimeOfDay.java100644 0 0 6304 10036267317 27622 0ustar 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.log.output.io.rotate; import java.io.File; import java.util.Calendar; import java.util.GregorianCalendar; /** * Rotation stragety based on a specific time of day. * * @author Leif Mortenson */ public class RotateStrategyByTimeOfDay implements RotateStrategy { /** Constant that stores the the number of ms in 24 hours. */ private static final long TIME_24_HOURS = 24 * 3600 * 1000; /** Time in ms that the current rotation started. */ private long m_currentRotation; /** * Rotate logs at specific time of day. * By default do log rotation at 00:00:00 every day. */ public RotateStrategyByTimeOfDay() { this( 0 ); } /** * Rotate logs at specific time of day. * * @param time Offset in milliseconds into the day to perform the log rotation. */ public RotateStrategyByTimeOfDay( final long time ) { // Calculate the time at the beginning of the current day and add the time to that. final GregorianCalendar cal = new GregorianCalendar(); cal.set( Calendar.MILLISECOND, 0 ); cal.set( Calendar.SECOND, 0 ); cal.set( Calendar.MINUTE, 0 ); cal.set( Calendar.HOUR_OF_DAY, 0 ); m_currentRotation = cal.getTime().getTime() + time; // Make sure that the current rotation time is in the past. if( m_currentRotation > System.currentTimeMillis() ) { m_currentRotation -= TIME_24_HOURS; } } /** * reset interval history counters. */ public void reset() { final long now = System.currentTimeMillis(); // Make sure the currentRotation time is set so that the current system // time is within 24 hours. while( m_currentRotation + TIME_24_HOURS < now ) { m_currentRotation += TIME_24_HOURS; } } /** * Check if now a log rotation is neccessary. * If the time of the current rotation + 24 hours is less than the current time. * If not then a rotation is needed. * * @param data the last message written to the log system * @param file not used * @return boolean return true if log rotation is neccessary, else false */ public boolean isRotationNeeded( final String data, final File file ) { final long now = System.currentTimeMillis(); if( m_currentRotation + TIME_24_HOURS < now ) { // Needs to be rotated. return true; } else { return false; } } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/io/rotate/OrRotateStrategy.java100644 0 0 5317 10036267317 26071 0ustar 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.log.output.io.rotate; import java.io.File; /** * Hierarchical rotation strategy. * This object is initialised with several rotation strategy objects. * The isRotationNeeded method checks the first rotation * strategy object. If a rotation is needed, this result is returned. * If not, the next rotation strategy object is checked, and so on. * * @author Carsten Ziegeler */ public class OrRotateStrategy implements RotateStrategy { private RotateStrategy[] m_strategies; /** The rotation strategy used. This marker is required for the reset() * method. */ private int m_usedRotation = -1; /** * Constructor * @param strategies the set of rotation strategies */ public OrRotateStrategy( final RotateStrategy[] strategies ) { this.m_strategies = strategies; } /** * reset. */ public void reset() { for( int i = 0; i < m_strategies.length; i++ ) { m_strategies[ i ].reset(); } } /** * check if now a log rotation is neccessary. * This object is initialised with several rotation strategy objects. * The isRotationNeeded method checks the first rotation * strategy object. If a rotation is needed, this result is returned. * If not the next rotation strategy object is asked and so on. * @param data the last message written to the log system * @param file ??? * @return boolean return true if log rotation is neccessary, else false */ public boolean isRotationNeeded( final String data, final File file ) { m_usedRotation = -1; if( null != m_strategies ) { final int length = m_strategies.length; for( int i = 0; i < length; i++ ) { if( true == m_strategies[ i ].isRotationNeeded( data, file ) ) { m_usedRotation = i; return true; } } } return false; } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/io/rotate/BaseFileNameFilter.java100644 0 0 2032 10036267317 26217 0ustar 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.log.output.io.rotate; import java.io.File; import java.io.FilenameFilter; class BaseFileNameFilter implements FilenameFilter { private String m_baseFileName; BaseFileNameFilter( final String baseFileName ) { m_baseFileName = baseFileName; } public boolean accept( File file, String name ) { return ( name.startsWith( m_baseFileName ) ); } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/io/rotate/RevolvingFileStrategy.java100644 0 0 20244 10036267317 27121 0ustar 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.log.output.io.rotate; import java.io.File; import java.text.DecimalFormat; import java.text.FieldPosition; import java.text.NumberFormat; /** * strategy for naming log files based on appending revolving suffix. * If the initial rotation is not specified then the class will attempt to * calculate the rotation number via the following algorithm. * * It will search for the file with the highest number in the rotation. It will * then increment its rotation number and use that number. If all files in rotation * are present then it will then set the initial rotation to the next rotation after * the most recently created file. * * @author Avalon Development Team * @author Bernhard Huber * @author Peter Donald * @author David Gray */ public class RevolvingFileStrategy implements FileStrategy { ///revolving suffix formatting pattern. ie. "'.'000000" private static final String PATTERN = "'.'000000"; ///a revolving suffix formatter private DecimalFormat m_decimalFormat; ///current revolving suffix private int m_rotation; ///max revolving value. private int m_maxRotations; ///the base file name. private File m_baseFile; /** * Creation of a new instane ofthe revolving file strategy. * @param baseFile the base file * @param maxRotations the maximum number of rotations ?? */ public RevolvingFileStrategy( final File baseFile, final int maxRotations ) { this( baseFile, -1, maxRotations ); } /** * Creation of a new instane ofthe revolving file strategy. * @param baseFile the base file * @param initialRotation the number of initial rotations ?? * @param maxRotations the maximum number of rotations?? */ public RevolvingFileStrategy( final File baseFile, final int initialRotation, final int maxRotations ) { m_decimalFormat = new DecimalFormat( PATTERN ); m_baseFile = baseFile; m_rotation = initialRotation; m_maxRotations = maxRotations; if( -1 == m_maxRotations ) { m_maxRotations = Integer.MAX_VALUE; } if( -1 == initialRotation ) { m_rotation = calculateInitialRotation(); } if( m_rotation > m_maxRotations ) { m_rotation = m_maxRotations; } if( m_rotation < 0 ) { m_rotation = 0; } } /** * Calculate the real file name from the base filename. * * @return File the calculated file name */ public File nextFile() { final StringBuffer sb = new StringBuffer(); final FieldPosition position = new FieldPosition( NumberFormat.INTEGER_FIELD ); sb.append( m_baseFile ); final StringBuffer result = m_decimalFormat.format( m_rotation, sb, position ); m_rotation += 1; if( m_rotation >= m_maxRotations ) { m_rotation = 0; } return new File( result.toString() ); } /** * Retrieve the current rotation number. * * @return the current rotation number. */ public int getCurrentRotation() { return m_rotation; } /** * Method that searches through files that * match the pattern for resolving file and determine * the last generation written to. * * @return the initial rotation */ private int calculateInitialRotation() { final File[] matchingFiles = getMatchingFiles(); if( null == matchingFiles || 0 == matchingFiles.length ) { return 0; } final int[] rotations = calculateRotations( matchingFiles ); //First we go through and look for maximumRotation int maxRotation = 0; for( int i = 0; i < rotations.length; i++ ) { final int rotation = rotations[ i ]; if( rotation > maxRotation ) { maxRotation = rotation; } } //If the max rotation present on filessytem //is less than max rotation possible then return that //rotation if( m_maxRotations != maxRotation ) { return maxRotation + 1; } //Okay now we need to calculate the youngest file for our rotation long time = matchingFiles[ 0 ].lastModified(); //index of oldest file int oldest = rotations[ 0 ]; for( int i = 0; i < matchingFiles.length; i++ ) { final File file = matchingFiles[ i ]; final long lastModified = file.lastModified(); if( lastModified < time ) { time = lastModified; oldest = rotations[ i ]; } } return oldest; } /** * Generate an array of rotation numbers for all the files specified. * * @param matchingFiles the files to generate rotation numbers for * @return the array containing rotations */ private int[] calculateRotations( final File[] matchingFiles ) { final int[] results = new int[ matchingFiles.length ]; for( int i = 0; i < matchingFiles.length; i++ ) { final File file = matchingFiles[ i ]; // The files may be returned in any order //therefore calc the rotation number try { results[ i ] = calculateRotationForFile( file ); } catch( final NumberFormatException nfe ) { //If bad log file detected then set to -1 results[ i ] = -1; } } return results; } /** * Return the rotation for the specified file * * @param file the file to check * @return the rotation of the file */ private int calculateRotationForFile( final File file ) { final String filename = file.toString(); final int length = filename.length(); final int minDigits = m_decimalFormat.getMinimumIntegerDigits(); final String rotation = filename.substring( length - minDigits ); return Integer.parseInt( rotation ); } /** * Get a list of files that could have been part of the rotation. * * @return the list of files that match */ private File[] getMatchingFiles() { // First get the path of the base file. Note that this path includes // the path and the base of the file name itself. final String fullFilePathName = m_baseFile.getPath(); // Try to find the last path separator (if it exists) final int fileSeparatorPosition = fullFilePathName.lastIndexOf( File.separator ); // If the last path separator does not exist the baseFile is a pure file name File basePath; String baseFileName; if( fileSeparatorPosition < 0 ) { // assume the current directory basePath = new File( "." ); baseFileName = fullFilePathName; } else { // Extract the sub-directory structure String m_parentPath = fullFilePathName.substring( 0, fileSeparatorPosition ); baseFileName = fullFilePathName.substring( fileSeparatorPosition + 1 ); basePath = new File( m_parentPath ); } return basePath.listFiles( new BaseFileNameFilter( baseFileName ) ); } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/io/WriterTarget.java100644 0 0 5366 10036267317 23740 0ustar 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.log.output.io; import java.io.IOException; import java.io.Writer; import org.apache.log.format.Formatter; import org.apache.log.output.AbstractOutputTarget; /** * This target outputs to a writer. * * @author Peter Donald */ public class WriterTarget extends AbstractOutputTarget { private Writer m_output; /** * Construct target with a specific writer and formatter. * * @param writer the writer * @param formatter the formatter */ public WriterTarget( final Writer writer, final Formatter formatter ) { super( formatter ); if( null != writer ) { setWriter( writer ); open(); } } /** * Set the writer. * Close down writer and write tail if appropriate. * * @param writer the new writer */ protected synchronized void setWriter( final Writer writer ) { if( null == writer ) { throw new NullPointerException( "writer property must not be null" ); } m_output = writer; } /** * Concrete implementation of output that writes out to underlying writer. * * @param data the data to output */ protected void write( final String data ) { try { m_output.write( data ); m_output.flush(); } catch( final IOException ioe ) { getErrorHandler().error( "Caught an IOException", ioe, null ); } } /** * Shutdown target. * Attempting to write to target after close() will cause errors to be logged. */ public synchronized void close() { super.close(); shutdownWriter(); } /** * Shutdown Writer. */ protected synchronized void shutdownWriter() { final Writer writer = m_output; m_output = null; try { if( null != writer ) { writer.close(); } } catch( final IOException ioe ) { getErrorHandler().error( "Error closing Writer", ioe, null ); } } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/io/package.html100644 0 0 121 10036267317 22673 0ustar 0 0 Stream anf file based output destination LogTargets. avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/io/SafeFileTarget.java100644 0 0 4607 10036267317 24137 0ustar 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.log.output.io; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.apache.log.LogEvent; import org.apache.log.format.Formatter; /** * A target that will open and close a file for each logevent. * This is slow but a more reliable form of logging on some * filesystems/OSes. It should only be used when there is a * small number of log events. * * @author Peter Donald */ public class SafeFileTarget extends FileTarget { /** * Construct file target to write to a file with a formatter. * * @param file the file to write to * @param append true if file is to be appended to, false otherwise * @param formatter the Formatter * @exception IOException if an error occurs */ public SafeFileTarget( final File file, final boolean append, final Formatter formatter ) throws IOException { super( file, append, formatter ); shutdownStream(); } /** * Process a log event, via formatting and outputting it. * * @param event the log event */ public synchronized void processEvent( final LogEvent event ) { if( !isOpen() ) { getErrorHandler().error( "Writing event to closed stream.", null, event ); return; } try { final FileOutputStream outputStream = new FileOutputStream( getFile().getPath(), true ); setOutputStream( outputStream ); } catch( final Throwable throwable ) { getErrorHandler().error( "Unable to open file to write log event.", throwable, event ); return; } //write out event super.processEvent( event ); shutdownStream(); } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/io/FileTarget.java100644 0 0 6611 10036267317 23335 0ustar 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.log.output.io; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.apache.log.format.Formatter; /** * A basic target that writes to a File. * * @author Avalon Development Team * @author Peter Donald */ public class FileTarget extends StreamTarget { ///File we are writing to private File m_file; ///Flag indicating whether or not file should be appended to private boolean m_append; /** * Construct file target to write to a file with a formatter. * * @param file the file to write to * @param append true if file is to be appended to, false otherwise * @param formatter the Formatter * @exception IOException if an error occurs */ public FileTarget( final File file, final boolean append, final Formatter formatter ) throws IOException { super( null, formatter ); if( null != file ) { setFile( file, append ); openFile(); } } /** * Set the file for this target. * * @param file the file to write to * @param append true if file is to be appended to, false otherwise * @exception IOException if directories can not be created or file can not be opened */ protected synchronized void setFile( final File file, final boolean append ) throws IOException { if( null == file ) { throw new NullPointerException( "file property must not be null" ); } if( isOpen() ) { throw new IOException( "target must be closed before " + "file property can be set" ); } m_append = append; m_file = file; } /** * Open underlying file and allocate resources. * This method will attempt to create directories below file and * append to it if specified. * @exception IOException if directories can not be created or file can not be opened */ protected synchronized void openFile() throws IOException { if( isOpen() ) { close(); } final File file = getFile().getCanonicalFile(); final File parent = file.getParentFile(); if( null != parent && !parent.exists() ) { parent.mkdirs(); } final FileOutputStream outputStream = new FileOutputStream( file.getPath(), m_append ); setOutputStream( outputStream ); open(); } /** * Retrieve file associated with target. * This allows subclasses to access file object. * * @return the output File */ protected synchronized File getFile() { return m_file; } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/io/StreamTarget.java100644 0 0 11443 10036267317 23730 0ustar 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.log.output.io; import java.io.IOException; import java.io.OutputStream; import org.apache.log.format.Formatter; import org.apache.log.output.AbstractOutputTarget; /** * A basic target that writes to an OutputStream. * * @author Peter Donald */ public class StreamTarget extends AbstractOutputTarget { /** OutputStream we are writing to. */ private OutputStream m_outputStream; /** The encoding to use when creating byte array for string, may be null. */ private String m_encoding; /** * Constructor that writes to a stream and uses a particular formatter. * * @param outputStream the OutputStream to write to * @param formatter the Formatter to use * @param encoding Desired encoding to use when writing to the log, null * implies the default system encoding. */ public StreamTarget( final OutputStream outputStream, final Formatter formatter, final String encoding ) { super( formatter ); m_encoding = encoding; if( null != outputStream ) { setOutputStream( outputStream ); open(); } } /** * Constructor that writes to a stream and uses a particular formatter. * * @param outputStream the OutputStream to write to * @param formatter the Formatter to use */ public StreamTarget( final OutputStream outputStream, final Formatter formatter ) { // We can get the default system encoding by calling the following // method, but it is not a standard API so we work around it by // allowing encoding to be null. // sun.io.Converters.getDefaultEncodingName(); this( outputStream, formatter, null ); } /** * Set the output stream. * Close down old stream and write tail if appropriate. * * @param outputStream the new OutputStream */ protected synchronized void setOutputStream( final OutputStream outputStream ) { if( null == outputStream ) { throw new NullPointerException( "outputStream property must not be null" ); } m_outputStream = outputStream; } /** * Abstract method that will output event. * * @param data the data to be output */ protected synchronized void write( final String data ) { //Cache method local version //so that can be replaced in another thread final OutputStream outputStream = m_outputStream; if( null == outputStream ) { final String message = "Attempted to write data '" + data + "' to Null OutputStream"; getErrorHandler().error( message, null, null ); return; } try { byte[] bytes; if( m_encoding == null ) { bytes = data.getBytes(); } else { bytes = data.getBytes( m_encoding ); } outputStream.write( bytes ); outputStream.flush(); } catch( final IOException ioe ) { final String message = "Error writing data '" + data + "' to OutputStream"; getErrorHandler().error( message, ioe, null ); } } /** * Shutdown target. * Attempting to write to target after close() will cause errors to be logged. * */ public synchronized void close() { super.close(); shutdownStream(); } /** * Shutdown output stream. */ protected synchronized void shutdownStream() { final OutputStream outputStream = m_outputStream; m_outputStream = null; try { if( null != outputStream ) { // Never close System Streams if( ! ( System.out == outputStream && System.err == outputStream ) ) { outputStream.close(); } } } catch( final IOException ioe ) { getErrorHandler().error( "Error closing OutputStream", ioe, null ); } } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/db/ColumnType.java100644 0 0 6177 10036267317 23373 0ustar 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.log.output.db; /** * A class to hold all constants for ColumnTypes. * * @author Peter Donald */ public class ColumnType { public static final int STATIC = 1; public static final int CATEGORY = 2; public static final int CONTEXT = 3; public static final int MESSAGE = 4; public static final int TIME = 5; public static final int RELATIVE_TIME = 6; public static final int THROWABLE = 7; public static final int PRIORITY = 8; public static final int HOSTNAME = 9; //public static final int IPADDRESS = 10; /** * The maximum value used for TYPEs. Subclasses can define their own TYPEs * starting at MAX_TYPE + 1. */ //public static final int MAX_TYPE = IPADDRESS; public static final String STATIC_STR = "static"; public static final String CATEGORY_STR = "category"; public static final String CONTEXT_STR = "context"; public static final String MESSAGE_STR = "message"; public static final String TIME_STR = "time"; public static final String RELATIVE_TIME_STR = "rtime"; public static final String THROWABLE_STR = "throwable"; public static final String PRIORITY_STR = "priority"; public static final String HOSTNAME_STR = "hostname"; //public static final String IPADDRESS_STR = "ipaddress"; public static int getTypeIdFor( final String type ) { if( type.equalsIgnoreCase( CATEGORY_STR ) ) { return CATEGORY; } else if( type.equalsIgnoreCase( STATIC_STR ) ) { return STATIC; } else if( type.equalsIgnoreCase( CONTEXT_STR ) ) { return CONTEXT; } else if( type.equalsIgnoreCase( MESSAGE_STR ) ) { return MESSAGE; } else if( type.equalsIgnoreCase( PRIORITY_STR ) ) { return PRIORITY; } else if( type.equalsIgnoreCase( TIME_STR ) ) { return TIME; } else if( type.equalsIgnoreCase( RELATIVE_TIME_STR ) ) { return RELATIVE_TIME; } //else if( type.equalsIgnoreCase( IPADDRESS_STR ) ) return IPADDRESS; else if( type.equalsIgnoreCase( HOSTNAME_STR ) ) { return HOSTNAME; } else if( type.equalsIgnoreCase( THROWABLE_STR ) ) { return THROWABLE; } else { throw new IllegalArgumentException( "Unknown Type " + type ); } } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/db/ColumnInfo.java100644 0 0 3505 10036267317 23335 0ustar 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.log.output.db; /** * A descriptor for each column stored in table. * * @author Avalon Development Team * @author Peter Donald */ public class ColumnInfo { ///Name of column private final String m_name; ///Type/Source of column private final int m_type; ///Auxilliary parameters (ie constant or sub-format) private final String m_aux; //may be null /** * Creation of a new column info instance. * @param name the column name * @param type the column type * @param aux the auxillary value */ public ColumnInfo( final String name, final int type, final String aux ) { m_name = name; m_type = type; m_aux = aux; } /** * Return the column name * @return the name of the column */ public String getName() { return m_name; } /** * Return the column type as an integer * @return the type */ public int getType() { return m_type; } /** * Return the auxillary column information. * @return the information */ public String getAux() { return m_aux; } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/db/AbstractJDBCTarget.java100644 0 0 10362 10036267317 24640 0ustar 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.log.output.db; import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import org.apache.log.LogEvent; import org.apache.log.output.AbstractTarget; /** * Abstract JDBC target. * * @author Avalon Development Team * @author Peter Donald */ public abstract class AbstractJDBCTarget extends AbstractTarget { ///Datasource to extract connections from private DataSource m_dataSource; ///Database connection private Connection m_connection; /** * Creation of a new instance of the AbstractJDBCTarget. * @param dataSource the JDBC datasource */ protected AbstractJDBCTarget( final DataSource dataSource ) { m_dataSource = dataSource; } /** * Process a log event, via formatting and outputting it. * * @param event the log event * @exception Exception if an event processing error occurs */ protected synchronized void doProcessEvent( final LogEvent event ) throws Exception { checkConnection(); if( isOpen() ) { output( event ); } } /** * Output a log event to DB. * This must be implemented by subclasses. * * @param event the log event. */ protected abstract void output( LogEvent event ); /** * Startup log session. * */ protected synchronized void open() { if( !isOpen() ) { super.open(); openConnection(); } } /** * Open connection to underlying database. * */ protected synchronized void openConnection() { try { m_connection = m_dataSource.getConnection(); } catch( final Throwable throwable ) { getErrorHandler().error( "Unable to open connection", throwable, null ); } } /** * Utility method for subclasses to access connection. * * @return the Connection */ protected final synchronized Connection getConnection() { return m_connection; } /** * Utility method to check connection and bring it back up if necessary. */ protected final synchronized void checkConnection() { if( isStale() ) { closeConnection(); openConnection(); } } /** * Detect if connection is stale and should be reopened. * * @return true if connection is stale, false otherwise */ protected synchronized boolean isStale() { if( null == m_connection ) { return true; } try { if( m_connection.isClosed() ) { return true; } } catch( final SQLException se ) { return true; } return false; } /** * Shutdown target. * Attempting to write to target after close() will cause errors to be logged. * */ public synchronized void close() { if( isOpen() ) { closeConnection(); super.close(); } } /** * Close connection to underlying database. * */ protected synchronized void closeConnection() { if( null != m_connection ) { try { m_connection.close(); } catch( final SQLException se ) { getErrorHandler().error( "Error shutting down JDBC connection", se, null ); } m_connection = null; } } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/db/DefaultDataSource.java100644 0 0 5667 10036267317 24636 0ustar 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.log.output.db; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import javax.sql.DataSource; /** * A basic datasource that doesn't do any pooling but just wraps * around default mechanisms. * * @author Peter Donald */ public class DefaultDataSource implements DataSource { private final String m_username; private final String m_password; private final String m_url; private PrintWriter m_logWriter; private int m_loginTimeout; public DefaultDataSource( final String url, final String username, final String password ) { m_url = url; m_username = username; m_password = password; m_logWriter = new PrintWriter( System.err, true ); } /** * Attempt to establish a database connection. * * @return the Connection */ public Connection getConnection() throws SQLException { return getConnection( m_username, m_password ); } /** * Attempt to establish a database connection. * * @return the Connection */ public Connection getConnection( final String username, final String password ) throws SQLException { return DriverManager.getConnection( m_url, username, password ); } /** * Gets the maximum time in seconds that this data source can wait while * attempting to connect to a database. * * @return the login time */ public int getLoginTimeout() throws SQLException { return m_loginTimeout; } /** * Get the log writer for this data source. * * @return the LogWriter */ public PrintWriter getLogWriter() throws SQLException { return m_logWriter; } /** * Sets the maximum time in seconds that this data source will wait * while attempting to connect to a database. * * @param loginTimeout the loging timeout in seconds */ public void setLoginTimeout( final int loginTimeout ) throws SQLException { m_loginTimeout = loginTimeout; } public void setLogWriter( final PrintWriter logWriter ) throws SQLException { m_logWriter = logWriter; } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/db/NormalizedJDBCTarget.java100644 0 0 11353 10036267317 25202 0ustar 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.log.output.db; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.HashMap; import javax.sql.DataSource; import org.apache.log.LogEvent; /** * JDBC target that writes to normalized tables. * This reduces overhead and cost of querying/storing logs. * *

Parts based on JDBC logger from prottomatter by * Nate Sammons

* * @author Peter Donald */ public class NormalizedJDBCTarget extends DefaultJDBCTarget { private HashMap m_categoryIDs = new HashMap(); private HashMap m_priorityIDs = new HashMap(); public NormalizedJDBCTarget( final DataSource dataSource, final String table, final ColumnInfo[] columns ) { super( dataSource, table, columns ); } /** * Adds a single object into statement. */ protected void specifyColumn( final PreparedStatement statement, final int index, final LogEvent event ) throws SQLException { final ColumnInfo info = getColumn( index ); int id = 0; String tableName = null; switch( info.getType() ) { case ColumnType.CATEGORY: tableName = getTable() + "_" + ColumnType.CATEGORY_STR + "_SET"; id = getID( tableName, m_categoryIDs, event.getCategory() ); statement.setInt( index + 1, id ); break; case ColumnType.PRIORITY: tableName = getTable() + "_" + ColumnType.PRIORITY_STR + "_SET"; id = getID( tableName, m_priorityIDs, event.getPriority().getName() ); statement.setInt( index + 1, id ); break; default: super.specifyColumn( statement, index, event ); } } protected synchronized int getID( final String tableName, final HashMap idMap, final String instance ) throws SQLException { final Integer id = (Integer)idMap.get( instance ); if( null != id ) return id.intValue(); // see if it's been put in before. Statement statement = null; ResultSet resultSet = null; try { statement = getConnection().createStatement(); final String querySql = "SELECT ID FROM " + tableName + " WHERE NAME='" + instance + "'"; resultSet = statement.executeQuery( querySql ); if( resultSet.next() ) { final Integer newID = new Integer( resultSet.getInt( 1 ) ); idMap.put( instance, newID ); return newID.intValue(); } resultSet.close(); //Note that the next part should be a transaction but //it is not mega vital so ... //Find the max id in table and set //max to it's value if any items are present in table final String maxQuerySql = "SELECT MAX(ID) FROM " + tableName; resultSet = statement.executeQuery( maxQuerySql ); int max = 0; if( resultSet.next() ) max = resultSet.getInt( 1 ); resultSet.close(); final int newID = max + 1; final String insertSQL = "INSERT INTO " + tableName + " (ID, NAME) VALUES ( " + newID + ", '" + instance + "')"; statement.executeUpdate( insertSQL ); idMap.put( instance, new Integer( newID ) ); return newID; } finally { // close up shop if( null != resultSet ) { try { resultSet.close(); } catch( final Exception e ) { } } if( null != statement ) { try { statement.close(); } catch( final Exception e ) { } } } } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/db/package.html100644 0 0 104 10036267317 22652 0ustar 0 0 Database output destination LogTargets. avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/db/DefaultJDBCTarget.java100644 0 0 17225 10036267317 24466 0ustar 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.log.output.db; import java.io.StringWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Timestamp; import javax.sql.DataSource; import org.apache.log.ContextMap; import org.apache.log.LogEvent; /** * The basic DB target for configurable output formats. * * @author Avalon Development Team * @author Peter Donald */ public class DefaultJDBCTarget extends AbstractJDBCTarget { private final String m_table; private final ColumnInfo[] m_columns; private PreparedStatement m_statement; /** * Creation of a new JDBC logging target. * @param dataSource the JDBC datasource * @param table the table * @param columns a ColumnInfo array */ public DefaultJDBCTarget( final DataSource dataSource, final String table, final ColumnInfo[] columns ) { super( dataSource ); m_table = table; m_columns = columns; if( null == table ) { throw new NullPointerException( "table property must not be null" ); } if( null == columns ) { throw new NullPointerException( "columns property must not be null" ); } if( 0 == columns.length ) { throw new NullPointerException( "columns must have at least 1 element" ); } open(); } /** * Output a log event to DB. * This must be implemented by subclasses. * * @param event the log event. */ protected synchronized void output( final LogEvent event ) { //TODO: Retry logic so that this method is called multiple times if it fails //Make retry configurable and if fail send event onto ErrorHandler try { for( int i = 0; i < m_columns.length; i++ ) { specifyColumn( m_statement, i, event ); } m_statement.executeUpdate(); } catch( final SQLException se ) { getErrorHandler().error( "Error executing statement", se, event ); } } /** * Open connection to underlying database. * */ protected synchronized void openConnection() { //if( null != m_statement ) return; super.openConnection(); m_statement = null; try { final Connection connection = getConnection(); if( null != connection ) { m_statement = connection.prepareStatement( getStatementSQL() ); } } catch( final SQLException se ) { getErrorHandler().error( "Error preparing statement", se, null ); } } /** * Return the SQL insert statement. * @return the statement */ protected String getStatementSQL() { final StringBuffer sb = new StringBuffer( "INSERT INTO " ); sb.append( m_table ); sb.append( " (" ); sb.append( m_columns[ 0 ].getName() ); for( int i = 1; i < m_columns.length; i++ ) { sb.append( ", " ); sb.append( m_columns[ i ].getName() ); } sb.append( ") VALUES (?" ); for( int i = 1; i < m_columns.length; i++ ) { sb.append( ", ?" ); } sb.append( ")" ); return sb.toString(); } /** * Test if the target is stale. * @return TRUE if the target is stale else FALSE */ protected boolean isStale() { return super.isStale(); //Check: "SELECT * FROM " + m_table + " WHERE 0 = 99" here ... } /** * Close connection to underlying database. * */ protected synchronized void closeConnection() { //close prepared statement here super.closeConnection(); if( null != m_statement ) { try { m_statement.close(); } catch( final SQLException se ) { getErrorHandler().error( "Error closing statement", se, null ); } m_statement = null; } } /** * Adds a single object into statement. * @param statement the prepard statement * @param index the index * @param event the log event * @exception SQLException if an SQL related error occurs * @exception IllegalStateException if the supplied index is out of bounds */ protected void specifyColumn( final PreparedStatement statement, final int index, final LogEvent event ) throws SQLException, IllegalStateException { final ColumnInfo info = m_columns[ index ]; switch( info.getType() ) { case ColumnType.RELATIVE_TIME: statement.setLong( index + 1, event.getRelativeTime() ); break; case ColumnType.TIME: statement.setTimestamp( index + 1, new Timestamp( event.getTime() ) ); break; case ColumnType.MESSAGE: statement.setString( index + 1, event.getMessage() ); break; case ColumnType.CATEGORY: statement.setString( index + 1, event.getCategory() ); break; case ColumnType.PRIORITY: statement.setString( index + 1, event.getPriority().getName() ); break; case ColumnType.CONTEXT: statement.setString( index + 1, getContextMap( event.getContextMap(), info.getAux() ) ); break; case ColumnType.STATIC: statement.setString( index + 1, info.getAux() ); break; case ColumnType.THROWABLE: statement.setString( index + 1, getStackTrace( event.getThrowable() ) ); break; default: throw new IllegalStateException( "Unknown ColumnType: " + info.getType() ); } } /** * Return the underlying table * @return the table name */ protected final String getTable() { return m_table; } /** * Return the column info for an supplied index. * @param index the index * @return the column info */ protected final ColumnInfo getColumn( final int index ) { return m_columns[ index ]; } private String getStackTrace( final Throwable throwable ) { if( null == throwable ) { return ""; } final StringWriter sw = new StringWriter(); throwable.printStackTrace( new java.io.PrintWriter( sw ) ); return sw.toString(); } private String getContextMap( final ContextMap map, final String aux ) { if( null == map ) { return ""; } else { return map.get( aux, "" ).toString(); } } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/lf5/LogKitLogRecord.java100644 0 0 7511 10036267317 24360 0ustar 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.log.output.lf5; import java.util.Arrays; import java.util.List; import org.apache.log.ContextMap; import org.apache.log.LogEvent; import org.apache.log.Logger; import org.apache.log.Priority; import org.apache.log.format.Formatter; import org.apache.log.util.StackIntrospector; import org.apache.log4j.lf5.LogLevel; import org.apache.log4j.lf5.LogRecord; /** * An implementation of a LogFactor5 LogRecord based on a * LogKit {@link LogEvent}. * * @author Sylvain Wallez * @version CVS $Revision: 1.7 $ $Date: 2004/02/28 11:31:26 $ */ public class LogKitLogRecord extends LogRecord { /** Is this a severe event ? */ private boolean m_severe; /** * Create a LogFactor record from a LogKit event */ public LogKitLogRecord( final LogEvent event, final Formatter fmt ) { final ContextMap contextMap = event.getContextMap(); Object contextObject; // Category setCategory( event.getCategory() ); // Level setLevel( toLogLevel( event.getPriority() ) ); m_severe = event.getPriority().isGreater( Priority.INFO ); // Location if( null != contextMap && null != ( contextObject = contextMap.get( "method" ) ) ) { setLocation( contextObject.toString() ); } else { setLocation( StackIntrospector.getCallerMethod( Logger.class ) ); } // Message setMessage( event.getMessage() ); // Millis setMillis( event.getTime() ); // NDC setNDC( fmt.format( event ) ); // SequenceNumber //setSequenceNumber( 0L ); // ThreadDescription if( null != contextMap && null != ( contextObject = contextMap.get( "thread" ) ) ) { setThreadDescription( contextObject.toString() ); } else { setThreadDescription( Thread.currentThread().getName() ); } // Thrown setThrown( event.getThrowable() ); // ThrownStackTrace //setThrownStackTrace(""); } public boolean isSevereLevel() { return m_severe; } /** * Convert a LogKit Priority to a LogFactor LogLevel. */ public LogLevel toLogLevel( final Priority priority ) { if( Priority.DEBUG == priority ) { return LogLevel.DEBUG; } else if( Priority.INFO == priority ) { return LogLevel.INFO; } else if( Priority.WARN == priority ) { return LogLevel.WARN; } else if( Priority.ERROR == priority ) { return LogLevel.ERROR; } else if( Priority.FATAL_ERROR == priority ) { return LogLevel.FATAL; } else { return new LogLevel( priority.getName(), priority.getValue() ); } } /** * The LogLevels corresponding to LogKit priorities. */ public static final List LOGKIT_LOGLEVELS = Arrays.asList( new LogLevel[]{ LogLevel.FATAL, LogLevel.ERROR, LogLevel.WARN, LogLevel.INFO, LogLevel.DEBUG } ); } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/lf5/package.html100644 0 0 313 10036267317 22755 0ustar 0 0 LogFactor5 (Swing GUI) based LogTarget. For more info about LogFactor5, please consult its documentation. avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/lf5/LF5LogTarget.java100644 0 0 6321 10036267317 23563 0ustar 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.log.output.lf5; import org.apache.log.LogEvent; import org.apache.log.LogTarget; import org.apache.log.format.Formatter; import org.apache.log.format.PatternFormatter; import org.apache.log4j.lf5.viewer.LogBrokerMonitor; /** * A {@link LogTarget} that displays log events using the * LogFactor5 * Swing GUI. * * @author Sylvain Wallez * @version CVS $Revision: 1.8 $ $Date: 2004/02/28 11:31:25 $ */ public class LF5LogTarget implements LogTarget { /** Common monitor */ private static LogBrokerMonitor c_defaultLogMonitor; /** Default context map formatter */ private static Formatter c_defaultContextFormatter = new PatternFormatter( "" ); /** Monitor for this LogTarget */ private LogBrokerMonitor m_monitor; /** Format for context maps */ private Formatter m_contextFormatter = c_defaultContextFormatter; /** * Create a LogFactorLogTarget on a given LogBrokerMonitor. * @param monitor the monitor */ public LF5LogTarget( final LogBrokerMonitor monitor ) { m_monitor = monitor; } /** * Create LogFactorLogTarget on the default LogBrokerMonitor. */ public LF5LogTarget() { // Creation of m_monitor is deferred up to the first call to processEvent(). // This allows the Swing window to pop up only if this target is actually used. } /** * Sets the {@link Formatter} that will be used to produce the "NDC" (nested diagnostic * context) text on the GUI. * @param formatter the message formatter */ public void setNDCFormatter( final Formatter formatter ) { m_contextFormatter = formatter; } /** * Get the default LogBrokerMonitor instance. * * @return the monitor */ public static synchronized LogBrokerMonitor getDefaultMonitor() { if( null == c_defaultLogMonitor ) { c_defaultLogMonitor = new LogBrokerMonitor( LogKitLogRecord.LOGKIT_LOGLEVELS ); c_defaultLogMonitor.setFontSize( 12 ); c_defaultLogMonitor.show(); } return c_defaultLogMonitor; } /** * Process a log event. * * @param event the log event */ public void processEvent( final LogEvent event ) { if( null == m_monitor ) { m_monitor = getDefaultMonitor(); } m_monitor.addMessage( new LogKitLogRecord( event, m_contextFormatter ) ); } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/jms/JMSQueueTarget.java100644 0 0 6446 10036267317 24304 0ustar 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.log.output.jms; import javax.jms.Message; import javax.jms.Queue; import javax.jms.QueueConnection; import javax.jms.QueueConnectionFactory; import javax.jms.QueueSender; import javax.jms.QueueSession; import javax.jms.Session; import org.apache.log.ErrorHandler; /** * A target that writes to a JMS Queue. * * @author Mircea Toma */ public class JMSQueueTarget extends AbstractJMSTarget { ///ConnectionFactory to use private QueueConnectionFactory m_factory; ///Queue we will send messages to private Queue m_queue; ///Session associated with queue private QueueSession m_session; ///Sender for queue private QueueSender m_sender; ///JMS queue Connection private QueueConnection m_connection; public JMSQueueTarget( final MessageBuilder builder, final QueueConnectionFactory factory, final Queue queue ) { super( builder ); m_factory = factory; m_queue = queue; open(); } public JMSQueueTarget( final MessageBuilder builder, final QueueConnectionFactory factory, final Queue queue, final ErrorHandler handler ) { super( builder, handler ); m_factory = factory; m_queue = queue; open(); } protected void send( final Message message ) { try { m_sender.send( message ); } catch( final Exception e ) { getErrorHandler().error( "Error publishing message", e, null ); } } protected Session getSession() { return m_session; } protected synchronized void openConnection() { try { m_connection = m_factory.createQueueConnection(); m_connection.start(); m_session = m_connection.createQueueSession( false, Session.AUTO_ACKNOWLEDGE ); m_sender = m_session.createSender( m_queue ); } catch( final Exception e ) { getErrorHandler().error( "Error starting connection", e, null ); } } protected synchronized void closeConnection() { try { if( null != m_sender ) m_sender.close(); if( null != m_session ) m_session.close(); if( null != m_connection ) m_connection.close(); } catch( Exception e ) { getErrorHandler().error( "Error closing connection", e, null ); } m_sender = null; m_session = null; m_connection = null; } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/jms/JMSTopicTarget.java100644 0 0 7054 10036267317 24272 0ustar 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.log.output.jms; import javax.jms.Message; import javax.jms.Session; import javax.jms.Topic; import javax.jms.TopicConnection; import javax.jms.TopicConnectionFactory; import javax.jms.TopicPublisher; import javax.jms.TopicSession; import org.apache.log.ErrorHandler; /** * A target that writes to a JMS Topic. * * @author Peter Donald */ public class JMSTopicTarget extends AbstractJMSTarget { ///ConnectionFactory to use private TopicConnectionFactory m_factory; ///Topic we will send messages to private Topic m_topic; ///Session associated with topic private TopicSession m_session; ///Publisher for topic private TopicPublisher m_publisher; ///JMS topic Connection private TopicConnection m_connection; public JMSTopicTarget( final MessageBuilder builder, final TopicConnectionFactory factory, final Topic topic ) { super( builder ); m_factory = factory; m_topic = topic; open(); } public JMSTopicTarget( final MessageBuilder builder, final TopicConnectionFactory factory, final Topic topic, final ErrorHandler handler ) { super( builder, handler ); m_factory = factory; m_topic = topic; open(); } protected void send( final Message message ) { try { m_publisher.publish( message ); } catch( final Exception e ) { getErrorHandler().error( "Error publishing message", e, null ); } } protected Session getSession() { return m_session; } protected synchronized void openConnection() { try { m_connection = m_factory.createTopicConnection(); m_connection.start(); m_session = m_connection.createTopicSession( false, Session.AUTO_ACKNOWLEDGE ); m_publisher = m_session.createPublisher( m_topic ); //if( m_persistent ) publisher.setDeliveryMode( DeliveryMode.PERSISTENT ); //else publisher.setDeliveryMode( DeliveryMode.NON_PERSISTENT ); //publisher.setPriority( m_priority ); //publisher.setTimeToLive( m_timeToLive ); } catch( final Exception e ) { getErrorHandler().error( "Error starting connection", e, null ); } } protected synchronized void closeConnection() { try { if( null != m_publisher ) m_publisher.close(); if( null != m_session ) m_session.close(); if( null != m_connection ) m_connection.close(); } catch( Exception e ) { getErrorHandler().error( "Error closing connection", e, null ); } m_publisher = null; m_session = null; m_connection = null; } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/jms/package.html100644 0 0 105 10036267317 23057 0ustar 0 0 JMS based output destination LogTargets. avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/jms/PropertyInfo.java100644 0 0 3540 10036267317 24127 0ustar 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.log.output.jms; /** * A descriptor for each message property. * * @author Avalon Development Team * @author Mircea Toma */ public class PropertyInfo { ///Name of property private final String m_name; ///Type/Source of property private final int m_type; ///Auxilliary parameters (ie constant or sub-format) private final String m_aux; //may be null /** * Creation of a new property info instance. * @param name the property * @param type the property type * @param aux auxillary property value */ public PropertyInfo( final String name, final int type, final String aux ) { m_type = type; m_aux = aux; m_name = name; } /** * Return the property name * @return the name */ public String getName() { return m_name; } /** * Return the property type * @return the type */ public int getType() { return m_type; } /** * Return the property auxilliary information * @return the information */ public String getAux() { return m_aux; } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/jms/AbstractJMSTarget.java100644 0 0 4501 10036267317 24751 0ustar 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.log.output.jms; import javax.jms.Message; import javax.jms.Session; import org.apache.log.ErrorHandler; import org.apache.log.LogEvent; import org.apache.log.output.AbstractTarget; /** * A target that writes to a JMS Topic. * * @author Peter Donald */ public abstract class AbstractJMSTarget extends AbstractTarget { ///Appropriate MessageBuilder private MessageBuilder m_builder; public AbstractJMSTarget( final MessageBuilder builder ) { m_builder = builder; } public AbstractJMSTarget( final MessageBuilder builder, final ErrorHandler errorHandler ) { super( errorHandler ); m_builder = builder; } protected abstract void send( Message message ); protected abstract Session getSession(); /** * Process a log event, via formatting and outputting it. * * @param event the log event */ protected void doProcessEvent( final LogEvent event ) throws Exception { final Message message = m_builder.buildMessage( getSession(), event ); send( message ); } /** * Startup log session. * */ protected synchronized void open() { if( !isOpen() ) { super.open(); openConnection(); } } /** * Shutdown target. * Attempting to write to target after close() will cause errors to be logged. * */ public synchronized void close() { if( isOpen() ) { closeConnection(); super.close(); } } protected abstract void openConnection(); protected abstract void closeConnection(); } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/jms/PropertyType.java100644 0 0 5114 10036267317 24154 0ustar 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.log.output.jms; /** * A class to hold all constants for PropertyTypes. * * @author Mircea Toma */ public class PropertyType { public static final int STATIC = 1; public static final int CATEGORY = 2; public static final int CONTEXT = 3; public static final int MESSAGE = 4; public static final int TIME = 5; public static final int RELATIVE_TIME = 6; public static final int THROWABLE = 7; public static final int PRIORITY = 8; /** * The maximum value used for TYPEs. Subclasses can define their own TYPEs * starting at MAX_TYPE + 1. */ public static final String STATIC_STR = "static"; public static final String CATEGORY_STR = "category"; public static final String CONTEXT_STR = "context"; public static final String MESSAGE_STR = "message"; public static final String TIME_STR = "time"; public static final String RELATIVE_TIME_STR = "rtime"; public static final String THROWABLE_STR = "throwable"; public static final String PRIORITY_STR = "priority"; public static int getTypeIdFor( final String type ) { if( type.equalsIgnoreCase( CATEGORY_STR ) ) return CATEGORY; else if( type.equalsIgnoreCase( STATIC_STR ) ) return STATIC; else if( type.equalsIgnoreCase( CONTEXT_STR ) ) return CONTEXT; else if( type.equalsIgnoreCase( MESSAGE_STR ) ) return MESSAGE; else if( type.equalsIgnoreCase( PRIORITY_STR ) ) return PRIORITY; else if( type.equalsIgnoreCase( TIME_STR ) ) return TIME; else if( type.equalsIgnoreCase( RELATIVE_TIME_STR ) ) return RELATIVE_TIME; else if( type.equalsIgnoreCase( THROWABLE_STR ) ) { return THROWABLE; } else { throw new IllegalArgumentException( "Unknown Type " + type ); } } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/jms/MessageBuilder.java100644 0 0 2466 10036267317 24370 0ustar 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.log.output.jms; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.Session; import org.apache.log.LogEvent; /** * Interface that classes implement to build JMS Messages. * * @author Avalon Development Team * @author Peter Donald */ public interface MessageBuilder { /** * Creation of a new message. * @param session the session against which the message will be created * @param event the log event * @return the message * @exception JMSException if a messaging error occurs */ Message buildMessage( Session session, LogEvent event ) throws JMSException; } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/jms/TextMessageBuilder.java100644 0 0 12174 10036267317 25252 0ustar 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.log.output.jms; import java.io.PrintWriter; import java.io.StringWriter; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.Session; import javax.jms.TextMessage; import org.apache.log.ContextMap; import org.apache.log.LogEvent; import org.apache.log.format.Formatter; /** * Basic message factory that stores LogEvent in Message. * * @author Avalon Development Team * @author Peter Donald */ public class TextMessageBuilder implements MessageBuilder { private final PropertyInfo[] m_properties; private final Formatter m_formatter; /** * Creation of a new text message builder. * @param formatter the message formatter */ public TextMessageBuilder( final Formatter formatter ) { m_properties = new PropertyInfo[ 0 ]; m_formatter = formatter; } /** * Creation of a new text message builder. * @param properties the property info set * @param formatter the message formatter */ public TextMessageBuilder( final PropertyInfo[] properties, final Formatter formatter ) { m_properties = properties; m_formatter = formatter; } /** * Build a message from the supplied session for the supplied event * @param session the session * @param event the log event * @return the message * @exception JMSException if a messaging related error occurs */ public Message buildMessage( final Session session, final LogEvent event ) throws JMSException { synchronized( session ) { final TextMessage message = session.createTextMessage(); message.setText( getText( event ) ); for( int i = 0; i < m_properties.length; i++ ) { setProperty( message, i, event ); } return message; } } /** * Set a property * @param message the text message * @param index the index * @param event the log event */ private void setProperty( final TextMessage message, final int index, final LogEvent event ) throws JMSException { final PropertyInfo info = m_properties[ index ]; final String name = info.getName(); switch( info.getType() ) { case PropertyType.MESSAGE: message.setStringProperty( name, event.getMessage() ); break; case PropertyType.RELATIVE_TIME: message.setLongProperty( name, event.getRelativeTime() ); break; case PropertyType.TIME: message.setLongProperty( name, event.getTime() ); break; case PropertyType.CATEGORY: message.setStringProperty( name, event.getCategory() ); break; case PropertyType.PRIORITY: message.setStringProperty( name, event.getPriority().getName() ); break; case PropertyType.CONTEXT: message.setStringProperty( name, getContextMap( event.getContextMap(), info.getAux() ) ); break; case PropertyType.STATIC: message.setStringProperty( name, info.getAux() ); break; case PropertyType.THROWABLE: message.setStringProperty( name, getStackTrace( event.getThrowable() ) ); break; default: throw new IllegalStateException( "Unknown PropertyType: " + info.getType() ); } } private String getText( final LogEvent event ) { if( null == m_formatter ) { return event.getMessage(); } else { return m_formatter.format( event ); } } private String getStackTrace( final Throwable throwable ) { if( null == throwable ) { return ""; } final StringWriter stringWriter = new StringWriter(); final PrintWriter printWriter = new PrintWriter( stringWriter ); throwable.printStackTrace( printWriter ); return stringWriter.getBuffer().toString(); } private String getContextMap( final ContextMap map, final String aux ) { if( null == map ) { return ""; } return map.get( aux, "" ).toString(); } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/jms/ObjectMessageBuilder.java100644 0 0 3164 10036267317 25513 0ustar 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.log.output.jms; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.ObjectMessage; import javax.jms.Session; import org.apache.log.LogEvent; /** * Basic message factory that stores LogEvent in Message. * * @author Avalon Development Team * @author Peter Donald */ public class ObjectMessageBuilder implements MessageBuilder { /** * Creation of a new message. * @param session the session against which the message will be created * @param event the log event * @return the message * @exception JMSException if a messaging error occurs */ public Message buildMessage( Session session, LogEvent event ) throws JMSException { //session access is single threaded synchronized( session ) { final ObjectMessage message = session.createObjectMessage(); message.setObject( event ); return message; } } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/AbstractOutputTarget.java100644 0 0 7526 10036267317 25041 0ustar 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.log.output; import org.apache.log.LogEvent; import org.apache.log.format.Formatter; /** Abstract output target. * * Any new output target that is writing to a single connected * resource should extend this class directly or indirectly. * * @author Avalon Development Team * @author Peter Donald */ public abstract class AbstractOutputTarget extends AbstractTarget { /** Formatter for target. */ private Formatter m_formatter; /** Parameterless constructor. */ public AbstractOutputTarget() { } /** * Creation of a new abstract output target instance. * @param formatter the formatter to apply */ public AbstractOutputTarget( final Formatter formatter ) { m_formatter = formatter; } /** Returns the Formatter. */ protected Formatter getFormatter() { return m_formatter; } /** * Abstract method to write data. * * @param data the data to be output */ protected void write( final String data ) { } /** * Process a log event. * @param event the event to process */ protected void doProcessEvent( LogEvent event ) { final String data = format( event ); write( data ); } /** * Startup log session. * */ protected synchronized void open() { if( !isOpen() ) { super.open(); writeHead(); } } /** * Shutdown target. * Attempting to write to target after close() will cause errors to be logged. * */ public synchronized void close() { if( isOpen() ) { writeTail(); super.close(); } } /** * Helper method to format an event into a string, using the formatter if available. * * @param event the LogEvent * @return the formatted string */ private String format( final LogEvent event ) { if( null != m_formatter ) { return m_formatter.format( event ); } else { return event.toString(); } } /** * Helper method to write out log head. * The head initiates a session of logging. */ private void writeHead() { if( !isOpen() ) { return; } final String head = getHead(); if( null != head ) { write( head ); } } /** * Helper method to write out log tail. * The tail completes a session of logging. */ private void writeTail() { if( !isOpen() ) { return; } final String tail = getTail(); if( null != tail ) { write( tail ); } } /** * Helper method to retrieve head for log session. * TODO: Extract from formatter * * @return the head string */ private String getHead() { return null; } /** * Helper method to retrieve tail for log session. * TODO: Extract from formatter * * @return the head string */ private String getTail() { return null; } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/AbstractTarget.java100644 0 0 7412 10036267317 23612 0ustar 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.log.output; import org.apache.log.ErrorAware; import org.apache.log.ErrorHandler; import org.apache.log.LogEvent; import org.apache.log.LogTarget; import org.apache.log.util.Closeable; import org.apache.log.util.DefaultErrorHandler; /** * Abstract target. * * @author Avalon Development Team * @author Peter Donald */ public abstract class AbstractTarget implements LogTarget, ErrorAware, Closeable { private static final ErrorHandler DEFAULT_ERROR_HANDLER = new DefaultErrorHandler(); ///ErrorHandler used by target to delegate Error handling private ErrorHandler m_errorHandler = DEFAULT_ERROR_HANDLER; ///Flag indicating that log session is finished (aka target has been closed) private boolean m_isOpen; /** * AbstractTarget constructor. */ public AbstractTarget() { } /** * AbstractTarget constructor. * @param errorHandler the error handler */ public AbstractTarget( final ErrorHandler errorHandler ) { if( errorHandler == null ) { throw new NullPointerException( "errorHandler specified cannot be null" ); } setErrorHandler( errorHandler ); } /** * Provide component with ErrorHandler. * * @param errorHandler the errorHandler */ public synchronized void setErrorHandler( final ErrorHandler errorHandler ) { m_errorHandler = errorHandler; } /** * Return the open state of the target. * @return TRUE if the target is open else FALSE */ protected synchronized boolean isOpen() { return m_isOpen; } /** * Startup log session. */ protected synchronized void open() { if( !isOpen() ) { m_isOpen = true; } } /** * Process a log event, via formatting and outputting it. * * @param event the log event */ public synchronized void processEvent( final LogEvent event ) { if( !isOpen() ) { getErrorHandler().error( "Writing event to closed stream.", null, event ); return; } try { doProcessEvent( event ); } catch( final Throwable throwable ) { getErrorHandler().error( "Unknown error writing event.", throwable, event ); } } /** * Process a log event, via formatting and outputting it. * This should be overidden by subclasses. * * @param event the log event * @exception Exception if an event processing error occurs */ protected abstract void doProcessEvent( LogEvent event ) throws Exception; /** * Shutdown target. * Attempting to write to target after close() will cause errors to be logged. * */ public synchronized void close() { if( isOpen() ) { m_isOpen = false; } } /** * Helper method to retrieve ErrorHandler for subclasses. * * @return the ErrorHandler */ protected final ErrorHandler getErrorHandler() { return m_errorHandler; } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/net/DatagramOutputTarget.java100644 0 0 7462 10036267317 25603 0ustar 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.log.output.net; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import org.apache.log.format.Formatter; import org.apache.log.output.AbstractOutputTarget; /** * A datagram output target. * Useful for writing using custom protocols or writing to syslog daemons. * * @author Avalon Development Team * @author Peter Donald */ public class DatagramOutputTarget extends AbstractOutputTarget { ///Default encoding of datagram private static final String DEFAULT_ENCODING = "US-ASCII"; ///Socket on which to send datagrams private DatagramSocket m_socket; ///The encoding to use when creating byte array from string private String m_encoding; /** * Create a output target with end point specified by address and port. * * @param address the address endpoint * @param port the address port * @param formatter the message formatter * @param encoding the encoding to use when encoding string * @exception IOException if an error occurs */ public DatagramOutputTarget( final InetAddress address, final int port, final Formatter formatter, final String encoding ) throws IOException { super( formatter ); m_socket = new DatagramSocket(); m_socket.connect( address, port ); m_encoding = encoding; open(); } /** * Create a output target with end point specified by address and port. * * @param address the address endpoint * @param port the address port * @param formatter the message formatter * @exception IOException if an error occurs */ public DatagramOutputTarget( final InetAddress address, final int port, final Formatter formatter ) throws IOException { this( address, port, formatter, DEFAULT_ENCODING ); } /** * Create a output target with end point specified by address and port. * * @param address the address endpoint * @param port the address port * @exception IOException if an error occurs */ public DatagramOutputTarget( final InetAddress address, final int port ) throws IOException { this( address, port, null ); } /** * Method to write output to datagram. * * @param stringData the data to be output */ protected void write( final String stringData ) { try { final byte[] data = stringData.getBytes( m_encoding ); final DatagramPacket packet = new DatagramPacket( data, data.length ); m_socket.send( packet ); } catch( final IOException ioe ) { getErrorHandler().error( "Error sending datagram.", ioe, null ); } } /** * Shutdown target. * Attempting to write to target after close() will cause errors to be logged. */ public synchronized void close() { super.close(); m_socket = null; } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/net/package.html100644 0 0 125 10036267317 23056 0ustar 0 0 Datagram, Socket and SMTP output destination LogTargets. avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/net/SMTPOutputLogTarget.java100644 0 0 12261 10036267317 25321 0ustar 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.log.output.net; import java.util.Date; import javax.mail.Address; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.MimeMessage; import org.apache.log.format.Formatter; import org.apache.log.output.AbstractOutputTarget; /** Logkit output target that logs data via SMTP. * * @author Avalon Development Team * @author Marcus Crafter * @version CVS $Id: SMTPOutputLogTarget.java,v 1.10 2004/03/28 05:05:43 niclas Exp $ * @since 1.1.0 */ public class SMTPOutputLogTarget extends AbstractOutputTarget { // Mail session private final Session m_session; // Message to be sent private Message m_message; // Address to sent mail to private final Address[] m_toAddresses; // Address to mail is to be listed as sent from private final Address m_fromAddress; // Mail subject private final String m_subject; // Current size of mail, in units of log events private int m_msgSize; // Maximum size of mail, in units of log events private final int m_maxMsgSize; // Buffer containing current mail private StringBuffer m_buffer; /** SMTPOutputLogTarget constructor. * * It creates a logkit output target capable of logging to SMTP * (ie. email, email gateway) targets. * * @param session mail session to be used * @param toAddresses addresses logs should be sent to * @param fromAddress address logs say they come from * @param subject subject line logs should use * @param maxMsgSize maximum size of any log mail, in units of log events * @param formatter log formatter to use */ public SMTPOutputLogTarget( final Session session, final Address[] toAddresses, final Address fromAddress, final String subject, final int maxMsgSize, final Formatter formatter ) { super( formatter ); // setup log target m_maxMsgSize = maxMsgSize; m_toAddresses = toAddresses; m_fromAddress = fromAddress; m_subject = subject; m_session = session; // ready for business open(); } /** Method to write data to the log target. * * Logging data is stored in * an internal buffer until the size limit is reached. When this happens * the data is sent to the SMTP target, and the buffer is reset for * subsequent events. * * @param data logging data to be written to target */ protected void write( final String data ) { try { // ensure we have a message object available if( m_message == null ) { m_message = new MimeMessage( m_session ); m_message.setFrom( m_fromAddress ); m_message.setRecipients( Message.RecipientType.TO, m_toAddresses ); m_message.setSubject( m_subject ); m_message.setSentDate( new Date() ); m_msgSize = 0; m_buffer = new StringBuffer(); } // add the data to the buffer, separated by a newline m_buffer.append( data ); m_buffer.append( '\n' ); ++m_msgSize; // send mail if message size has reached it's size limit if( m_msgSize >= m_maxMsgSize ) { send(); } } catch( MessagingException e ) { getErrorHandler().error( "Error creating message", e, null ); } } /** Closes this log target. * * Sends currently buffered message, if existing. */ public synchronized void close() { super.close(); send(); } /** * Method to enable/disable debugging on the mail session. * * @param flag true to enable debugging, false to disable it */ public void setDebug( boolean flag ) { m_session.setDebug( flag ); } /** * Helper method to send the currently buffered message, * if existing. */ private void send() { try { if( m_message != null && m_buffer != null ) { m_message.setText( m_buffer.toString() ); Transport.send( m_message ); m_message = null; } } catch( MessagingException e ) { getErrorHandler().error( "Error sending message", e, null ); } } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/net/SocketOutputTarget.java100644 0 0 6220 10036267317 25302 0ustar 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.log.output.net; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.InetAddress; import java.net.Socket; import org.apache.log.LogEvent; import org.apache.log.output.AbstractOutputTarget; /** * SocketOutputTarget * * Useful for writing the output to a TCP/IP client socket. * * @author Rajendra Ghorpade */ public class SocketOutputTarget extends AbstractOutputTarget { /** Socket to communicate with the server */ private Socket m_socket; /** Output strem to write the log */ private ObjectOutputStream m_outputStream; /** * Creates output target with the end point specified by the address and port * * @param address end point address * @param port the end point port * @exception IOException if an I/O error ocurrs when creating socket */ public SocketOutputTarget( final InetAddress address, final int port ) throws IOException { m_socket = new Socket( address, port ); m_outputStream = new ObjectOutputStream( m_socket.getOutputStream() ); super.open(); } /** * Creates the output target with the end point specified by host and port * * @param host end point host * @param port the end point port * @exception IOException if an I/O error ocurrs when creating socket */ public SocketOutputTarget( final String host, final int port ) throws IOException { m_socket = new Socket( host, port ); m_outputStream = new ObjectOutputStream( m_socket.getOutputStream() ); super.open(); } /** * Writes the output as a LogEvent without formatting. * Formatting ia applied on the server side where it is log. * * @param event the LogEvent */ protected void write( LogEvent event ) { try { m_outputStream.writeObject( event ); } catch( final IOException ioex ) { getErrorHandler().error( "Error writting to socket", ioex, null ); } } /** * To process the LogEvent * * @param event the LogEvent */ protected void doProcessEvent( LogEvent event ) { write( event ); } /** * Shutdown target. * Attempting to write to target after close() will cause errors to be logged. */ public synchronized void close() { super.close(); m_socket = null; } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/NullOutputLogTarget.java100644 0 0 2244 10036267317 24642 0ustar 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.log.output; /** * A output target that does nothing. Useful for profiling. * * @author Avalon Development Team * @author Peter Donald */ public class NullOutputLogTarget extends AbstractOutputTarget { /** * Creation of a new null log target. */ public NullOutputLogTarget() { open(); } /** * Do nothing output method. * * @param data the data to be output */ protected void write( final String data ) { } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/MemoryTarget.java100644 0 0 11623 10036267317 23336 0ustar 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.log.output; import org.apache.log.LogEvent; import org.apache.log.LogTarget; import org.apache.log.Priority; /** * Output LogEvents into an buffer in memory. * At a later stage these LogEvents can be forwarded or * pushed to another target. This pushing is triggered * when buffer is full, the priority of a LogEvent reaches a threshold * or when another class calls the push method. * * This is based on specification of MemoryHandler in Logging JSR47. * * @author Avalon Development Team * @author Peter Donald */ public class MemoryTarget extends AbstractTarget { ///Buffer for all the LogEvents private final LogEvent[] m_buffer; ///Priority at which to push LogEvents to next LogTarget private Priority m_threshold; ///Target to push LogEvents to private LogTarget m_target; ///Count of used events private int m_used; ///Position of last element inserted private int m_index; ///Flag indicating whether it is possible to overite elements in array private boolean m_overwrite; /** * Creation of a new instance of the memory target. * @param target the target to push LogEvents to * @param size the event buffer size * @param threshold the priority at which to push LogEvents to next LogTarget */ public MemoryTarget( final LogTarget target, final int size, final Priority threshold ) { m_target = target; m_buffer = new LogEvent[ size ]; m_threshold = threshold; open(); } /** * Set flag indicating whether it is valid to overwrite memory buffer. * * @param overwrite true if buffer should overwrite logevents in buffer, false otherwise */ protected synchronized void setOverwrite( final boolean overwrite ) { m_overwrite = overwrite; } /** * Process a log event, via formatting and outputting it. * * @param event the log event */ protected synchronized void doProcessEvent( final LogEvent event ) { //Check if it is full if( isFull() ) { if( m_overwrite ) { m_used--; } else { getErrorHandler().error( "Memory buffer is full", null, event ); return; } } if( 0 == m_used ) { m_index = 0; } else { m_index = ( m_index + 1 ) % m_buffer.length; } m_buffer[ m_index ] = event; m_used++; if( shouldPush( event ) ) { push(); } } /** * Check if memory buffer is full. * * @return true if buffer is full, false otherwise */ public final synchronized boolean isFull() { return m_buffer.length == m_used; } /** * Determine if LogEvent should initiate a push to target. * Subclasses can overide this method to change the conditions * under which a push occurs. * * @param event the incoming LogEvent * @return true if should push, false otherwise */ protected synchronized boolean shouldPush( final LogEvent event ) { return ( m_threshold.isLowerOrEqual( event.getPriority() ) || isFull() ); } /** * Push log events to target. */ public synchronized void push() { if( null == m_target ) { getErrorHandler().error( "Can not push events to a null target", null, null ); return; } try { final int size = m_used; int base = m_index - m_used + 1; if( base < 0 ) { base += m_buffer.length; } for( int i = 0; i < size; i++ ) { final int index = ( base + i ) % m_buffer.length; //process event in buffer m_target.processEvent( m_buffer[ index ] ); //help GC m_buffer[ index ] = null; m_used--; } } catch( final Throwable throwable ) { getErrorHandler().error( "Unknown error pushing events.", throwable, null ); } } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/ServletOutputLogTarget.java100644 0 0 5316 10036267317 25357 0ustar 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.log.output; import javax.servlet.ServletContext; import org.apache.log.format.Formatter; /** * Generic logging interface. Implementations are based on the strategy * pattern. * * @author Tommy Santoso */ public class ServletOutputLogTarget extends AbstractOutputTarget { ///The servlet context written to (may be null in which case it won't log at all) private ServletContext m_context; /** * Constructor. * * @param context ServletContext to use for logging. */ public ServletOutputLogTarget( final ServletContext context, final Formatter formatter ) { super( formatter ); m_context = context; open(); } /** * Constructor. * * @param context ServletContext to use for logging. */ public ServletOutputLogTarget( final ServletContext context ) { m_context = context; open(); } /** * Logs message to servlet context log file * * @param message message to log to servlet context log file. */ protected void write( final String message ) { final int len = message.length(); final char last = len > 0 ? message.charAt( len - 1 ) : 0; final char prev = len > 1 ? message.charAt( len - 2 ) : 0; final String trimmedMessage; if( prev == '\r' && last == '\n' ) { trimmedMessage = message.substring( 0, len - 2 ); } else if( last == '\n' ) { trimmedMessage = message.substring( 0, len - 1 ); } else { trimmedMessage = message; } final ServletContext context = m_context; if( null != context ) { synchronized( context ) { context.log( trimmedMessage ); } } } /** * Shutdown target. * Attempting to write to target after close() will cause errors to be logged. */ public synchronized void close() { super.close(); m_context = null; } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/package.html100644 0 0 135 10036267317 22271 0ustar 0 0 This package contains some useful output destination LogTargets. avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/PriorityFilteringTarget.java100644 0 0 6272 10036267317 25537 0ustar 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. */ package org.apache.log.output; import org.apache.log.LogEvent; import org.apache.log.LogTarget; import org.apache.log.Priority; import org.apache.log.util.Closeable; /** * This is a priority filtering target that forwards only requests * to other (wrapped) targets that have the same or a higher * priority. * * @author Avalon Development Team */ public class PriorityFilteringTarget extends AbstractTarget { private final Priority m_priority; private final boolean m_closeWrapped; /** Log targets in filter chain */ private LogTarget m_targets[]; /** * @param priority The priority used to filter * @param closeWrappedTarget see AbstractWrappingTarget */ public PriorityFilteringTarget(Priority priority, boolean closeWrappedTarget) { m_priority = priority; m_closeWrapped = closeWrappedTarget; open(); } /** * @param priority The priority used to filter */ public PriorityFilteringTarget(Priority priority) { this(priority, false ); } /** * Add a new target to output chain. * * @param target the target */ public void addTarget( final LogTarget target ) { if( null == m_targets ) { m_targets = new LogTarget[]{target}; } else { final LogTarget oldTargets[] = m_targets; m_targets = new LogTarget[ oldTargets.length + 1 ]; System.arraycopy( oldTargets, 0, m_targets, 0, oldTargets.length ); m_targets[ m_targets.length - 1 ] = target; } } /* (non-Javadoc) * @see org.apache.log.output.AbstractTarget#doProcessEvent(org.apache.log.LogEvent) */ protected void doProcessEvent(LogEvent event) throws Exception { if ( event != null && m_targets != null && !event.getPriority().isLower(m_priority) ) { for( int i = 0; i < m_targets.length; i++ ) { m_targets[ i ].processEvent( event ); } } } /* (non-Javadoc) * @see org.apache.log.util.Closeable#close() */ public void close() { super.close(); if( m_closeWrapped && m_targets != null ) { for( int i = 0; i < m_targets.length; i++ ) { if ( m_targets[i] instanceof Closeable ) { ( (Closeable)m_targets[i] ).close(); } } } } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/AsyncLogTarget.java100644 0 0 14362 10036267317 23610 0ustar 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.log.output; import java.util.LinkedList; import org.apache.log.ErrorAware; import org.apache.log.ErrorHandler; import org.apache.log.LogEvent; import org.apache.log.LogTarget; /** * An asynchronous LogTarget that sends entries on in another thread. * It is the responsibility of the user of this class to start * the thread etc. * *
 * LogTarget mySlowTarget = ...;
 * AsyncLogTarget asyncTarget = new AsyncLogTarget( mySlowTarget );
 * Thread thread = new Thread( asyncTarget );
 * thread.setPriority( Thread.MIN_PRIORITY );
 * thread.start();
 *
 * logger.setLogTargets( new LogTarget[] { asyncTarget } );
 * 
* * @author Avalon Development Team * @author Peter Donald */ public class AsyncLogTarget extends AbstractWrappingTarget implements Runnable { private final LinkedList m_list; private final int m_queueSize; /** * Creation of a new async log target. * @param logTarget the underlying target */ public AsyncLogTarget( final LogTarget logTarget ) { this( logTarget, 15 ); } /** * Creation of a new async log target. * @param logTarget the underlying target * @param queueSize the queue size */ public AsyncLogTarget( final LogTarget logTarget, final int queueSize ) { this( logTarget, queueSize, false ); } /** * Creation of a new async log target. * @param logTarget the underlying target * @param closeTarget close the underlying target when this target is closed. This flag * has no effect unless the logTarget implements Closeable. */ public AsyncLogTarget( final LogTarget logTarget, final boolean closeTarget ) { this( logTarget, 15, closeTarget ); } /** * Creation of a new async log target. * @param logTarget the underlying target * @param queueSize the queue size * @param closeTarget close the underlying target when this target is closed. This flag * has no effect unless the logTarget implements Closeable. */ public AsyncLogTarget( final LogTarget logTarget, final int queueSize, final boolean closeTarget ) { super( logTarget, closeTarget ); m_list = new LinkedList(); m_queueSize = queueSize; open(); } /** * Provide component with ErrorHandler. * * @param errorHandler the errorHandler */ public synchronized void setErrorHandler( final ErrorHandler errorHandler ) { super.setErrorHandler( errorHandler ); if( this.getLogTarget() instanceof ErrorAware ) { ( (ErrorAware)this.getLogTarget() ).setErrorHandler( errorHandler ); } } /** * Process a log event by adding it to queue. * * @param event the log event */ public void doProcessEvent( final LogEvent event ) { synchronized( m_list ) { int size = m_list.size(); while( m_queueSize <= size ) { try { m_list.wait(); } catch( final InterruptedException ie ) { //This really should not occur ... //Maybe we should log it though for //now lets ignore it } size = m_list.size(); } m_list.addFirst( event ); if( size == 0 ) { //tell the "server" thread to wake up //if it is waiting for a queue to contain some items m_list.notify(); } } } /** * Thread startup. */ public void run() { //set this variable when thread is interupted //so we know we can shutdown thread soon. boolean interupted = false; while( true ) { LogEvent event = null; synchronized( m_list ) { while( null == event ) { final int size = m_list.size(); if( size > 0 ) { event = (LogEvent)m_list.removeLast(); if( size == m_queueSize ) { //tell the "client" thread to wake up //if it is waiting for a queue position to open up m_list.notify(); } } else if( interupted || Thread.interrupted() ) { //ie there is nothing in queue and thread is interrupted //thus we stop thread return; } else { try { m_list.wait(); } catch( final InterruptedException ie ) { //Ignore this and let it be dealt in next loop //Need to set variable as the exception throw cleared status interupted = true; } } } } try { //actually process an event this.getLogTarget().processEvent( event ); } catch( final Throwable throwable ) { getErrorHandler().error( "Unknown error writing event.", throwable, event ); } } } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/output/AbstractWrappingTarget.java100644 0 0 4752 10036267317 25326 0ustar 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.log.output; import org.apache.log.LogTarget; import org.apache.log.util.Closeable; /** * Abstract base class for targets that wrap other targets. The class * provides functionality for optionally closing a wrapped target that * implements org.apache.log.util.Closeable. * * @see org.apache.log.util.Closeable * @author Avalon Development Team */ public abstract class AbstractWrappingTarget extends AbstractTarget { private final boolean m_closeWrapped; private final LogTarget m_wrappedLogTarget; /** * Creation of a new wrapping log target. * * @param logTarget the underlying target * @param closeWrappedTarget boolean flag indicating whether the wrapped log target * should be closed when this target is closed. Note: This flag has no * effect unless the underlying target implements org.apache.log.util.Closeable. * @see org.apache.log.util.Closeable */ public AbstractWrappingTarget( final LogTarget logTarget, final boolean closeWrappedTarget ) { m_wrappedLogTarget = logTarget; m_closeWrapped = closeWrappedTarget; } /** * Creation of a new wrapping log target. The underlying log target will * not be closed when this target is closed. * * @param logTarget the underlying target */ public AbstractWrappingTarget( final LogTarget logTarget ) { this( logTarget, false ); } public void close() { super.close(); if( m_closeWrapped && m_wrappedLogTarget instanceof Closeable ) { ( (Closeable)m_wrappedLogTarget ).close(); } } /** * Return the target for subclasses */ protected final LogTarget getLogTarget() { return m_wrappedLogTarget; } }avalon-logkit-2.0.dev-0/src/java/org/apache/log/LogEvent.java100644 0 0 11475 10036267317 21107 0ustar 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.log; import java.io.ObjectStreamException; import java.io.Serializable; /** * This class encapsulates each individual log event. * LogEvents usually originate at a Logger and are routed * to LogTargets. * * @author Avalon Development Team * @author Peter Donald */ public final class LogEvent implements Serializable { //A Constant used when retrieving time relative to start of applicaiton start private static final long START_TIME = System.currentTimeMillis(); ///The category that this LogEvent concerns. (Must not be null) private String m_category; ///The message to be logged. (Must not be null) private String m_message; ///The exception that caused LogEvent if any. (May be null) private Throwable m_throwable; ///The time in millis that LogEvent occurred private long m_time; ///The priority of LogEvent. (Must not be null) private Priority m_priority; ///The context map associated with LogEvent. (May be null). private ContextMap m_contextMap; /** * Get Priority for LogEvent. * * @return the LogEvent Priority */ public final Priority getPriority() { return m_priority; } /** * Set the priority of LogEvent. * * @param priority the new LogEvent priority */ public final void setPriority( final Priority priority ) { m_priority = priority; } /** * Get ContextMap associated with LogEvent * * @return the ContextMap */ public final ContextMap getContextMap() { return m_contextMap; } /** * Set the ContextMap for this LogEvent. * * @param contextMap the context map */ public final void setContextMap( final ContextMap contextMap ) { m_contextMap = contextMap; } /** * Get the category that LogEvent relates to. * * @return the name of category */ public final String getCategory() { return m_category; } /** * Get the message associated with event. * * @return the message */ public final String getMessage() { return m_message; } /** * Get throwabe instance associated with event. * * @return the Throwable */ public final Throwable getThrowable() { return m_throwable; } /** * Get the absolute time of the log event. * * @return the absolute time */ public final long getTime() { return m_time; } /** * Get the time of the log event relative to start of application. * * @return the time */ public final long getRelativeTime() { return m_time - START_TIME; } /** * Set the LogEvent category. * * @param category the category */ public final void setCategory( final String category ) { m_category = category; } /** * Set the message for LogEvent. * * @param message the message */ public final void setMessage( final String message ) { m_message = message; } /** * Set the throwable for LogEvent. * * @param throwable the instance of Throwable */ public final void setThrowable( final Throwable throwable ) { m_throwable = throwable; } /** * Set the absolute time of LogEvent. * * @param time the time */ public final void setTime( final long time ) { m_time = time; } /** * Helper method that replaces deserialized priority with correct singleton. * * @return the singleton version of object * @exception ObjectStreamException if an error occurs */ private Object readResolve() throws ObjectStreamException { if( null == m_category ) { m_category = ""; } if( null == m_message ) { m_message = ""; } String priorityName = ""; if( null != m_priority ) { priorityName = m_priority.getName(); } m_priority = Priority.getPriorityForName( priorityName ); return this; } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/ErrorHandler.java100644 0 0 2176 10036267317 21731 0ustar 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.log; /** * Handle unrecoverable errors that occur during logging. * Based on Log4js notion of ErrorHandlers. * * @author Peter Donald */ public interface ErrorHandler { /** * Log an unrecoverable error. * * @param message the error message * @param throwable the exception associated with error (may be null) * @param event the LogEvent that caused error, if any (may be null) */ void error( String message, Throwable throwable, LogEvent event ); } avalon-logkit-2.0.dev-0/src/java/org/apache/log/util/LoggerListener.java100644 0 0 2417 10036267317 23242 0ustar 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.log.util; import org.apache.log.Logger; /** * The LoggerListener class is used to notify listeners * when a new Logger object is created. Loggers are created * when a client requests a new Logger via {@link Logger#getChildLogger}. * * @author Avalon Development Team * @author Peter Donald */ public abstract class LoggerListener { /** * Notify listener that Logger was created. * * @param category the error message * @param logger the logger that was created */ public abstract void loggerCreated( String category, Logger logger ); } avalon-logkit-2.0.dev-0/src/java/org/apache/log/util/StackIntrospector.java100644 0 0 25150 10036267317 24015 0ustar 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.log.util; import java.io.PrintWriter; import java.io.StringWriter; /** * A set of utilities to inspect current stack frame. * * @author Avalon Development Team * @author Sylvain Wallez * @author Stuart Roebuck * @version CVS $Revision: 1.16 $ $Date: 2004/02/28 11:31:25 $ */ public final class StackIntrospector { /** * Hack to get the call stack as an array of classes. The * SecurityManager class provides it as a protected method, so * change it to public through a new method ! */ private static final class CallStack extends SecurityManager { /** * Returns the current execution stack as an array of classes. * The length of the array is the number of methods on the execution * stack. The element at index 0 is the class of the currently executing * method, the element at index 1 is the class of that method's caller, * and so on. */ public Class[] get() { return getClassContext(); } } ///Method to cache CallStack hack as needed private static CallStack c_callStack; /** * Private constructor to block instantiation. * */ private StackIntrospector() { } /** * Create Hack SecurityManager to get CallStack. * * @return the CallStack object * @exception SecurityException if an existing SecurityManager disallows construction * of another SecurityManager */ private static synchronized CallStack getCallStack() throws SecurityException { if( null == c_callStack ) { //Lazily create CallStack accessor as appropriate c_callStack = new CallStack(); } return c_callStack; } /** * Find the caller of the passed in Class. * May return null if caller not found on execution stack * * @param clazz the Class to search for on stack to find caller of * @return the Class of object that called parrameter class * @exception SecurityException if an existing SecurityManager disallows construction * of another SecurityManager and thus blocks method results */ public static final Class getCallerClass( final Class clazz ) throws SecurityException { return getCallerClass( clazz, 0 ); } /** * Find the caller of the passed in Class. * May return null if caller not found on execution stack * * @param clazz the Class to search for on stack to find caller of * @param stackDepthOffset Offset call-stack depth to find caller * @return the Class of object that called parrameter class * @exception SecurityException if an existing SecurityManager disallows construction * of another SecurityManager and thus blocks method results */ public static final Class getCallerClass( final Class clazz, int stackDepthOffset ) { final Class[] stack = getCallStack().get(); // Traverse the call stack in reverse order until we find clazz for( int i = stack.length - 1; i >= 0; i-- ) { if( clazz.isAssignableFrom( stack[ i ] ) ) { // Found : the caller is the previous stack element return stack[ i + 1 + stackDepthOffset ]; } } //Unable to locate class in call stack return null; } /** * Get the method path name for the method from which the LogEvent was * created, this includes the path name and the source filename and line * number if the source was compiled with debugging on. * * @param clazz the Class to search for on stack to find caller of * @return The method path name in the form "the.package.path.Method" */ public static final String getCallerMethod( final Class clazz ) { final String className = clazz.getName(); //Extract stack into a StringBuffer final StringWriter sw = new StringWriter(); final Throwable throwable = new Throwable(); throwable.printStackTrace( new PrintWriter( sw, true ) ); final StringBuffer buffer = sw.getBuffer(); //Cache vars used in loop final StringBuffer line = new StringBuffer(); final int length = buffer.length(); //setup state boolean found = false; int state = 0; //parse line for( int i = 0; i < length; i++ ) { final char ch = buffer.charAt( i ); switch( state ) { case 0: //Strip the first line from input if( '\n' == ch ) { state = 1; } break; case 1: //strip 't' from 'at' if( 't' == ch ) { state = 2; } break; case 2: //Strip space after 'at' line.setLength( 0 ); state = 3; break; case 3: //accumulate all characters to end of line if( '\n' != ch ) { line.append( ch ); } else { //At this stage you have the line that looks like //com.biz.SomeClass.someMethod(SomeClass.java:22) final String method = line.toString(); ///Determine if line is a match for class final boolean match = method.startsWith( className ); if( !found && match ) { //If this is the first time we cound class then //set found to true and look for caller into class found = true; } else if( found && !match ) { //We have now located caller of Clazz return method; } //start parsing from start of line again state = 1; } } } return ""; } /** * Return the current call stack as a String, starting with the first call * in the stack after a reference to the clazz class, and then * display entries entries. * *

This can be useful for debugging code to determine where calls to a * method are coming from.

* * @param clazz the last class on the stack you are not interested in! * @param entries the number of stack lines to return. * * @return The method path name in the form "the.package.path.Method" */ public static final String getRecentStack( final Class clazz, int entries ) { final String className = clazz.getName(); //Extract stack into a StringBuffer final StringWriter sw = new StringWriter(); final Throwable throwable = new Throwable(); throwable.printStackTrace( new PrintWriter( sw, true ) ); final StringBuffer buffer = sw.getBuffer(); //Cache vars used in loop final StringBuffer line = new StringBuffer(); final StringBuffer stack = new StringBuffer(); final int length = buffer.length(); //setup state boolean found = false; int state = 0; //parse line for( int i = 0; i < length; i++ ) { final char ch = buffer.charAt( i ); switch( state ) { case 0: //Strip the first line from input if( '\n' == ch ) { state = 1; } break; case 1: //strip 't' from 'at' if( 't' == ch ) { state = 2; } break; case 2: //Strip space after 'at' line.setLength( 0 ); state = 3; break; case 3: //accumulate all characters to end of line if( '\n' != ch ) { line.append( ch ); } else { //At this stage you have the line that looks like //com.biz.SomeClass.someMethod(SomeClass.java:22) final String method = line.toString(); ///Determine if line is a match for class final boolean match = method.startsWith( className ); if( !found && match ) { //If this is the first time we cound class then //set found to true and look for caller into class found = true; } else if( found && !match ) { //We are looking at the callers of Clazz stack.append( method ); entries--; if( entries == 0 ) { return stack.toString(); } stack.append( "\n" ); } //start parsing from start of line again state = 1; } } } return ""; } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/util/DefaultErrorHandler.java100644 0 0 2705 10036267317 24211 0ustar 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.log.util; import org.apache.log.ErrorHandler; import org.apache.log.LogEvent; /** * Handle unrecoverable errors that occur during logging by * writing to standard error. * * @author Peter Donald */ public class DefaultErrorHandler implements ErrorHandler { /** * Log an unrecoverable error. * * @param message the error message * @param throwable the exception associated with error (may be null) * @param event the LogEvent that caused error, if any (may be null) */ public void error( final String message, final Throwable throwable, final LogEvent event ) { System.err.println( "Logging Error: " + message ); if( null != throwable ) { throwable.printStackTrace(); } } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/util/Closeable.java100644 0 0 1550 10036267317 22203 0ustar 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.log.util; /** * Interface implemented by LogTargets that are capable of being * closed. * * @author Peter Donald */ public interface Closeable { /** * Close the LogTarget. */ void close(); } avalon-logkit-2.0.dev-0/src/java/org/apache/log/util/LoggerOutputStream.java100644 0 0 6377 10036267317 24142 0ustar 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.log.util; import java.io.EOFException; import java.io.IOException; import java.io.OutputStream; import org.apache.log.Logger; import org.apache.log.Priority; /** * Redirect an output stream to a logger. * This class is useful to redirect standard output or * standard error to a Logger. An example use is * *
 * final LoggerOutputStream outputStream =
 *     new LoggerOutputStream( logger, Priority.DEBUG );
 * final PrintStream output = new PrintStream( outputStream, true );
 *
 * System.setOut( output );
 * 
* * @author Avalon Development Team * @author Peter Donald */ public class LoggerOutputStream extends OutputStream { ///Logger that we log to private final Logger m_logger; ///Log level we log to private final Priority m_priority; ///The buffered output so far private final StringBuffer m_output = new StringBuffer(); ///Flag set to true once stream closed private boolean m_closed; /** * Construct OutputStreamLogger to write to a particular logger at a particular priority. * * @param logger the logger to write to * @param priority the priority at which to log */ public LoggerOutputStream( final Logger logger, final Priority priority ) { m_logger = logger; m_priority = priority; } /** * Shutdown stream. * @exception IOException if an error occurs while closing the stream */ public void close() throws IOException { flush(); super.close(); m_closed = true; } /** * Write a single byte of data to output stream. * * @param data the byte of data * @exception IOException if an error occurs */ public void write( final int data ) throws IOException { checkValid(); //Should we properly convert char using locales etc?? m_output.append( (char)data ); if( '\n' == data ) { flush(); } } /** * Flush data to underlying logger. * * @exception IOException if an error occurs */ public synchronized void flush() throws IOException { checkValid(); m_logger.log( m_priority, m_output.toString() ); m_output.setLength( 0 ); } /** * Make sure stream is valid. * * @exception IOException if an error occurs */ private void checkValid() throws IOException { if( true == m_closed ) { throw new EOFException( "OutputStreamLogger closed" ); } } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/util/package.html100644 0 0 111 10036267317 21700 0ustar 0 0 Utilities suppporting the logging framework. avalon-logkit-2.0.dev-0/src/java/org/apache/log/format/Formatter.java100644 0 0 2003 10036267317 22562 0ustar 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.log.format; import org.apache.log.LogEvent; /** This defines the interface for components that wish to serialize * LogEvents into Strings. * * @author Peter Donald */ public interface Formatter { /** * Serialize log event into string. * * @param event the event * @return the formatted string */ String format( LogEvent event ); } avalon-logkit-2.0.dev-0/src/java/org/apache/log/format/XMLFormatter.java100644 0 0 12657 10036267317 23203 0ustar 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.log.format; import java.util.Date; import org.apache.log.LogEvent; /** * Basic XML formatter that writes out a basic XML-ified log event. * * Note that this formatter assumes that the category and context * values will produce strings that do not need to be escaped in XML. * * @author Peter Donald */ public class XMLFormatter implements Formatter { private static final String EOL = System.getProperty( "line.separator", "\n" ); //Booleans indicating whether or not we //print out a particular field private boolean m_printTime = true; private boolean m_printRelativeTime = false; private boolean m_printPriority = true; private boolean m_printCategory = true; // This can't be changed to 'true' until the Testcases have been fixed // private boolean m_printContext = false; private boolean m_printMessage = true; private boolean m_printException = true; private boolean m_printNumericTime = true; /** * Print out time field to log. * * @param printTime true to print time, false otherwise */ public void setPrintTime( final boolean printTime ) { m_printTime = printTime; } /** * Print out relativeTime field to log. * * @param printRelativeTime true to print relativeTime, false otherwise */ public void setPrintRelativeTime( final boolean printRelativeTime ) { m_printRelativeTime = printRelativeTime; } /** * Print out priority field to log. * * @param printPriority true to print priority, false otherwise */ public void setPrintPriority( final boolean printPriority ) { m_printPriority = printPriority; } /** * Print out category field to log. * * @param printCategory true to print category, false otherwise */ public void setPrintCategory( final boolean printCategory ) { m_printCategory = printCategory; } /** * Print out context field to log. * * @param printContext true to print context, false otherwise */ public void setPrintContext( final boolean printContext ) { m_printContext = printContext; } /** * Print out message field to log. * * @param printMessage true to print message, false otherwise */ public void setPrintMessage( final boolean printMessage ) { m_printMessage = printMessage; } /** * Print out exception field to log. * * @param printException true to print exception, false otherwise */ public void setPrintException( final boolean printException ) { m_printException = printException; } /** * Format log event into string. * * @param event the event * @return the formatted string */ public String format( final LogEvent event ) { final StringBuffer sb = new StringBuffer( 400 ); sb.append( "" ); sb.append( EOL ); if( m_printTime ) { sb.append( " " ); sb.append( EOL ); } if( m_printRelativeTime ) { sb.append( " " ); sb.append( event.getRelativeTime() ); sb.append( "" ); sb.append( EOL ); } if( m_printPriority ) { sb.append( " " ); sb.append( event.getPriority().getName() ); sb.append( "" ); sb.append( EOL ); } if( m_printCategory ) { sb.append( " " ); sb.append( event.getCategory() ); sb.append( "" ); sb.append( EOL ); } if( m_printContext && null != event.getContextMap() ) { sb.append( " " ); sb.append( event.getContextMap() ); sb.append( "" ); sb.append( EOL ); } if( m_printMessage && null != event.getMessage() ) { sb.append( " " ); sb.append( EOL ); } if( m_printException && null != event.getThrowable() ) { sb.append( " " ); sb.append( EOL ); } sb.append( "" ); sb.append( EOL ); return sb.toString(); } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/format/SyslogFormatter.java100644 0 0 13450 10036267317 24013 0ustar 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.log.format; import org.apache.log.LogEvent; import org.apache.log.Priority; /** * A formatter that serializes in the format originally * used by BSD syslog daemon. * * @author Peter Donald */ public class SyslogFormatter implements Formatter { public static final int PRIORITY_DEBUG = 7; public static final int PRIORITY_INFO = 6; public static final int PRIORITY_NOTICE = 5; public static final int PRIORITY_WARNING = 4; public static final int PRIORITY_ERR = 3; public static final int PRIORITY_CRIT = 2; public static final int PRIORITY_ALERT = 1; public static final int PRIORITY_EMERG = 0; /* * Constants for facility. */ public static final int FACILITY_KERN = ( 0 << 3 ); public static final int FACILITY_USER = ( 1 << 3 ); public static final int FACILITY_MAIL = ( 2 << 3 ); public static final int FACILITY_DAEMON = ( 3 << 3 ); public static final int FACILITY_AUTH = ( 4 << 3 ); public static final int FACILITY_SYSLOG = ( 5 << 3 ); public static final int FACILITY_LPR = ( 6 << 3 ); public static final int FACILITY_NEWS = ( 7 << 3 ); public static final int FACILITY_UUCP = ( 8 << 3 ); public static final int FACILITY_CRON = ( 9 << 3 ); public static final int FACILITY_AUTHPRIV = ( 10 << 3 ); public static final int FACILITY_FTP = ( 11 << 3 ); public static final int FACILITY_LOCAL0 = ( 16 << 3 ); public static final int FACILITY_LOCAL1 = ( 17 << 3 ); public static final int FACILITY_LOCAL2 = ( 18 << 3 ); public static final int FACILITY_LOCAL3 = ( 19 << 3 ); public static final int FACILITY_LOCAL4 = ( 20 << 3 ); public static final int FACILITY_LOCAL5 = ( 21 << 3 ); public static final int FACILITY_LOCAL6 = ( 22 << 3 ); public static final int FACILITY_LOCAL7 = ( 23 << 3 ); ///String descriptions of all the facilities protected static final String[] FACILITY_DESCRIPTIONS = { "kern", "user", "mail", "daemon", "auth", "syslog", "lpr", "news", "uucp", "cron", "authpriv", "ftp", "", "", "", "", "local0", "local1", "local2", "local3", "local4", "local5", "local6", "local7" }; ///Constant for holding facility id private int m_facility; ///flag to decide whether we write out Facility banner private boolean m_showFacilityBanner; /** * Constructor that assumes FACILITY_USER. */ public SyslogFormatter() { this( FACILITY_USER ); } /** * Constructor so that you can associate facility with formatter. * * @param facility the facility constant */ public SyslogFormatter( final int facility ) { this( facility, true ); } /** * Constructor allowing setting of facility and whether to show banner. * * @param facility the facility code. * @param showFacilityBanner true if facility banner should be shown */ public SyslogFormatter( final int facility, final boolean showFacilityBanner ) { m_facility = facility; m_showFacilityBanner = showFacilityBanner; } /** * Format log event into syslog string. * * @param event the event * @return the formatted string */ public String format( final LogEvent event ) { final int priority = getSyslogPriority( event ); final int facility = getSyslogFacility( event ); String message = event.getMessage(); //TODO: Clean and spruce message here (ie remove \t and \n's) if( null == message ) { message = ""; } if( m_showFacilityBanner ) { message = getFacilityDescription( facility ) + ": " + message; } return "<" + ( facility | priority ) + "> " + message; } /** * Retrieve description for facility. * * @param facility the facility code * @return the facility description */ protected String getFacilityDescription( final int facility ) { return FACILITY_DESCRIPTIONS[ facility >> 3 ]; } /** * Get facility associated with event. * Default implementation returns facility set in constructor. * * @param event the log event * @return the facility code */ protected int getSyslogFacility( final LogEvent event ) { return m_facility; } /** * Get syslog priority code for LogEvent. * This is done by translating LogKit priority to syslog priority. * * @param event the log event * @return the priority code */ protected int getSyslogPriority( final LogEvent event ) { if( event.getPriority().isLowerOrEqual( Priority.DEBUG ) ) { return PRIORITY_DEBUG; } else if( event.getPriority().isLowerOrEqual( Priority.INFO ) ) { return PRIORITY_INFO; } else if( event.getPriority().isLowerOrEqual( Priority.WARN ) ) { return PRIORITY_WARNING; } else if( event.getPriority().isLowerOrEqual( Priority.ERROR ) ) { return PRIORITY_ERR; } else { return PRIORITY_CRIT; } } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/format/package.html100644 0 0 142 10036267317 22217 0ustar 0 0 This package contains formmaters that serialize LogEvents to strings. avalon-logkit-2.0.dev-0/src/java/org/apache/log/format/ExtendedPatternFormatter.java100644 0 0 11457 10036267317 25636 0ustar 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.log.format; import org.apache.log.ContextMap; import org.apache.log.LogEvent; import org.apache.log.Logger; import org.apache.log.util.StackIntrospector; /** * Formatter especially designed for debugging applications. * * This formatter extends the standard PatternFormatter to add * two new possible expansions. These expansions are %{method} * and %{thread}. In both cases the context map is first checked * for values with specified key. This is to facilitate passing * information about caller/thread when threads change (as in * AsyncLogTarget). They then attempt to determine appropriate * information dynamically. * * @author Avalon Development Team * @author Peter Donald * @version CVS $Revision: 1.16 $ $Date: 2004/02/28 11:31:24 $ */ public class ExtendedPatternFormatter extends PatternFormatter { private static final int TYPE_METHOD = MAX_TYPE + 1; private static final int TYPE_THREAD = MAX_TYPE + 2; private static final String TYPE_METHOD_STR = "method"; private static final String TYPE_THREAD_STR = "thread"; private int m_callStackOffset = 0; /** * Creation of a new extended pattern formatter. * @param format the format string */ public ExtendedPatternFormatter( final String format ) { this( format, 0 ); } /** * Creation of a new extended pattern formatter. * * @param format the format string * @param callStackOffset the offset */ public ExtendedPatternFormatter( final String format, final int callStackOffset ) { super( format ); m_callStackOffset = callStackOffset; } /** * Retrieve the type-id for a particular string. * * @param type the string * @return the type-id */ protected int getTypeIdFor( final String type ) { if( type.equalsIgnoreCase( TYPE_METHOD_STR ) ) { return TYPE_METHOD; } else if( type.equalsIgnoreCase( TYPE_THREAD_STR ) ) { return TYPE_THREAD; } else { return super.getTypeIdFor( type ); } } /** * Formats a single pattern run (can be extended in subclasses). * * @param event the log event * @param run the pattern run to format. * @return the formatted result. */ protected String formatPatternRun( final LogEvent event, final PatternRun run ) { switch( run.m_type ) { case TYPE_METHOD: return getMethod( event ); case TYPE_THREAD: return getThread( event ); default: return super.formatPatternRun( event, run ); } } /** * Utility method to format category. * * @param event the event * @return the formatted string */ private String getMethod( final LogEvent event ) { final ContextMap map = event.getContextMap(); if( null != map ) { final Object object = map.get( "method" ); if( null != object ) { return object.toString(); } } //Determine callee of user's class. If offset is 0, we need to find // Logger.class. If offset is 1, We need to find caller of Logger.class, etc. final Class clazz = StackIntrospector.getCallerClass( Logger.class, m_callStackOffset - 1 ); if( null == clazz ) { return "UnknownMethod"; } final String result = StackIntrospector.getCallerMethod( clazz ); if( null == result ) { return "UnknownMethod"; } return result; } /** * Utility thread to format category. * * @param event the even * @return the formatted string */ private String getThread( final LogEvent event ) { final ContextMap map = event.getContextMap(); if( null != map ) { final Object object = map.get( "thread" ); if( null != object ) { return object.toString(); } } return Thread.currentThread().getName(); } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/format/RawFormatter.java100644 0 0 2353 10036267317 23244 0ustar 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.log.format; import org.apache.log.LogEvent; /** * Basic formatter that just returns raw * message string and ignores remainder of LogEvent. * * @author Peter Donald */ public class RawFormatter implements Formatter { /** * Format log event into string. * * @param event the event * @return the formatted string */ public String format( final LogEvent event ) { final String message = event.getMessage(); if( null == message ) { return ""; } else { return message; } } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/format/PatternFormatter.java100644 0 0 50012 10036267317 24143 0ustar 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.log.format; import java.io.StringWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Stack; import org.apache.log.ContextMap; import org.apache.log.LogEvent; import org.apache.log.Priority; /** * This formater formats the LogEvents according to a input pattern * string. *

* The format of each pattern element can be * %[+|-][#[.#]]{field:subformat}. *

* *

A simple example of a typical PatternFormatter format would be: *


 *   %{time} %5.5{priority}[%-10.10{category}]: %{message}
 * 
*

* This would produce a line like: *


 *   1000928827905 DEBUG [     junit]: Sample message
 * 
*

* The format string specifies that the logger should first print the * time value of the log event without size restriction, then the * priority of the log event with a minimum and maximum size of 5, * then the category of the log event right justified with a minimum * and maximum size of 10, followed by the message of the log event * without any size restriction. *

* @author Avalon Development Team * @author Peter Donald * @author Sylvain Wallez * @author Leif Mortenson * @version CVS $Revision: 1.42 $ $Date: 2004/02/28 11:31:24 $ */ public class PatternFormatter implements Formatter { private static final int TYPE_TEXT = 1; private static final int TYPE_CATEGORY = 2; private static final int TYPE_CONTEXT = 3; private static final int TYPE_MESSAGE = 4; private static final int TYPE_TIME = 5; private static final int TYPE_RELATIVE_TIME = 6; private static final int TYPE_THROWABLE = 7; private static final int TYPE_PRIORITY = 8; private static final int TYPE_THREAD = 9; /** * The maximum value used for TYPEs. Subclasses can define their own TYPEs * starting at MAX_TYPE + 1. */ protected static final int MAX_TYPE = TYPE_PRIORITY; private static final String TYPE_CATEGORY_STR = "category"; private static final String TYPE_CONTEXT_STR = "context"; private static final String TYPE_MESSAGE_STR = "message"; private static final String TYPE_TIME_STR = "time"; private static final String TYPE_RELATIVE_TIME_STR = "rtime"; private static final String TYPE_THROWABLE_STR = "throwable"; private static final String TYPE_PRIORITY_STR = "priority"; private static final String TYPE_THREAD_STR = "thread"; private static final String SPACE_16 = " "; private static final String SPACE_8 = " "; private static final String SPACE_4 = " "; private static final String SPACE_2 = " "; private static final String SPACE_1 = " "; private static final String EOL = System.getProperty( "line.separator", "\n" ); protected static class PatternRun { public String m_data; public boolean m_rightJustify; public int m_minSize; public int m_maxSize; public int m_type; public String m_format; } private PatternRun m_formatSpecification[]; private SimpleDateFormat m_simpleDateFormat; private final Date m_date = new Date(); /** * Creation of a new patter formatter baseed on a supplied pattern. * @param pattern the patter */ public PatternFormatter( final String pattern ) { parse( pattern ); } /** * Extract and build a pattern from input string. * * @param stack the stack on which to place patterns * @param pattern the input string * @param index the start of pattern run * @return the number of characters in pattern run */ private int addPatternRun( final Stack stack, final char pattern[], int index ) { final PatternRun run = new PatternRun(); final int start = index++; //first check for a +|- sign if( '+' == pattern[ index ] ) { index++; } else if( '-' == pattern[ index ] ) { run.m_rightJustify = true; index++; } if( Character.isDigit( pattern[ index ] ) ) { int total = 0; while( Character.isDigit( pattern[ index ] ) ) { total = total * 10 + ( pattern[ index ] - '0' ); index++; } run.m_minSize = total; } //check for . sign indicating a maximum is to follow if( index < pattern.length && '.' == pattern[ index ] ) { index++; if( Character.isDigit( pattern[ index ] ) ) { int total = 0; while( Character.isDigit( pattern[ index ] ) ) { total = total * 10 + ( pattern[ index ] - '0' ); index++; } run.m_maxSize = total; } } if( index >= pattern.length || '{' != pattern[ index ] ) { throw new IllegalArgumentException( "Badly formed pattern at character " + index ); } int typeStart = index; while( index < pattern.length && pattern[ index ] != ':' && pattern[ index ] != '}' ) { index++; } int typeEnd = index - 1; final String type = new String( pattern, typeStart + 1, typeEnd - typeStart ); run.m_type = getTypeIdFor( type ); if( index < pattern.length && pattern[ index ] == ':' ) { index++; while( index < pattern.length && pattern[ index ] != '}' ) index++; final int length = index - typeEnd - 2; if( 0 != length ) { run.m_format = new String( pattern, typeEnd + 2, length ); } } if( index >= pattern.length || '}' != pattern[ index ] ) { throw new IllegalArgumentException( "Unterminated type in pattern at character " + index ); } index++; stack.push( run ); return index - start; } /** * Extract and build a text run from input string. * It does special handling of '\n' and '\t' replaceing * them with newline and tab. * * @param stack the stack on which to place runs * @param pattern the input string * @param index the start of the text run * @return the number of characters in run */ private int addTextRun( final Stack stack, final char pattern[], int index ) { final PatternRun run = new PatternRun(); final int start = index; boolean escapeMode = false; if( '%' == pattern[ index ] ) { index++; } final StringBuffer sb = new StringBuffer(); while( index < pattern.length && pattern[ index ] != '%' ) { if( escapeMode ) { if( 'n' == pattern[ index ] ) { sb.append( EOL ); } else if( 't' == pattern[ index ] ) { sb.append( '\t' ); } else { sb.append( pattern[ index ] ); } escapeMode = false; } else if( '\\' == pattern[ index ] ) { escapeMode = true; } else { sb.append( pattern[ index ] ); } index++; } run.m_data = sb.toString(); run.m_type = TYPE_TEXT; stack.push( run ); return index - start; } /** * Utility to append a string to buffer given certain constraints. * * @param sb the StringBuffer * @param minSize the minimum size of output (0 to ignore) * @param maxSize the maximum size of output (0 to ignore) * @param rightJustify true if the string is to be right justified in it's box. * @param output the input string */ private void append( final StringBuffer sb, final int minSize, final int maxSize, final boolean rightJustify, final String output ) { final int size = output.length(); if( size < minSize ) { //assert( minSize > 0 ); if( rightJustify ) { appendWhiteSpace( sb, minSize - size ); sb.append( output ); } else { sb.append( output ); appendWhiteSpace( sb, minSize - size ); } } else if( maxSize > 0 && maxSize < size ) { if( rightJustify ) { sb.append( output.substring( size - maxSize ) ); } else { sb.append( output.substring( 0, maxSize ) ); } } else { sb.append( output ); } } /** * Append a certain number of whitespace characters to a StringBuffer. * * @param sb the StringBuffer * @param length the number of spaces to append */ private void appendWhiteSpace( final StringBuffer sb, int length ) { while( length >= 16 ) { sb.append( SPACE_16 ); length -= 16; } if( length >= 8 ) { sb.append( SPACE_8 ); length -= 8; } if( length >= 4 ) { sb.append( SPACE_4 ); length -= 4; } if( length >= 2 ) { sb.append( SPACE_2 ); length -= 2; } if( length >= 1 ) { sb.append( SPACE_1 ); length -= 1; } } /** * Format the event according to the pattern. * * @param event the event * @return the formatted output */ public String format( final LogEvent event ) { final StringBuffer sb = new StringBuffer(); for( int i = 0; i < m_formatSpecification.length; i++ ) { final PatternRun run = m_formatSpecification[ i ]; //treat text differently as it doesn't need min/max padding if( run.m_type == TYPE_TEXT ) { sb.append( run.m_data ); } else { final String data = formatPatternRun( event, run ); if( null != data ) { append( sb, run.m_minSize, run.m_maxSize, run.m_rightJustify, data ); } } } return sb.toString(); } /** * Formats a single pattern run (can be extended in subclasses). * * @param run the pattern run to format. * @return the formatted result. */ protected String formatPatternRun( final LogEvent event, final PatternRun run ) { switch( run.m_type ) { case TYPE_RELATIVE_TIME: return getRTime( event.getRelativeTime(), run.m_format ); case TYPE_TIME: return getTime( event.getTime(), run.m_format ); case TYPE_THROWABLE: return getStackTrace( event.getThrowable(), run.m_format ); case TYPE_MESSAGE: return getMessage( event.getMessage(), run.m_format ); case TYPE_CATEGORY: return getCategory( event.getCategory(), run.m_format ); case TYPE_PRIORITY: return getPriority( event.getPriority(), run.m_format ); case TYPE_CONTEXT: return getContextMap( event.getContextMap(), run.m_format ); case TYPE_THREAD: return getThread( run.m_format ); default: throw new IllegalStateException( "Unknown Pattern specification." + run.m_type ); } } /** * Utility method to format category. * * @param category the category string * @param format ancilliary format parameter - allowed to be null * @return the formatted string */ protected String getCategory( final String category, final String format ) { return category; } /** * Get formatted priority string. */ protected String getPriority( final Priority priority, final String format ) { return priority.getName(); } /** * Get formatted thread string. */ protected String getThread( final String format ) { return Thread.currentThread().getName(); } /** * Utility method to format context map. * * @param map the context map * @param format ancilliary format parameter - allowed to be null * @return the formatted string */ protected String getContextMap( final ContextMap map, final String format ) { if( null == map ) return ""; return map.get( format, "" ).toString(); } /** * Utility method to format message. * * @param message the message string * @param format ancilliary format parameter - allowed to be null * @return the formatted string */ protected String getMessage( final String message, final String format ) { return message; } /** * Utility method to format stack trace. * * @param throwable the throwable instance * @param format ancilliary format parameter - allowed to be null * @return the formatted string */ protected String getStackTrace( final Throwable throwable, final String format ) { if( null == throwable ) return ""; final StringWriter sw = new StringWriter(); throwable.printStackTrace( new java.io.PrintWriter( sw ) ); return sw.toString(); } /** * Utility method to format relative time. * * @param time the time * @param format ancilliary format parameter - allowed to be null * @return the formatted string */ protected String getRTime( final long time, final String format ) { return getTime( time, format ); } /** * Utility method to format time. * * @param time the time * @param format ancilliary format parameter - allowed to be null * @return the formatted string */ protected String getTime( final long time, final String format ) { if( null == format ) { return Long.toString( time ); } else { synchronized( m_date ) { if( null == m_simpleDateFormat ) { m_simpleDateFormat = new SimpleDateFormat( format ); } m_date.setTime( time ); return m_simpleDateFormat.format( m_date ); } } } /** * Retrieve the type-id for a particular string. * * @param type the string * @return the type-id */ protected int getTypeIdFor( final String type ) { if( type.equalsIgnoreCase( TYPE_CATEGORY_STR ) ) { return TYPE_CATEGORY; } else if( type.equalsIgnoreCase( TYPE_CONTEXT_STR ) ) { return TYPE_CONTEXT; } else if( type.equalsIgnoreCase( TYPE_MESSAGE_STR ) ) { return TYPE_MESSAGE; } else if( type.equalsIgnoreCase( TYPE_PRIORITY_STR ) ) { return TYPE_PRIORITY; } else if( type.equalsIgnoreCase( TYPE_TIME_STR ) ) { return TYPE_TIME; } else if( type.equalsIgnoreCase( TYPE_RELATIVE_TIME_STR ) ) { return TYPE_RELATIVE_TIME; } else if( type.equalsIgnoreCase( TYPE_THREAD_STR ) ) { return TYPE_THREAD; } else if( type.equalsIgnoreCase( TYPE_THROWABLE_STR ) ) { return TYPE_THROWABLE; } else { throw new IllegalArgumentException( "Unknown Type in pattern - " + type ); } } /** * Parse the input pattern and build internal data structures. * * @param patternString the pattern */ protected final void parse( final String patternString ) { final Stack stack = new Stack(); final int size = patternString.length(); final char pattern[] = new char[ size ]; int index = 0; patternString.getChars( 0, size, pattern, 0 ); while( index < size ) { if( pattern[ index ] == '%' && !( index != size - 1 && pattern[ index + 1 ] == '%' ) ) { index += addPatternRun( stack, pattern, index ); } else { index += addTextRun( stack, pattern, index ); } } final int elementCount = stack.size(); m_formatSpecification = new PatternRun[ elementCount ]; for( int i = 0; i < elementCount; i++ ) { m_formatSpecification[ i ] = (PatternRun)stack.elementAt( i ); } } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/Priority.java100644 0 0 12117 10036267317 21177 0ustar 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.log; import java.io.Serializable; /** * Class representing and holding constants for priority. * * @author Peter Donald */ public final class Priority implements Serializable { /** * Developer orientated messages, usually used during development of product. */ public static final Priority DEBUG = new Priority( "DEBUG", 5 ); /** * Useful information messages such as state changes, client connection, user login etc. */ public static final Priority INFO = new Priority( "INFO", 10 ); /** * A problem or conflict has occurred but it may be recoverable, then * again it could be the start of the system failing. */ public static final Priority WARN = new Priority( "WARN", 15 ); /** * A problem has occurred but it is not fatal. The system will still function. */ public static final Priority ERROR = new Priority( "ERROR", 20 ); /** * Something caused whole system to fail. This indicates that an administrator * should restart the system and try to fix the problem that caused the failure. */ public static final Priority FATAL_ERROR = new Priority( "FATAL_ERROR", 25 ); /** * Do not log anything. */ public static final Priority NONE = new Priority( "NONE", Integer.MAX_VALUE ); private final String m_name; private final int m_priority; /** * Retrieve a Priority object for the name parameter. * * @param priority the priority name * @return the Priority for name */ public static Priority getPriorityForName( final String priority ) { if( Priority.DEBUG.getName().equals( priority ) ) { return Priority.DEBUG; } else if( Priority.INFO.getName().equals( priority ) ) { return Priority.INFO; } else if( Priority.WARN.getName().equals( priority ) ) { return Priority.WARN; } else if( Priority.ERROR.getName().equals( priority ) ) { return Priority.ERROR; } else if( Priority.FATAL_ERROR.getName().equals( priority ) ) { return Priority.FATAL_ERROR; } else if( Priority.NONE.getName().equals( priority ) ) { return Priority.NONE; } else { return Priority.DEBUG; } } /** * Private Constructor to block instantiation outside class. * * @param name the string name of priority * @param priority the numerical code of priority */ private Priority( final String name, final int priority ) { if( null == name ) { throw new NullPointerException( "name" ); } m_name = name; m_priority = priority; } /** * Overidden string to display Priority in human readable form. * * @return the string describing priority */ public String toString() { return "Priority[" + getName() + "/" + getValue() + "]"; } /** * Get numerical value associated with priority. * * @return the numerical value */ public int getValue() { return m_priority; } /** * Get name of priority. * * @return the priorities name */ public String getName() { return m_name; } /** * Test whether this priority is greater than other priority. * * @param other the other Priority * @return TRUE if the priority is greater else FALSE */ public boolean isGreater( final Priority other ) { return m_priority > other.getValue(); } /** * Test whether this priority is lower than other priority. * * @param other the other Priority * @return TRUE if the priority is lower else FALSE */ public boolean isLower( final Priority other ) { return m_priority < other.getValue(); } /** * Test whether this priority is lower or equal to other priority. * * @param other the other Priority * @return TRUE if the priority is lower or equal else FALSE */ public boolean isLowerOrEqual( final Priority other ) { return m_priority <= other.getValue(); } /** * Helper method that replaces deserialized object with correct singleton. * * @return the singleton version of object */ private Object readResolve() { return getPriorityForName( m_name ); } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/Hierarchy.java100644 0 0 21076 10036267317 21300 0ustar 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.log; import org.apache.log.format.PatternFormatter; import org.apache.log.output.io.StreamTarget; import org.apache.log.util.DefaultErrorHandler; import org.apache.log.util.LoggerListener; /** * This class encapsulates a basic independent log hierarchy. * The hierarchy is essentially a safe wrapper around root logger. * * @author Avalon Development Team * @author Peter Donald */ public class Hierarchy { ///Format of default formatter public 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}"; ///The instance of default hierarchy private static final Hierarchy c_hierarchy = new Hierarchy(); ///Error Handler associated with hierarchy private ErrorHandler m_errorHandler; ///The root logger which contains all Loggers in this hierarchy private Logger m_rootLogger; ///LoggerListener associated with hierarchy private LoggerListener m_loggerListener; /** * Retrieve the default hierarchy. * *

In most cases the default LogHierarchy is the only * one used in an application. However when security is * a concern or multiple independent applications will * be running in same JVM it is advantageous to create * new Hierarchies rather than reuse default.

* * @return the default Hierarchy */ public static Hierarchy getDefaultHierarchy() { return c_hierarchy; } /** * Create a hierarchy object. * The default LogTarget writes to stdout. */ public Hierarchy() { m_errorHandler = new DefaultErrorHandler(); m_rootLogger = new Logger( new InnerErrorHandler(), new InnerLoggerListener(), "", null, null ); //Setup default output target to print to console final PatternFormatter formatter = new PatternFormatter( DEFAULT_FORMAT ); final StreamTarget target = new StreamTarget( System.out, formatter ); setDefaultLogTarget( target ); } /** * Set the default log target for hierarchy. * This is the target inherited by loggers if no other target is specified. * * @param target the default target */ public void setDefaultLogTarget( final LogTarget target ) { if( null == target ) { throw new IllegalArgumentException( "Can not set DefaultLogTarget to null" ); } final LogTarget[] targets = new LogTarget[]{target}; getRootLogger().setLogTargets( targets ); } /** * Set the default log targets for this hierarchy. * These are the targets inherited by loggers if no other targets are specified * * @param targets the default targets */ public void setDefaultLogTargets( final LogTarget[] targets ) { if( null == targets || 0 == targets.length ) { throw new IllegalArgumentException( "Can not set DefaultLogTargets to null" ); } for( int i = 0; i < targets.length; i++ ) { if( null == targets[ i ] ) { final String message = "Can not set DefaultLogTarget element to null"; throw new IllegalArgumentException( message ); } } getRootLogger().setLogTargets( targets ); } /** * Set the default priority for hierarchy. * This is the priority inherited by loggers if no other priority is specified. * * @param priority the default priority */ public void setDefaultPriority( final Priority priority ) { if( null == priority ) { final String message = "Can not set default Hierarchy Priority to null"; throw new IllegalArgumentException( message ); } getRootLogger().setPriority( priority ); } /** * Set the ErrorHandler associated with hierarchy. * * @param errorHandler the ErrorHandler */ public void setErrorHandler( final ErrorHandler errorHandler ) { if( null == errorHandler ) { final String message = "Can not set default Hierarchy ErrorHandler to null"; throw new IllegalArgumentException( message ); } m_errorHandler = errorHandler; } /** * Set the LoggerListener associated with hierarchy. This is a * unicast listener, so only one LoggerListener is allowed. * * @param loggerListener the LoggerListener * * @throws UnsupportedOperationException if no more LoggerListeners are * permitted. */ public synchronized void addLoggerListener( final LoggerListener loggerListener ) { if( null == loggerListener ) { throw new NullPointerException( "loggerListener" ); } if( null == m_loggerListener ) { m_loggerListener = loggerListener; } else { final String message = "LoggerListener already set on a unicast event notifier"; throw new UnsupportedOperationException( message ); } } /** * Remove the LoggerListener associated with hierarchy. Perform this * step before adding a new one if you want to change it. * * @param loggerListener the LoggerListener */ public synchronized void removeLoggerListener( final LoggerListener loggerListener ) { if( null == loggerListener ) { throw new NullPointerException( "loggerListener" ); } if( null != m_loggerListener && m_loggerListener == loggerListener ) ; { m_loggerListener = null; } } /** * Retrieve a logger for named category. * * @param category the context * @return the Logger */ public Logger getLoggerFor( final String category ) { return getRootLogger().getChildLogger( category ); } /** * Notify logger listener (if any) that a new logger was created. * * @param category the category of new logger * @param logger the logger */ private synchronized void notifyLoggerCreated( final String category, final Logger logger ) { if( null != m_loggerListener ) { m_loggerListener.loggerCreated( category, logger ); } } /** * Inner class to redirect to hierarchys real LoggerListener if any. * Used so that all the loggers will not have to be updated * when LoggerListener changes. */ private class InnerLoggerListener extends LoggerListener { /** * Notify listener that a logger was created. * * @param category the category of logger * @param logger the logger object */ public void loggerCreated( final String category, final Logger logger ) { notifyLoggerCreated( category, logger ); } } private class InnerErrorHandler implements ErrorHandler { /** * Log an unrecoverable error. * * @param message the error message * @param throwable the exception associated with error (may be null) * @param event the LogEvent that caused error, if any (may be null) */ public void error( final String message, final Throwable throwable, final LogEvent event ) { m_errorHandler.error( message, throwable, event ); } } /** * Utility method to retrieve logger for hierarchy. * This method is intended for use by sub-classes * which can take responsibility for manipulating * Logger directly. * * @return the Logger */ public final Logger getRootLogger() { return m_rootLogger; } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/LogTarget.java100644 0 0 2455 10036267317 21232 0ustar 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.log; /** * LogTarget is a class to encapsulate outputting LogEvent's. * This provides the base for all output and filter targets. * * Warning: If performance becomes a problem then this * interface will be rewritten as a abstract class. * * @author Peter Donald */ public interface LogTarget { /** * Process a log event. * In NO case should this method ever throw an exception/error. * The reason is that logging is usually added for debugging/auditing * purposes and it would be unnaceptable to have your debugging * code cause more errors. * * @param event the event */ void processEvent( LogEvent event ); } avalon-logkit-2.0.dev-0/src/java/org/apache/log/package.html100644 0 0 372 10036267317 20734 0ustar 0 0 Avalon LogKit is the logging framework used throughout the Avalon project. Excalibur, Cornerstone, and Phoenix all assume the use of this project. See the LogKit whitepaper for further details on how to use the toolkit. avalon-logkit-2.0.dev-0/src/java/org/apache/log/Logger.java100644 0 0 47616 10036267317 20611 0ustar 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.log; import org.apache.log.util.LoggerListener; /** * The object interacted with by client objects to perform logging. * * @author Avalon Development Team * @author Peter Donald */ public class Logger { private static final Logger[] EMPTY_SET = new Logger[ 0 ]; /** * Separator character use to separate different categories */ public static final char CATEGORY_SEPARATOR = '.'; // The ErrorHandler associated with Logger private final ErrorHandler m_errorHandler; ///The ErrorHandler associated with Logger private final LoggerListener m_loggerListener; ///Logger to inherit logtargets and priorities from private final Logger m_parent; ///the fully qualified name of category private final String m_category; ///The list of child loggers associated with this logger private Logger[] m_children; ///The log-targets this logger writes to private LogTarget[] m_logTargets; ///Indicate that logTargets were set with setLogTargets() rather than inherited private boolean m_logTargetsForceSet; ///The priority threshold associated with logger private Priority m_priority; ///Indicate that priority was set with setPriority() rather than inherited private boolean m_priorityForceSet; /** * True means LogEvents will be sent to parents LogTargets * aswell as the ones set for this Logger. */ private boolean m_additivity; /** * Protected constructor for use inside the logging toolkit. * You should not be using this constructor directly. * * @param errorHandler the ErrorHandler logger uses to log errors * @param category the fully qualified name of category * @param logTargets the LogTargets associated with logger * @param parent the parent logger (used for inheriting from) */ Logger( final ErrorHandler errorHandler, final LoggerListener loggerListener, final String category, final LogTarget[] logTargets, final Logger parent ) { m_errorHandler = errorHandler; m_loggerListener = loggerListener; m_category = category; m_logTargets = logTargets; m_parent = parent; if( null == m_logTargets ) { unsetLogTargets(); } unsetPriority(); } /** * Determine if messages of priority DEBUG will be logged. * * @return true if DEBUG messages will be logged */ public final boolean isDebugEnabled() { return m_priority.isLowerOrEqual( Priority.DEBUG ); } /** * Log a debug priority event. * * @param message the message * @param throwable the throwable */ public final void debug( final String message, final Throwable throwable ) { if( isDebugEnabled() ) { output( Priority.DEBUG, message, throwable ); } } /** * Log a debug priority event. * * @param message the message */ public final void debug( final String message ) { if( isDebugEnabled() ) { output( Priority.DEBUG, message, null ); } } /** * Determine if messages of priority INFO will be logged. * * @return true if INFO messages will be logged */ public final boolean isInfoEnabled() { return m_priority.isLowerOrEqual( Priority.INFO ); } /** * Log a info priority event. * * @param message the message * @param throwable the throwable */ public final void info( final String message, final Throwable throwable ) { if( isInfoEnabled() ) { output( Priority.INFO, message, throwable ); } } /** * Log a info priority event. * * @param message the message */ public final void info( final String message ) { if( isInfoEnabled() ) { output( Priority.INFO, message, null ); } } /** * Determine if messages of priority WARN will be logged. * * @return true if WARN messages will be logged */ public final boolean isWarnEnabled() { return m_priority.isLowerOrEqual( Priority.WARN ); } /** * Log a warn priority event. * * @param message the message * @param throwable the throwable */ public final void warn( final String message, final Throwable throwable ) { if( isWarnEnabled() ) { output( Priority.WARN, message, throwable ); } } /** * Log a warn priority event. * * @param message the message */ public final void warn( final String message ) { if( isWarnEnabled() ) { output( Priority.WARN, message, null ); } } /** * Determine if messages of priority ERROR will be logged. * * @return true if ERROR messages will be logged */ public final boolean isErrorEnabled() { return m_priority.isLowerOrEqual( Priority.ERROR ); } /** * Log a error priority event. * * @param message the message * @param throwable the throwable */ public final void error( final String message, final Throwable throwable ) { if( isErrorEnabled() ) { output( Priority.ERROR, message, throwable ); } } /** * Log a error priority event. * * @param message the message */ public final void error( final String message ) { if( isErrorEnabled() ) { output( Priority.ERROR, message, null ); } } /** * Determine if messages of priority FATAL_ERROR will be logged. * * @return true if FATAL_ERROR messages will be logged */ public final boolean isFatalErrorEnabled() { return m_priority.isLowerOrEqual( Priority.FATAL_ERROR ); } /** * Log a fatalError priority event. * * @param message the message * @param throwable the throwable */ public final void fatalError( final String message, final Throwable throwable ) { if( isFatalErrorEnabled() ) { output( Priority.FATAL_ERROR, message, throwable ); } } /** * Log a fatalError priority event. * * @param message the message */ public final void fatalError( final String message ) { if( isFatalErrorEnabled() ) { output( Priority.FATAL_ERROR, message, null ); } } /** * Make this logger additive. I.e. Send all log events to parent * loggers LogTargets regardless of whether or not the * LogTargets have been overidden. * * This is derived from Log4js notion of Additivity. * * @param additivity true to make logger additive, false otherwise */ public final void setAdditivity( final boolean additivity ) { m_additivity = additivity; } /** * Determine if messages of priority �will be logged. * @param priority the priority * @return true if messages will be logged */ public final boolean isPriorityEnabled( final Priority priority ) { return m_priority.isLowerOrEqual( priority ); } /** * Log a event at specific priority with a certain message and throwable. * * @param priority the priority * @param message the message * @param throwable the throwable */ public final void log( final Priority priority, final String message, final Throwable throwable ) { if( m_priority.isLowerOrEqual( priority ) ) { output( priority, message, throwable ); } } /** * Log a event at specific priority with a certain message. * * @param priority the priority * @param message the message */ public final void log( final Priority priority, final String message ) { if( m_priority.isLowerOrEqual( priority ) ) { log( priority, message, null ); } } /** * Set the priority for this logger. * * @param priority the priority */ public synchronized void setPriority( final Priority priority ) { m_priority = priority; m_priorityForceSet = true; resetChildPriorities( false ); } /** * Unset the priority of Logger. * (Thus it will use it's parent's priority or DEBUG if no parent. */ public synchronized void unsetPriority() { unsetPriority( false ); } /** * Unset the priority of Logger. * (Thus it will use it's parent's priority or DEBUG if no parent. * If recursive is true unset priorities of all child loggers. * * @param recursive true to unset priority of all child loggers */ public synchronized void unsetPriority( final boolean recursive ) { if( null != m_parent ) { m_priority = m_parent.m_priority; } else { m_priority = Priority.DEBUG; } m_priorityForceSet = false; resetChildPriorities( recursive ); } /** * Set the log targets for this logger. * * @param logTargets the Log Targets */ public synchronized void setLogTargets( final LogTarget[] logTargets ) { if( null != logTargets ) { //Make sure that the array passed in does not have any //nulls in it before we actually do the assignment for( int i = 0; i < logTargets.length; i++ ) { if( null == logTargets[ i ] ) { final String message = "logTargets[ " + i + " ]"; throw new NullPointerException( message ); } } } m_logTargets = logTargets; setupErrorHandlers(); m_logTargetsForceSet = true; resetChildLogTargets( false ); } /** * Unset the logtargets for this logger. * This logger (and thus all child loggers who don't specify logtargets) will * inherit from the parents LogTargets. */ public synchronized void unsetLogTargets() { unsetLogTargets( false ); } /** * Unset the logtargets for this logger and all child loggers if recursive is set. * The loggers unset (and all child loggers who don't specify logtargets) will * inherit from the parents LogTargets. * @param recursive the recursion policy */ public synchronized void unsetLogTargets( final boolean recursive ) { if( null != m_parent ) { m_logTargets = m_parent.safeGetLogTargets(); } else { m_logTargets = null; } m_logTargetsForceSet = false; resetChildLogTargets( recursive ); } /** * Get all the child Loggers of current logger. * * @return the child loggers */ public synchronized Logger[] getChildren() { if( null == m_children ) { return EMPTY_SET; } final Logger[] children = new Logger[ m_children.length ]; for( int i = 0; i < children.length; i++ ) { children[ i ] = m_children[ i ]; } return children; } /** * Create a new child logger. * The category of child logger is [current-category].subcategory * * @param subCategory the subcategory of this logger * @return the new logger * @exception IllegalArgumentException if subCategory has an empty element name */ public synchronized Logger getChildLogger( final String subCategory ) throws IllegalArgumentException { final int end = subCategory.indexOf( CATEGORY_SEPARATOR ); String nextCategory = null; String remainder = null; if( -1 == end ) { nextCategory = subCategory; } else { if( end == 0 ) { throw new IllegalArgumentException( "Logger categories MUST not have empty elements" ); } nextCategory = subCategory.substring( 0, end ); remainder = subCategory.substring( end + 1 ); } //Get FQN for category String category = null; if( m_category.equals( "" ) ) { category = nextCategory; } else { category = m_category + CATEGORY_SEPARATOR + nextCategory; } //Check existing children to see if they //contain next Logger for step in category if( null != m_children ) { for( int i = 0; i < m_children.length; i++ ) { if( m_children[ i ].m_category.equals( category ) ) { if( null == remainder ) { return m_children[ i ]; } else { return m_children[ i ].getChildLogger( remainder ); } } } } //Create new logger final Logger child = new Logger( m_errorHandler, m_loggerListener, category, null, this ); if( m_additivity ) { child.setAdditivity( true ); } m_loggerListener.loggerCreated( child.m_category, child ); //Add new logger to child list if( null == m_children ) { m_children = new Logger[]{child}; } else { final Logger[] children = new Logger[ m_children.length + 1 ]; System.arraycopy( m_children, 0, children, 0, m_children.length ); children[ m_children.length ] = child; m_children = children; } if( null == remainder ) { return child; } else { return child.getChildLogger( remainder ); } } /** * Internal method to do actual outputting. * * @param priority the priority * @param message the message * @param throwable the throwable */ private final void output( final Priority priority, final String message, final Throwable throwable ) { final LogEvent event = new LogEvent(); event.setCategory( m_category ); event.setContextMap( ContextMap.getCurrentContext( false ) ); if( null != message ) { event.setMessage( message ); } else { event.setMessage( "" ); } event.setThrowable( throwable ); event.setPriority( priority ); //this next line can kill performance. It may be wise to //disable it sometimes and use a more granular approach event.setTime( System.currentTimeMillis() ); output( event ); } private final void output( final LogEvent event ) { //cache a copy of targets for thread safety //It is now possible for another thread //to replace m_logTargets final LogTarget[] targets = m_logTargets; if( null == targets ) { final String message = "LogTarget is null for category '" + m_category + "'"; m_errorHandler.error( message, null, event ); } else if( !m_additivity ) { fireEvent( event, targets ); } else { //If log targets were not inherited, additivity is true //then fire an event to local targets if( m_logTargetsForceSet ) { fireEvent( event, targets ); } //if we have a parent Logger then send log event to parent if( null != m_parent ) { m_parent.output( event ); } } } private final void fireEvent( final LogEvent event, final LogTarget[] targets ) { for( int i = 0; i < targets.length; i++ ) { //No need to clone array as addition of a log-target //will result in changin whole array targets[ i ].processEvent( event ); } } /** * Update priority of children if any. */ private synchronized void resetChildPriorities( final boolean recursive ) { if( null == m_children ) { return; } final Logger[] children = m_children; for( int i = 0; i < children.length; i++ ) { children[ i ].resetPriority( recursive ); } } /** * Update priority of this Logger. * If this loggers priority was manually set then ignore * otherwise get parents priority and update all children's priority. * */ private synchronized void resetPriority( final boolean recursive ) { if( recursive ) { m_priorityForceSet = false; } else if( m_priorityForceSet ) { return; } m_priority = m_parent.m_priority; resetChildPriorities( recursive ); } /** * Retrieve logtarget array contained in logger. * This method is provided so that child Loggers can access a * copy of parents LogTargets. * * @return the array of LogTargets */ private synchronized LogTarget[] safeGetLogTargets() { if( null == m_logTargets ) { if( null == m_parent ) { return new LogTarget[ 0 ]; } else { return m_parent.safeGetLogTargets(); } } else { final LogTarget[] logTargets = new LogTarget[ m_logTargets.length ]; for( int i = 0; i < logTargets.length; i++ ) { logTargets[ i ] = m_logTargets[ i ]; } return logTargets; } } /** * Update logTargets of children if any. */ private synchronized void resetChildLogTargets( final boolean recursive ) { if( null == m_children ) { return; } for( int i = 0; i < m_children.length; i++ ) { m_children[ i ].resetLogTargets( recursive ); } } /** * Set ErrorHandlers of LogTargets if necessary. */ private synchronized void setupErrorHandlers() { if( null == m_logTargets ) { return; } for( int i = 0; i < m_logTargets.length; i++ ) { final LogTarget target = m_logTargets[ i ]; if( target instanceof ErrorAware ) { ( (ErrorAware)target ).setErrorHandler( m_errorHandler ); } } } /** * Update logTarget of this Logger. * If this loggers logTarget was manually set then ignore * otherwise get parents logTarget and update all children's logTarget. * */ private synchronized void resetLogTargets( final boolean recursive ) { if( recursive ) { m_logTargetsForceSet = false; } else if( m_logTargetsForceSet ) { return; } m_logTargets = m_parent.safeGetLogTargets(); resetChildLogTargets( recursive ); } } avalon-logkit-2.0.dev-0/src/java/org/apache/log/ErrorAware.java100644 0 0 1742 10036267317 21411 0ustar 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.log; /** * Interface implemented by components that wish to * delegate ErrorHandling to an ErrorHandler. * * @author Peter Donald */ public interface ErrorAware { /** * Provide component with ErrorHandler. * * @param errorHandler the errorHandler */ void setErrorHandler( ErrorHandler errorHandler ); } avalon-logkit-2.0.dev-0/src/java/org/apache/log/ContextMap.java100644 0 0 14306 10036267317 21442 0ustar 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.log; import java.io.Serializable; import java.util.Hashtable; /** * The ContextMap contains non-hierarchical context information * relevant to a particular LogEvent. It may include information * such as; * * * The context is bound to a thread (and inherited by sub-threads) but * it can also be added to by LogTargets. * * @author Avalon Development Team * @author Peter Donald */ public final class ContextMap implements Serializable { ///Thread local for holding instance of map associated with current thread private static final ThreadLocal c_localContext = new InheritableThreadLocal(); private final ContextMap m_parent; ///Container to hold map of elements private Hashtable m_map = new Hashtable(); ///Flag indicating whether this map should be readonly private transient boolean m_readOnly; /** * Get the Current ContextMap. * This method returns a ContextMap associated with current thread. If the * thread doesn't have a ContextMap associated with it then a new * ContextMap is created. * * @return the current ContextMap */ public static final ContextMap getCurrentContext() { return getCurrentContext( true ); } /** * Get the Current ContextMap. * This method returns a ContextMap associated with current thread. * If the thread doesn't have a ContextMap associated with it and * autocreate is true then a new ContextMap is created. * * @param autocreate true if a ContextMap is to be created if it doesn't exist * @return the current ContextMap */ public static final ContextMap getCurrentContext( final boolean autocreate ) { //Check security permission here??? ContextMap context = (ContextMap)c_localContext.get(); if( null == context && autocreate ) { context = new ContextMap(); c_localContext.set( context ); } return context; } /** * Bind a particular ContextMap to current thread. * * @param context the context map (may be null) */ public static final void bind( final ContextMap context ) { //Check security permission here?? c_localContext.set( context ); } /** * Default constructor. */ public ContextMap() { this( null ); } /** * Constructor that sets parent contextMap. * * @param parent the parent ContextMap */ public ContextMap( final ContextMap parent ) { m_parent = parent; } /** * Make the context read-only. * This makes it safe to allow untrusted code reference * to ContextMap. */ public void makeReadOnly() { m_readOnly = true; } /** * Determine if context is read-only. * * @return true if Context is read only, false otherwise */ public boolean isReadOnly() { return m_readOnly; } /** * Empty the context map. * */ public void clear() { checkReadable(); m_map.clear(); } /** * Get an entry from the context. * * @param key the key to map * @param defaultObject a default object to return if key does not exist * @return the object in context */ public Object get( final String key, final Object defaultObject ) { final Object object = get( key ); if( null != object ) { return object; } else { return defaultObject; } } /** * Get an entry from the context. * * @param key the key to map * @return the object in context or null if none with specified key */ public Object get( final String key ) { if( key == null ) return null; final Object result = m_map.get( key ); if( null == result && null != m_parent ) { return m_parent.get( key ); } return result; } /** * Set a value in context * * @param key the key * @param value the value (may be null) */ public void set( final String key, final Object value ) { checkReadable(); if( value == null ) { m_map.remove( key ); } else { m_map.put( key, value ); } } /** * Retrieve keys of entries into context map. * * @return the keys of items in context */ /* public String[] getKeys() { return (String[])m_map.keySet().toArray( new String[ 0 ] ); } */ /** * Get the number of contexts in map. * * @return the number of contexts in map */ public int getSize() { return m_map.size(); } /** * Helper method that sets context to read-only after de-serialization. * * @return the corrected object version */ private Object readResolve() { makeReadOnly(); return this; } /** * Utility method to verify that Context is read-only. */ private void checkReadable() { if( isReadOnly() ) { throw new IllegalStateException( "ContextMap is read only and can not be modified" ); } } } avalon-logkit-2.0.dev-0/src/test/org/apache/log/format/test/FormatterTestCase.java100644 0 0 40526 10036267317 25267 0ustar 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.log.format.test; import junit.framework.TestCase; import org.apache.log.ContextMap; import org.apache.log.LogEvent; import org.apache.log.Priority; 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; /** * Test suite for the formatters. * TODO: Incorporate testing for ContextMap * * @author Peter Donald */ public final class FormatterTestCase extends TestCase { private static String EOL = System.getProperty( "line.separator", "\n" ); private static String M1 = "Message1"; private static String M2 = "Message2Message2"; private static String M3 = "Message3Message3Message3"; private static String C1 = "Category1"; private static String C2 = "Category2Category2"; private static String C3 = "Category3Category3Category3"; private static long T1 = 0; private static long T2 = 1; private static long T3 = 2; private static Priority P1 = Priority.FATAL_ERROR; private static Priority P2 = Priority.ERROR; private static Priority P3 = Priority.WARN; private static boolean mapsConfigured; private static ContextMap CM1 = new ContextMap(); private static ContextMap CM2 = new ContextMap(); private static LogEvent E1 = createEvent( C1, M1, null, T1, P1, CM1 ); private static LogEvent E2 = createEvent( C2, M2, null, T2, P2, CM2 ); private static LogEvent E3 = createEvent( C3, M3, null, T3, P3, null ); private static String E1_XML = "" + EOL + " " + EOL + " " + P1.getName() + "" + EOL + " " + C1 + "" + EOL + " " + EOL + "" + EOL; private static String E2_XML = "" + EOL + " " + EOL + " " + P2.getName() + "" + EOL + " " + C2 + "" + EOL + " " + EOL + "" + EOL; private static String E3_XML = "" + EOL + " " + EOL + " " + P3.getName() + "" + EOL + " " + C3 + "" + EOL + " " + EOL + "" + EOL; private static int FACILITY_ID = 9 << 3; //cron private static String FACILITY_NAME = "cron"; //cron private static String E1_SYSLOG = "<" + ( 2 | FACILITY_ID ) + "> " + M1; private static String E2_SYSLOG = "<" + ( 3 | FACILITY_ID ) + "> " + M2; private static String E3_SYSLOG = "<" + ( 4 | FACILITY_ID ) + "> " + M3; private static String E1_SYSLOG_WB = "<" + ( 2 | FACILITY_ID ) + "> " + FACILITY_NAME + ": " + M1; private static String E2_SYSLOG_WB = "<" + ( 3 | FACILITY_ID ) + "> " + FACILITY_NAME + ": " + M2; private static String E3_SYSLOG_WB = "<" + ( 4 | FACILITY_ID ) + "> " + FACILITY_NAME + ": " + M3; private static String PATTERN1 = "[%8.8{category}]: %{message}" + EOL; private static String E1_PATTERN1 = "[Category]: " + M1 + EOL; private static String E2_PATTERN1 = "[Category]: " + M2 + EOL; private static String E3_PATTERN1 = "[Category]: " + M3 + EOL; private static String PATTERN2 = "[%10.{category}]: %{message}" + EOL; private static String E1_PATTERN2 = "[" + C1 + " ]: " + M1 + EOL; private static String E2_PATTERN2 = "[" + C2 + "]: " + M2 + EOL; private static String E3_PATTERN2 = "[" + C3 + "]: " + M3 + EOL; private static String PATTERN3 = "[%.10{category}]: %{message}" + EOL; private static String E1_PATTERN3 = "[" + C1 + "]: " + M1 + EOL; private static String E2_PATTERN3 = "[Category2C]: " + M2 + EOL; private static String E3_PATTERN3 = "[Category3C]: " + M3 + EOL; private static String PATTERN4 = "[%+10.{category}]: %{message}" + EOL; private static String E1_PATTERN4 = "[" + C1 + " ]: " + M1 + EOL; private static String E2_PATTERN4 = "[" + C2 + "]: " + M2 + EOL; private static String E3_PATTERN4 = "[" + C3 + "]: " + M3 + EOL; private static String PATTERN5 = "[%-10.{category}]: %{message}" + EOL; private static String E1_PATTERN5 = "[ " + C1 + "]: " + M1 + EOL; private static String E2_PATTERN5 = "[" + C2 + "]: " + M2 + EOL; private static String E3_PATTERN5 = "[" + C3 + "]: " + M3 + EOL; private static String PATTERN6 = "[%{context}]: %{message}" + EOL; private static String E1_PATTERN6 = "[]: " + M1 + EOL; private static String E2_PATTERN6 = "[]: " + M2 + EOL; private static String E3_PATTERN6 = "[]: " + M3 + EOL; private static String PATTERN7 = "[%{context:stack}]: %{message}" + EOL; private static String E1_PATTERN7 = "[]: " + M1 + EOL; private static String E2_PATTERN7 = "[]: " + M2 + EOL; private static String E3_PATTERN7 = "[]: " + M3 + EOL; private static String PATTERN8 = "[%{context:method}]: %{message}" + EOL; private static String E1_PATTERN8 = "[com.biz.MyObject.myMethod(MyObject:53)]: " + M1 + EOL; private static String E2_PATTERN8 = "[]: " + M2 + EOL; private static String E3_PATTERN8 = "[]: " + M3 + EOL; private static String CLASS_PREFIX = FormatterTestCase.class.getName() + "."; private static String PATTERN9 = "[%{method}]: %{message}" + EOL; private static String E1_PATTERN9 = "[com.biz.MyObject.myMethod(MyObject:53)]: " + M1 + EOL; private static String E2_PATTERN9_START = "[" + CLASS_PREFIX + "testPattern9Formatter("; private static String E2_PATTERN9_END = ")]: " + M2 + EOL; private static String E3_PATTERN9_START = "[" + CLASS_PREFIX + "testPattern9Formatter("; private static String E3_PATTERN9_END = ")]: " + M3 + EOL; private static String PATTERN10 = "[%{context:method}]: %{message}" + EOL; private static String E1_PATTERN10 = "[com.biz.MyObject.myMethod(MyObject:53)]: " + M1 + EOL; private static String E2_PATTERN10 = "[]: " + M2 + EOL; private static String E3_PATTERN10 = "[]: " + M3 + EOL; private static String PATTERN11 = "[%{context:method}]: %{message}" + EOL; private static String E1_PATTERN11 = "[com.biz.MyObject.myMethod(MyObject:53)]: " + M1 + EOL; private static String E2_PATTERN11 = "[]: " + M2 + EOL; private static String E3_PATTERN11 = "[]: " + M3 + EOL; private static LogEvent createEvent( final String category, final String message, final Throwable throwable, final long time, final Priority priority, final ContextMap contextMap ) { setupContext(); final LogEvent event = new LogEvent(); event.setCategory( category ); event.setMessage( message ); event.setThrowable( throwable ); event.setTime( time ); event.setPriority( priority ); event.setContextMap( contextMap ); return event; } private static void setupContext() { if( !mapsConfigured ) { mapsConfigured = true; CM1.set( "method", "com.biz.MyObject.myMethod(MyObject:53)" ); CM1.set( "hostname", "helm.realityforge.org" ); CM1.set( "interface", "127.0.0.1" ); CM1.set( "user", "barney" ); CM1.makeReadOnly(); CM2.set( "hostname", "helm.realityforge.org" ); CM2.set( "interface", "127.0.0.1" ); CM2.set( "user", "barney" ); CM2.makeReadOnly(); } } public FormatterTestCase( final String name ) { super( name ); } public void testRawFormatter() { final Formatter formatter = new RawFormatter(); final String result1 = formatter.format( E1 ); final String result2 = formatter.format( E2 ); final String result3 = formatter.format( E3 ); assertEquals( "Raw formatting of E1", E1.getMessage(), result1 ); assertEquals( "Raw formatting of E2", E2.getMessage(), result2 ); assertEquals( "Raw formatting of E3", E3.getMessage(), result3 ); } public void testXMLFormatter() { final Formatter formatter = new XMLFormatter(); final String result1 = formatter.format( E1 ); final String result2 = formatter.format( E2 ); final String result3 = formatter.format( E3 ); assertEquals( "XML formatting of E1", E1_XML, result1 ); assertEquals( "XML formatting of E2", E2_XML, result2 ); assertEquals( "XML formatting of E3", E3_XML, result3 ); } public void testSyslogFormatter() { final Formatter formatter = new SyslogFormatter( FACILITY_ID, false ); final String result1 = formatter.format( E1 ); final String result2 = formatter.format( E2 ); final String result3 = formatter.format( E3 ); assertEquals( "SYSLOG formatting of E1", E1_SYSLOG, result1 ); assertEquals( "SYSLOG formatting of E2", E2_SYSLOG, result2 ); assertEquals( "SYSLOG formatting of E3", E3_SYSLOG, result3 ); } public void testSyslogWithBannerFormatter() { final Formatter formatter = new SyslogFormatter( FACILITY_ID, true ); final String result1 = formatter.format( E1 ); final String result2 = formatter.format( E2 ); final String result3 = formatter.format( E3 ); assertEquals( "SYSLOG with banner formatting of E1", E1_SYSLOG_WB, result1 ); assertEquals( "SYSLOG with banner formatting of E2", E2_SYSLOG_WB, result2 ); assertEquals( "SYSLOG with banner formatting of E3", E3_SYSLOG_WB, result3 ); } public void testPattern1Formatter() { final Formatter formatter = new PatternFormatter( PATTERN1 ); final String result1 = formatter.format( E1 ); final String result2 = formatter.format( E2 ); final String result3 = formatter.format( E3 ); assertEquals( "Pattern1 formatting of E1", E1_PATTERN1, result1 ); assertEquals( "Pattern1 formatting of E2", E2_PATTERN1, result2 ); assertEquals( "Pattern1 formatting of E3", E3_PATTERN1, result3 ); } public void testPattern2Formatter() { final Formatter formatter = new PatternFormatter( PATTERN2 ); final String result1 = formatter.format( E1 ); final String result2 = formatter.format( E2 ); final String result3 = formatter.format( E3 ); assertEquals( "Pattern2 formatting of E1", E1_PATTERN2, result1 ); assertEquals( "Pattern2 formatting of E2", E2_PATTERN2, result2 ); assertEquals( "Pattern2 formatting of E3", E3_PATTERN2, result3 ); } public void testPattern3Formatter() { final Formatter formatter = new PatternFormatter( PATTERN3 ); final String result1 = formatter.format( E1 ); final String result2 = formatter.format( E2 ); final String result3 = formatter.format( E3 ); assertEquals( "Pattern3 formatting of E1", E1_PATTERN3, result1 ); assertEquals( "Pattern3 formatting of E2", E2_PATTERN3, result2 ); assertEquals( "Pattern3 formatting of E3", E3_PATTERN3, result3 ); } public void testPattern4Formatter() { final Formatter formatter = new PatternFormatter( PATTERN4 ); final String result1 = formatter.format( E1 ); final String result2 = formatter.format( E2 ); final String result3 = formatter.format( E3 ); assertEquals( "Pattern4 formatting of E1", E1_PATTERN4, result1 ); assertEquals( "Pattern4 formatting of E2", E2_PATTERN4, result2 ); assertEquals( "Pattern4 formatting of E3", E3_PATTERN4, result3 ); } public void testPattern5Formatter() { final Formatter formatter = new PatternFormatter( PATTERN5 ); final String result1 = formatter.format( E1 ); final String result2 = formatter.format( E2 ); final String result3 = formatter.format( E3 ); assertEquals( "Pattern5 formatting of E1", E1_PATTERN5, result1 ); assertEquals( "Pattern5 formatting of E2", E2_PATTERN5, result2 ); assertEquals( "Pattern5 formatting of E3", E3_PATTERN5, result3 ); } public void testPattern6Formatter() { final Formatter formatter = new PatternFormatter( PATTERN6 ); final String result1 = formatter.format( E1 ); final String result2 = formatter.format( E2 ); final String result3 = formatter.format( E3 ); assertEquals( "Pattern6 formatting of E1", E1_PATTERN6, result1 ); assertEquals( "Pattern6 formatting of E2", E2_PATTERN6, result2 ); assertEquals( "Pattern6 formatting of E3", E3_PATTERN6, result3 ); } public void testPattern7Formatter() { final Formatter formatter = new PatternFormatter( PATTERN7 ); final String result1 = formatter.format( E1 ); final String result2 = formatter.format( E2 ); final String result3 = formatter.format( E3 ); assertEquals( "Pattern7 formatting of E1", E1_PATTERN7, result1 ); assertEquals( "Pattern7 formatting of E2", E2_PATTERN7, result2 ); assertEquals( "Pattern7 formatting of E3", E3_PATTERN7, result3 ); } public void testPattern8Formatter() { final Formatter formatter = new PatternFormatter( PATTERN8 ); final String result1 = formatter.format( E1 ); final String result2 = formatter.format( E2 ); final String result3 = formatter.format( E3 ); assertEquals( "Pattern8 formatting of E1", E1_PATTERN8, result1 ); assertEquals( "Pattern8 formatting of E2", E2_PATTERN8, result2 ); assertEquals( "Pattern8 formatting of E3", E3_PATTERN8, result3 ); } /* public void testPattern9Formatter() { final Formatter formatter = new PatternFormatter( PATTERN9 ); final String result1 = formatter.format( E1 ); final String result2 = formatter.format( E2 ); final String result3 = formatter.format( E3 ); System.out.println( "results1: " + result1 ); System.out.println( "results2: " + result2 ); System.out.println( "results3: " + result3 ); assertEquals( "Pattern9 formatting of E1", E1_PATTERN9, result1 ); assertTrue( "Pattern9 formatting of E2", result2.startsWith( E2_PATTERN9_START ) ); assertTrue( "Pattern9 end formatting of E2", result2.endsWith( E2_PATTERN9_END ) ); assertTrue( "Pattern9 formatting of E3", result3.startsWith( E3_PATTERN9_START ) ); assertTrue( "Pattern9 end formatting of E3", result3.endsWith( E3_PATTERN9_END ) ); } */ public void testPattern10Formatter() { final Formatter formatter = new PatternFormatter( PATTERN10 ); final String result1 = formatter.format( E1 ); final String result2 = formatter.format( E2 ); final String result3 = formatter.format( E3 ); assertEquals( "Pattern10 formatting of E1", E1_PATTERN10, result1 ); assertEquals( "Pattern10 formatting of E2", E2_PATTERN10, result2 ); assertEquals( "Pattern10 formatting of E3", E3_PATTERN10, result3 ); } public void testPattern11Formatter() { final Formatter formatter = new PatternFormatter( PATTERN11 ); final String result1 = formatter.format( E1 ); final String result2 = formatter.format( E2 ); final String result3 = formatter.format( E3 ); assertEquals( "Pattern11 formatting of E1", E1_PATTERN11, result1 ); assertEquals( "Pattern11 formatting of E2", E2_PATTERN11, result2 ); assertEquals( "Pattern11 formatting of E3", E3_PATTERN11, result3 ); } } avalon-logkit-2.0.dev-0/src/test/org/apache/log/util/test/UtilTestCase.java100644 0 0 6371 10036267317 23706 0ustar 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.log.util.test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import junit.framework.TestCase; import org.apache.log.Hierarchy; import org.apache.log.Logger; import org.apache.log.Priority; import org.apache.log.format.RawFormatter; import org.apache.log.output.io.StreamTarget; import org.apache.log.util.LoggerOutputStream; /** * Test suite for utility features of Logger. * * @author Peter Donald */ public final class UtilTestCase extends TestCase { private static final String EOL = System.getProperty( "line.separator", "\n" ); private static final RawFormatter FORMATTER = new RawFormatter(); private static final String MSG = "No soup for you!"; private static final String RMSG = MSG; public UtilTestCase( final String name ) { super( name ); } private String getResult( final ByteArrayOutputStream output ) { final String result = output.toString(); output.reset(); return result; } public void testStackIntrospector() throws Exception { /* final String METHOD_RESULT = UtilTestCase.class.getName() + "."; final ByteArrayOutputStream output = new ByteArrayOutputStream(); final StreamTarget target = new StreamTarget( output, METHOD_FORMATTER ); final Hierarchy hierarchy = new Hierarchy(); hierarchy.setDefaultLogTarget( target ); final Logger logger = hierarchy.getLoggerFor( "myLogger" ); logger.debug( MSG ); final String result = getResult( output ); final String expected = METHOD_RESULT + "testStackIntrospector()"; assert( "StackIntrospector", result.startsWith( expected ) ); //result of StackIntrospector.getCallerMethod( Logger.class ); */ } public void testLoggerOutputStream() throws Exception { final ByteArrayOutputStream output = new ByteArrayOutputStream(); final StreamTarget target = new StreamTarget( output, FORMATTER ); final Hierarchy hierarchy = new Hierarchy(); hierarchy.setDefaultLogTarget( target ); final Logger logger = hierarchy.getLoggerFor( "myLogger" ); final LoggerOutputStream outputStream = new LoggerOutputStream( logger, Priority.DEBUG ); final PrintStream printer = new PrintStream( outputStream, true ); printer.println( MSG ); assertEquals( "LoggerOutputStream", RMSG + EOL, getResult( output ) ); //unbuffered output printer.print( MSG ); printer.flush(); assertEquals( "LoggerOutputStream", RMSG, getResult( output ) ); printer.close(); } } avalon-logkit-2.0.dev-0/src/test/org/apache/log/output/test/OutputTargetTestCase.java100644 0 0 21751 10036267317 26042 0ustar 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.log.output.test; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStreamWriter; import junit.framework.TestCase; import org.apache.log.Hierarchy; import org.apache.log.LogTarget; import org.apache.log.Logger; import org.apache.log.Priority; import org.apache.log.format.RawFormatter; import org.apache.log.output.AbstractOutputTarget; import org.apache.log.output.MemoryTarget; import org.apache.log.output.io.FileTarget; import org.apache.log.output.io.SafeFileTarget; import org.apache.log.output.io.StreamTarget; import org.apache.log.output.io.WriterTarget; /** * Test suite for the formatters. * TODO: Incorporate testing for ContextStack and ContextMap * * @author Peter Donald */ public final class OutputTargetTestCase extends TestCase { private static String M1 = "meep meep!"; private static String M2 = "marina"; private static String M3 = "spin and then fall down"; private static String HEAD = ""; private static String TAIL = ""; private static String R1 = M1; private static String R2 = M2; private static String R3 = M3; private static String OUTPUT = HEAD + R1 + R2 + R3 + TAIL; private static RawFormatter FORMATTER = new RawFormatter(); private final File m_logFile; public OutputTargetTestCase( final String name ) throws IOException { super( name ); m_logFile = ( new File( "test/log/logfile.txt" ) ).getCanonicalFile(); } private String getResult( final ByteArrayOutputStream output ) { final String result = output.toString(); output.reset(); return result; } public void testStreamTarget() throws Exception { final ByteArrayOutputStream output = new ByteArrayOutputStream(); final StreamTarget target = new StreamTarget( output, FORMATTER ); doStreamTest( output, target ); /* final ExtendedPatternFormatter formatter = new ExtendedPatternFormatter( "%{method} from %{thread}\n" ); final StreamTarget target2 = new StreamTarget( System.out, formatter ); final Logger logger = getNewLogger( target2 ); logger.debug( M1 ); */ } public void testWriterTarget() throws Exception { final ByteArrayOutputStream output = new ByteArrayOutputStream(); final OutputStreamWriter writer = new OutputStreamWriter( output ); final WriterTarget target = new WriterTarget( writer, FORMATTER ); doStreamTest( output, target ); } public void testFileTarget() throws Exception { final FileTarget target = new FileTarget( m_logFile, false, FORMATTER ); final Logger logger = getNewLogger( target ); logger.debug( M1 ); logger.debug( M2 ); logger.debug( M3 ); target.close(); final String data = getFileContents( m_logFile ); assertEquals( "Targets file output", OUTPUT, data ); assertTrue( "Deleting logfile", m_logFile.delete() ); logger.debug( M1 ); assertTrue( "Write after close()", !m_logFile.exists() ); } public void testSafeFileTarget() throws Exception { final SafeFileTarget target = new SafeFileTarget( m_logFile, false, FORMATTER ); final Logger logger = getNewLogger( target ); logger.debug( M1 ); final String data1 = getFileContents( m_logFile ); assertEquals( "Targets file output", HEAD + R1, data1 ); assertTrue( "Deleting logfile", m_logFile.delete() ); logger.debug( M2 ); logger.debug( M3 ); target.close(); final String data2 = getFileContents( m_logFile ); assertEquals( "Targets file output", R2 + R3 + TAIL, data2 ); assertTrue( "Deleting logfile", m_logFile.delete() ); logger.debug( M1 ); assertTrue( "Write after close()", !m_logFile.exists() ); } /** * Test that MemoryTarget triggers on buffer size hit. * * @exception Exception if an error occurs */ public void testMemoryTarget1() throws Exception { final ByteArrayOutputStream output = new ByteArrayOutputStream(); final StreamTarget other = new StreamTarget( output, FORMATTER ); final MemoryTarget target = new MemoryTarget( other, 1, Priority.FATAL_ERROR ); doStreamOutputTest( output, target ); } /** * Test that MemoryTarget triggers on priority correctly. * * @exception Exception if an error occurs */ public void testMemoryTarget2() throws Exception { final ByteArrayOutputStream output = new ByteArrayOutputStream(); final StreamTarget other = new StreamTarget( output, FORMATTER ); final MemoryTarget target = new MemoryTarget( other, 10, Priority.DEBUG ); doStreamOutputTest( output, target ); } /** * Test that MemoryTarget triggers on priority correctly. * * @exception Exception if an error occurs */ public void testMemoryTarget3() throws Exception { final ByteArrayOutputStream output = new ByteArrayOutputStream(); final StreamTarget other = new StreamTarget( output, FORMATTER ); final MemoryTarget target = new MemoryTarget( other, 10, Priority.FATAL_ERROR ); final Logger logger = getNewLogger( target ); //Head output should not be pushed yet final String head = getResult( output ); assertEquals( "Targets Head output", "", head ); //Not pushed yet logger.debug( M1 ); final String result1 = getResult( output ); assertEquals( "Targets R1 debug output", "", result1 ); target.push(); final String resultPP = getResult( output ); assertEquals( "Targets HEAD+R1 debug output", HEAD + R1, resultPP ); logger.debug( M2 ); final String result2 = getResult( output ); logger.debug( M3 ); final String result3 = getResult( output ); //fatal error triggers a push logger.fatalError( M3 ); final String result4 = getResult( output ); assertEquals( "Targets R2 debug output", "", result2 ); assertEquals( "Targets R3 debug output", "", result3 ); assertEquals( "Targets R3 debug output", R2 + R3 + R3, result4 ); } private Logger getNewLogger( final LogTarget target ) { final Hierarchy hierarchy = new Hierarchy(); final Logger logger = hierarchy.getLoggerFor( "myCategory" ); logger.setLogTargets( new LogTarget[]{target} ); return logger; } private String getFileContents( final File file ) throws IOException { final FileInputStream input = new FileInputStream( file ); final StringBuffer sb = new StringBuffer(); int ch = input.read(); while( -1 != ch ) { sb.append( (char)ch ); ch = input.read(); } input.close(); return sb.toString(); } private Logger doStreamOutputTest( final ByteArrayOutputStream output, final LogTarget target ) { final Logger logger = getNewLogger( target ); final String head = getResult( output ); logger.debug( M1 ); final String result1 = getResult( output ); logger.debug( M2 ); final String result2 = getResult( output ); logger.debug( M3 ); final String result3 = getResult( output ); assertEquals( "Targets Head output", HEAD, head ); assertEquals( "Targets R1 debug output", R1, result1 ); assertEquals( "Targets R2 debug output", R2, result2 ); assertEquals( "Targets R3 debug output", R3, result3 ); return logger; } private void doStreamTest( final ByteArrayOutputStream output, final AbstractOutputTarget target ) { final Logger logger = doStreamOutputTest( output, target ); target.close(); final String tail = getResult( output ); assertEquals( "Targets Tail output", TAIL, tail ); logger.debug( M1 ); final String noresult = getResult( output ); //final String errorResult = getErrorResult( errorOutput ); assertEquals( "Write after close()", "", noresult ); //assertEquals( "Epecting error", "", errorResult ); } } avalon-logkit-2.0.dev-0/src/test/org/apache/log/output/test/TestRotatingFileOutputLogTarget.java100644 0 0 12010 10036267317 30204 0ustar 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.log.output.test; import java.io.File; import org.apache.log.Hierarchy; import org.apache.log.LogTarget; import org.apache.log.Logger; import org.apache.log.format.RawFormatter; import org.apache.log.output.io.rotate.FileStrategy; import org.apache.log.output.io.rotate.RevolvingFileStrategy; import org.apache.log.output.io.rotate.RotateStrategy; import org.apache.log.output.io.rotate.RotateStrategyBySize; import org.apache.log.output.io.rotate.RotateStrategyByTime; import org.apache.log.output.io.rotate.RotatingFileTarget; import org.apache.log.output.io.rotate.UniqueFileStrategy; /** * * @author Bernhard Huber */ public class TestRotatingFileOutputLogTarget { private RawFormatter m_formatter = new RawFormatter(); /** test file rotation by size, using unique filenames */ public void testSizeUnique() throws Exception { final File file = new File( "test/size-unique.log" ); final FileStrategy fileStrategy = new UniqueFileStrategy( file ); final RotateStrategy rotateStrategy = new RotateStrategyBySize( 128 * 1024 ); final Logger logger = getLogger( fileStrategy, rotateStrategy ); doTest( logger ); } /** test file rotation by size, using revolving filenames */ public void testSizeRevoling() throws Exception { final File file = new File( "test/size-revolve.log" ); final FileStrategy fileStrategy = new RevolvingFileStrategy( file, 20 ); final RotateStrategy rotateStrategy = new RotateStrategyBySize( 128 * 1024 ); final Logger logger = getLogger( fileStrategy, rotateStrategy ); doTest( logger ); } /** test file rotation by time, using unique filenames */ public void testTimeUnique() throws Exception { final File file = new File( "test/time-unique.log" ); final FileStrategy fileStrategy = new UniqueFileStrategy( file ); final RotateStrategy rotateStrategy = new RotateStrategyByTime( 3 * 1000 ); final Logger logger = getLogger( fileStrategy, rotateStrategy ); doTest( logger ); } /** test file rotation by time, using revolving filenames */ public void testTimeRevolving() throws Exception { final File file = new File( "test/time-revolve.log" ); final FileStrategy fileStrategy = new RevolvingFileStrategy( file, 5 ); final RotateStrategy rotateStrategy = new RotateStrategyByTime( 3 * 1000 ); final Logger logger = getLogger( fileStrategy, rotateStrategy ); doTest( logger ); } private void doTest( final Logger logger ) { final long startTime = System.currentTimeMillis(); final long diffTime = 10 * 1000; long endTime = startTime; int size = 0; for( int i = 0; ( endTime - startTime ) < diffTime; i++ ) { size += generateMessages( logger, i, size, ( endTime - startTime ) ); endTime = System.currentTimeMillis(); } } /** just generate some logger messages */ private int generateMessages( final Logger logger, final int i, final long totalSize, final long diffTime ) { final String message = "Message " + i + ": total size " + totalSize + " diff time " + diffTime; logger.debug( message ); logger.info( message ); logger.warn( message ); logger.error( message ); logger.fatalError( message ); return message.length(); } private Logger getLogger( final FileStrategy fileStrategy, final RotateStrategy rotateStrategy ) throws Exception { final RotatingFileTarget target = new RotatingFileTarget( m_formatter, rotateStrategy, fileStrategy ); final Hierarchy hierarchy = new Hierarchy(); final Logger logger = hierarchy.getLoggerFor( "myCat" ); logger.setLogTargets( new LogTarget[]{target} ); return logger; } public static void main( final String args[] ) throws Exception { TestRotatingFileOutputLogTarget trfolt = new TestRotatingFileOutputLogTarget(); trfolt.testSizeUnique(); trfolt.testSizeRevoling(); trfolt.testTimeUnique(); trfolt.testTimeRevolving(); } } avalon-logkit-2.0.dev-0/src/test/org/apache/log/output/test/DatagramTest.java100644 0 0 4250 10036267317 24272 0ustar 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.log.output.test; import java.net.InetAddress; import org.apache.log.Hierarchy; import org.apache.log.LogTarget; import org.apache.log.Logger; import org.apache.log.format.Formatter; import org.apache.log.format.RawFormatter; import org.apache.log.format.SyslogFormatter; import org.apache.log.output.net.DatagramOutputTarget; /** * * @author Peter Donald */ public final class DatagramTest { public static void main( final String[] args ) { try { Formatter formatter = null; String message = null; if( 0 == args.length ) { formatter = new SyslogFormatter( SyslogFormatter.FACILITY_DAEMON ); message = "hello!!!"; } else { //final int facility = 9<<3; //Cron //final int priority = 3; //ERROR //final String message = "<" + (facility|priority) + "> hello!!!"; formatter = new RawFormatter(); message = args[ 0 ]; } final InetAddress address = InetAddress.getByName( "localhost" ); final DatagramOutputTarget target = new DatagramOutputTarget( address, 514, formatter ); final Logger logger = Hierarchy.getDefaultHierarchy().getLoggerFor( "foo" ); logger.setLogTargets( new LogTarget[]{target} ); logger.warn( message, new Exception() ); } catch( final Throwable t ) { t.printStackTrace(); } } } avalon-logkit-2.0.dev-0/src/test/org/apache/log/output/test/RevolvingFileStrategyTestCase.java100644 0 0 12526 10036267317 27671 0ustar 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.log.output.test; import java.io.File; import java.io.IOException; import junit.framework.TestCase; import org.apache.log.output.io.rotate.RevolvingFileStrategy; /** * Test suite for the RevolvingFileStrategy. * * @author Peter Donald */ public final class RevolvingFileStrategyTestCase extends TestCase { private static final int OLD_AGE = 100000000; private static final int YOUNG_AGE = -100000000; private final File m_baseFile; private final long m_now = System.currentTimeMillis(); public RevolvingFileStrategyTestCase( final String name ) throws IOException { super( name ); m_baseFile = ( new File( "build/testdata/log" ) ).getCanonicalFile(); m_baseFile.getParentFile().mkdirs(); } private void deleteFiles( final int maxRotation ) throws IOException { for( int i = 0; i <= maxRotation; i++ ) { final File file = new File( getFilename( i ) ); if( file.exists() && !file.delete() ) { throw new IOException( "Failed to delete file " + file ); } } } private String getFilename( int i ) { return m_baseFile.toString() + ".00000" + i; } private void createFile( final int rotation, final long age ) throws IOException { final File file = new File( getFilename( rotation ) ); if( !file.createNewFile() ) { throw new IOException( "Failed to create file " + file ); } final long time = m_now - age; file.setLastModified( time ); } public void testNew() throws Exception { deleteFiles( 9 ); final RevolvingFileStrategy strategy = new RevolvingFileStrategy( m_baseFile, 9 ); assertEquals( "rotation", 0, strategy.getCurrentRotation() ); } public void testRotationExisting() throws Exception { deleteFiles( 9 ); createFile( 0, 0 ); final RevolvingFileStrategy strategy = new RevolvingFileStrategy( m_baseFile, 9 ); assertEquals( "rotation", 1, strategy.getCurrentRotation() ); } public void testRotationExisting2() throws Exception { deleteFiles( 9 ); createFile( 0, 0 ); createFile( 1, 0 ); createFile( 2, 0 ); createFile( 3, 0 ); createFile( 4, 0 ); final RevolvingFileStrategy strategy = new RevolvingFileStrategy( m_baseFile, 9 ); assertEquals( "rotation", 5, strategy.getCurrentRotation() ); } public void testRotationExistingWithMissing() throws Exception { deleteFiles( 9 ); createFile( 0, 0 ); createFile( 4, 0 ); final RevolvingFileStrategy strategy = new RevolvingFileStrategy( m_baseFile, 9 ); assertEquals( "rotation", 5, strategy.getCurrentRotation() ); } public void testRotationExistingWithOlderLower() throws Exception { deleteFiles( 9 ); createFile( 0, OLD_AGE ); //Note this is oldest createFile( 4, 0 ); final RevolvingFileStrategy strategy = new RevolvingFileStrategy( m_baseFile, 9 ); assertEquals( "rotation", 5, strategy.getCurrentRotation() ); } public void testRotationExistingWithOlderHigher() throws Exception { deleteFiles( 9 ); createFile( 0, 0 ); createFile( 4, OLD_AGE ); final RevolvingFileStrategy strategy = new RevolvingFileStrategy( m_baseFile, 9 ); assertEquals( "rotation", 5, strategy.getCurrentRotation() ); } public void testFullRotation() throws Exception { deleteFiles( 9 ); createFile( 0, 0 ); createFile( 1, 0 ); createFile( 2, 0 ); createFile( 3, 0 ); createFile( 4, 0 ); createFile( 5, 0 ); createFile( 6, 0 ); createFile( 7, 0 ); createFile( 8, 0 ); createFile( 9, 0 ); final RevolvingFileStrategy strategy = new RevolvingFileStrategy( m_baseFile, 9 ); assertEquals( "rotation", 0, strategy.getCurrentRotation() ); } public void testFullRotationWithOlder() throws Exception { deleteFiles( 9 ); createFile( 0, 0 ); createFile( 1, 0 ); createFile( 2, 0 ); createFile( 3, 0 ); createFile( 4, 0 ); createFile( 5, 0 ); createFile( 6, 0 ); createFile( 7, OLD_AGE ); createFile( 8, 0 ); createFile( 9, 0 ); final RevolvingFileStrategy strategy = new RevolvingFileStrategy( m_baseFile, 9 ); assertEquals( "rotation", 7, strategy.getCurrentRotation() ); } } avalon-logkit-2.0.dev-0/src/test/org/apache/log/output/test/DBTargetTestCase.java100644 0 0 11233 10036267317 25021 0ustar 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.log.output.test; import junit.framework.TestCase; import org.apache.log.Hierarchy; import org.apache.log.LogTarget; import org.apache.log.Logger; import org.apache.log.output.db.ColumnInfo; import org.apache.log.output.db.ColumnType; import org.apache.log.output.db.DefaultDataSource; import org.apache.log.output.db.DefaultJDBCTarget; import org.apache.log.output.db.NormalizedJDBCTarget; /** * Test suite for the DB output target. * * @author Peter Donald */ public final class DBTargetTestCase extends TestCase { private String m_connectString; private String m_userName; private String m_userPassword; private boolean m_doDBTest; public DBTargetTestCase( final String name ) throws Exception { super( name ); } public void setUp() throws Exception { String driverName = System.getProperty("test.db.driver"); m_connectString = System.getProperty("test.db.jdbc", ""); m_userName = System.getProperty( "test.db.user", "" ); m_userPassword = System.getProperty( "test.db.pword", "" ); m_doDBTest = System.getProperty( "test.db.run", "false" ).equalsIgnoreCase("true"); if (m_doDBTest) { Class.forName(driverName); } else { System.out.println("[WARNING] Database Testing is not being done"); System.out.println(); System.out.println("To enable database testing, please provide the"); System.out.println("following properties:"); System.out.println(); System.out.println( "test.db.driver -> Class name for the JDBC driver" ); System.out.println( "test.db.jdbc -> JDBC connect string" ); System.out.println( "test.db.user -> User ID" ); System.out.println( "test.db.pword -> User password" ); System.out.println( "test.db.run -> \"true\"" ); } } public void testBasicTarget() throws Exception { if (! m_doDBTest) return; final DefaultDataSource dataSource = new DefaultDataSource( m_connectString, m_userName, m_userPassword ); final ColumnInfo[] columns = { new ColumnInfo( "TIME", ColumnType.TIME, null ), new ColumnInfo( "PRIORITY", ColumnType.PRIORITY, null ), new ColumnInfo( "CATEGORY", ColumnType.CATEGORY, null ), new ColumnInfo( "HOSTNAME", ColumnType.STATIC, "helm.realityforge.net" ), new ColumnInfo( "MESSAGE", ColumnType.MESSAGE, null ) }; final DefaultJDBCTarget target = new DefaultJDBCTarget( dataSource, "log_entrys", columns ); final Logger logger = getNewLogger( target ); logger.debug( "Hello" ); } public void testNumericConstants() throws Exception { if ( !m_doDBTest ) return; final DefaultDataSource dataSource = new DefaultDataSource( m_connectString, m_userName, m_userPassword ); final ColumnInfo[] columns = { new ColumnInfo( "TIME", ColumnType.TIME, null ), new ColumnInfo( "PRIORITY", ColumnType.PRIORITY, null ), new ColumnInfo( "CATEGORY", ColumnType.CATEGORY, null ), new ColumnInfo( "HOSTNAME", ColumnType.STATIC, "helm.realityforge.net" ), new ColumnInfo( "MESSAGE", ColumnType.MESSAGE, null ) }; final NormalizedJDBCTarget target = new NormalizedJDBCTarget( dataSource, "log_entrys2", columns ); final Logger logger = getNewLogger( target ); logger.debug( "Hello" ); logger.info( "Hello info" ); logger.error( "Hello error" ); logger.fatalError( "Hello fatalError" ); } private Logger getNewLogger( final LogTarget target ) { final Hierarchy hierarchy = new Hierarchy(); final Logger logger = hierarchy.getLoggerFor( "myCategory" ); logger.setLogTargets( new LogTarget[]{target} ); return logger; } } avalon-logkit-2.0.dev-0/src/test/org/apache/log/test/RecordingLoggerListener.java100644 0 0 2550 10036267317 25135 0ustar 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.log.test; import java.util.ArrayList; import java.util.List; import org.apache.log.Logger; import org.apache.log.util.LoggerListener; /** * A logger listener that records the log messages it receives. * * @author Peter Donald * @version $Revision: 1.6 $ $Date: 2004/02/28 11:31:24 $ */ class RecordingLoggerListener extends LoggerListener { //The listeners that have been created private final List m_loggers = new ArrayList(); public void loggerCreated( final String category, final Logger logger ) { m_loggers.add( logger ); } public Logger[] getLoggers() { return (Logger[])m_loggers.toArray( new Logger[ m_loggers.size() ] ); } } avalon-logkit-2.0.dev-0/src/test/org/apache/log/test/WrappingTargetTestCase.java100644 0 0 10435 10036267317 24766 0ustar 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.log.test; import junit.framework.TestCase; import org.apache.log.LogEvent; import org.apache.log.LogTarget; import org.apache.log.output.AbstractWrappingTarget; import org.apache.log.util.Closeable; /** * Test suite for wrapping targets. * * @author Avalon Development Team */ public final class WrappingTargetTestCase extends TestCase { public WrappingTargetTestCase(String name) { super(name); } static private class DummyTarget implements LogTarget { private boolean closed = false; public void close() { closed = true; } public boolean isClosed() { return closed; } public void processEvent( LogEvent event ) { // Do nothing } } static private class CloseableDummyTarget extends DummyTarget implements Closeable { } static private class DummyTargetWrapper extends AbstractWrappingTarget { public DummyTargetWrapper( final LogTarget logTarget ) { super( logTarget ); } public DummyTargetWrapper( final LogTarget logTarget, final boolean closeWrappedTarget ) { super( logTarget, closeWrappedTarget ); } public void doProcessEvent( LogEvent event ) { // Do nothing } } public void testNonCloseable() { DummyTarget dummyTargetNonClose = new DummyTarget(); DummyTarget dummyTargetNonClose2 = new DummyTarget(); DummyTarget dummyTargetClose = new DummyTarget(); DummyTargetWrapper wrapperNonClose = new DummyTargetWrapper(dummyTargetNonClose, false); DummyTargetWrapper wrapperNonClose2 = new DummyTargetWrapper(dummyTargetNonClose2); // should default to false DummyTargetWrapper wrapperClose = new DummyTargetWrapper(dummyTargetClose, true); assertTrue( !dummyTargetNonClose.isClosed() ); assertTrue( !dummyTargetNonClose2.isClosed() ); assertTrue( !dummyTargetClose.isClosed() ); wrapperNonClose.close(); wrapperNonClose2.close(); wrapperClose.close(); // The close() should have no effect, since neither target implements closeable. assertTrue( !dummyTargetNonClose.isClosed() ); assertTrue( !dummyTargetNonClose2.isClosed() ); assertTrue( !dummyTargetClose.isClosed() ); } public void testCloseable() { DummyTarget dummyTargetNonClose = new CloseableDummyTarget(); DummyTarget dummyTargetNonClose2 = new CloseableDummyTarget(); DummyTarget dummyTargetClose = new CloseableDummyTarget(); DummyTargetWrapper wrapperNonClose = new DummyTargetWrapper(dummyTargetNonClose, false); DummyTargetWrapper wrapperNonClose2 = new DummyTargetWrapper(dummyTargetNonClose2); // should default to false DummyTargetWrapper wrapperClose = new DummyTargetWrapper(dummyTargetClose, true); assertTrue( !dummyTargetNonClose.isClosed() ); assertTrue( !dummyTargetNonClose2.isClosed() ); assertTrue( !dummyTargetClose.isClosed() ); wrapperNonClose.close(); wrapperNonClose2.close(); wrapperClose.close(); // Only the target that was wrapped with the closeWrapped parameter // set to true should be closed. assertTrue( !dummyTargetNonClose.isClosed() ); assertTrue( !dummyTargetNonClose2.isClosed() ); assertTrue( dummyTargetClose.isClosed() ); } } avalon-logkit-2.0.dev-0/src/test/org/apache/log/test/InheritanceTestCase.java100644 0 0 33074 10036267317 24265 0ustar 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.log.test; import java.io.ByteArrayOutputStream; import junit.framework.TestCase; import org.apache.log.Hierarchy; import org.apache.log.LogTarget; import org.apache.log.Logger; import org.apache.log.Priority; import org.apache.log.format.PatternFormatter; import org.apache.log.output.io.StreamTarget; /** * Test suite for inheritance features of Logger. * * @author Peter Donald */ public final class InheritanceTestCase extends TestCase { private static final String PATTERN = "%{priority}-%{message}"; private static final PatternFormatter FORMATTER = new PatternFormatter( PATTERN ); private static final String PATTERN2 = "Simon saids %{priority}-%{message}"; private static final PatternFormatter FORMATTER2 = new PatternFormatter( PATTERN2 ); private static final String MSG = "No soup for you!"; private static final String RMSG = "DEBUG-" + MSG; private static final String R2MSG = "Simon saids DEBUG-" + MSG; public InheritanceTestCase( final String name ) { super( name ); } private String getResult( final ByteArrayOutputStream output ) { final String result = output.toString(); output.reset(); return result; } public void testPriorityInheritance() throws Exception { final Hierarchy hierarchy = new Hierarchy(); final ByteArrayOutputStream output = new ByteArrayOutputStream(); final StreamTarget target = new StreamTarget( output, FORMATTER ); hierarchy.setDefaultLogTarget( target ); final Logger b = hierarchy.getLoggerFor( "b" ); final Logger bc = hierarchy.getLoggerFor( "b.c" ); final Logger bcd = hierarchy.getLoggerFor( "b.c.d" ); b.debug( MSG ); assertEquals( "Priority debug output", RMSG, getResult( output ) ); bc.debug( MSG ); assertEquals( "Priority debug output", RMSG, getResult( output ) ); bcd.debug( MSG ); assertEquals( "Priority debug output", RMSG, getResult( output ) ); b.setPriority( Priority.WARN ); b.debug( MSG ); assertEquals( "Priority debug output", "", getResult( output ) ); bc.debug( MSG ); assertEquals( "Priority debug output", "", getResult( output ) ); bcd.debug( MSG ); assertEquals( "Priority debug output", "", getResult( output ) ); bc.setPriority( Priority.DEBUG ); b.debug( MSG ); assertEquals( "Priority debug output", "", getResult( output ) ); bc.debug( MSG ); assertEquals( "Priority debug output", RMSG, getResult( output ) ); bcd.debug( MSG ); assertEquals( "Priority debug output", RMSG, getResult( output ) ); bcd.setPriority( Priority.WARN ); b.debug( MSG ); assertEquals( "Priority debug output", "", getResult( output ) ); bc.debug( MSG ); assertEquals( "Priority debug output", RMSG, getResult( output ) ); bcd.debug( MSG ); assertEquals( "Priority debug output", "", getResult( output ) ); bcd.unsetPriority(); b.debug( MSG ); assertEquals( "Priority debug output", "", getResult( output ) ); bc.debug( MSG ); assertEquals( "Priority debug output", RMSG, getResult( output ) ); bcd.debug( MSG ); assertEquals( "Priority debug output", RMSG, getResult( output ) ); bc.unsetPriority(); b.debug( MSG ); assertEquals( "Priority debug output", "", getResult( output ) ); bc.debug( MSG ); assertEquals( "Priority debug output", "", getResult( output ) ); bcd.debug( MSG ); assertEquals( "Priority debug output", "", getResult( output ) ); b.unsetPriority(); b.debug( MSG ); assertEquals( "Priority debug output", RMSG, getResult( output ) ); bc.debug( MSG ); assertEquals( "Priority debug output", RMSG, getResult( output ) ); bcd.debug( MSG ); assertEquals( "Priority debug output", RMSG, getResult( output ) ); bc.setPriority( Priority.WARN ); b.debug( MSG ); assertEquals( "Priority debug output", RMSG, getResult( output ) ); bc.debug( MSG ); assertEquals( "Priority debug output", "", getResult( output ) ); bcd.debug( MSG ); assertEquals( "Priority debug output", "", getResult( output ) ); b.unsetPriority( true ); b.debug( MSG ); assertEquals( "Priority debug output", RMSG, getResult( output ) ); bc.debug( MSG ); assertEquals( "Priority debug output", RMSG, getResult( output ) ); bcd.debug( MSG ); assertEquals( "Priority debug output", RMSG, getResult( output ) ); } public void testLogTargetInheritance() { final ByteArrayOutputStream output1 = new ByteArrayOutputStream(); final StreamTarget target1 = new StreamTarget( output1, FORMATTER ); final ByteArrayOutputStream output2 = new ByteArrayOutputStream(); final StreamTarget target2 = new StreamTarget( output2, FORMATTER2 ); final LogTarget[] targets1 = new LogTarget[]{target1}; final LogTarget[] targets2 = new LogTarget[]{target2}; final Hierarchy hierarchy = new Hierarchy(); hierarchy.setDefaultLogTarget( target1 ); final Logger b = hierarchy.getLoggerFor( "b" ); final Logger bc = hierarchy.getLoggerFor( "b.c" ); final Logger bcd = hierarchy.getLoggerFor( "b.c.d" ); b.setLogTargets( targets1 ); b.debug( MSG ); assertEquals( "LogTarget inherit debug output", RMSG, getResult( output1 ) ); bc.debug( MSG ); assertEquals( "LogTarget inherit debug output", RMSG, getResult( output1 ) ); bcd.debug( MSG ); assertEquals( "LogTarget inherit debug output", RMSG, getResult( output1 ) ); b.setLogTargets( targets2 ); b.debug( MSG ); assertEquals( "LogTarget inherit debug output", R2MSG, getResult( output2 ) ); bc.debug( MSG ); assertEquals( "LogTarget inherit debug output", R2MSG, getResult( output2 ) ); bcd.debug( MSG ); assertEquals( "LogTarget inherit debug output", R2MSG, getResult( output2 ) ); bc.setLogTargets( targets1 ); b.debug( MSG ); assertEquals( "LogTarget inherit debug output", R2MSG, getResult( output2 ) ); bc.debug( MSG ); assertEquals( "LogTarget inherit debug output", RMSG, getResult( output1 ) ); bcd.debug( MSG ); assertEquals( "LogTarget inherit debug output", RMSG, getResult( output1 ) ); bcd.setLogTargets( targets2 ); b.debug( MSG ); assertEquals( "LogTarget inherit debug output", R2MSG, getResult( output2 ) ); bc.debug( MSG ); assertEquals( "LogTarget inherit debug output", RMSG, getResult( output1 ) ); bcd.debug( MSG ); assertEquals( "LogTarget inherit debug output", R2MSG, getResult( output2 ) ); bcd.unsetLogTargets(); b.debug( MSG ); assertEquals( "LogTarget inherit debug output", R2MSG, getResult( output2 ) ); bc.debug( MSG ); assertEquals( "LogTarget inherit debug output", RMSG, getResult( output1 ) ); bcd.debug( MSG ); assertEquals( "LogTarget inherit debug output", RMSG, getResult( output1 ) ); bc.unsetLogTargets(); b.debug( MSG ); assertEquals( "LogTarget inherit debug output", R2MSG, getResult( output2 ) ); bc.debug( MSG ); assertEquals( "LogTarget inherit debug output", R2MSG, getResult( output2 ) ); bcd.debug( MSG ); assertEquals( "LogTarget inherit debug output", R2MSG, getResult( output2 ) ); b.unsetLogTargets(); b.debug( MSG ); assertEquals( "LogTarget inherit debug output", RMSG, getResult( output1 ) ); bc.debug( MSG ); assertEquals( "LogTarget inherit debug output", RMSG, getResult( output1 ) ); bcd.debug( MSG ); assertEquals( "LogTarget inherit debug output", RMSG, getResult( output1 ) ); bc.setLogTargets( targets2 ); b.debug( MSG ); assertEquals( "LogTarget inherit debug output", RMSG, getResult( output1 ) ); bc.debug( MSG ); assertEquals( "LogTarget inherit debug output", R2MSG, getResult( output2 ) ); bcd.debug( MSG ); assertEquals( "LogTarget inherit debug output", R2MSG, getResult( output2 ) ); b.unsetLogTargets( true ); b.debug( MSG ); assertEquals( "LogTarget inherit debug output", RMSG, getResult( output1 ) ); bc.debug( MSG ); assertEquals( "LogTarget inherit debug output", RMSG, getResult( output1 ) ); bcd.debug( MSG ); assertEquals( "LogTarget inherit debug output", RMSG, getResult( output1 ) ); } public void testAdditivity() throws Exception { final Hierarchy hierarchy = new Hierarchy(); final ByteArrayOutputStream output = new ByteArrayOutputStream(); final StreamTarget target = new StreamTarget( output, FORMATTER ); final LogTarget[] targets = new LogTarget[]{target}; final Logger b = hierarchy.getLoggerFor( "b" ); final Logger bc = hierarchy.getLoggerFor( "b.c" ); final Logger bcd = hierarchy.getLoggerFor( "b.c.d" ); b.setLogTargets( targets ); bc.setLogTargets( targets ); bcd.setLogTargets( targets ); b.debug( MSG ); assertEquals( "Additivity debug output", RMSG, getResult( output ) ); bc.debug( MSG ); assertEquals( "Additivity debug output", RMSG, getResult( output ) ); bcd.debug( MSG ); assertEquals( "Additivity debug output", RMSG, getResult( output ) ); b.setAdditivity( true ); b.debug( MSG ); assertEquals( "Additivity debug output", RMSG, getResult( output ) ); bc.debug( MSG ); assertEquals( "Additivity debug output", RMSG, getResult( output ) ); bcd.debug( MSG ); assertEquals( "Additivity debug output", RMSG, getResult( output ) ); bc.setAdditivity( true ); b.debug( MSG ); assertEquals( "Additivity debug output", RMSG, getResult( output ) ); bc.debug( MSG ); assertEquals( "Additivity debug output", RMSG + RMSG, getResult( output ) ); bcd.debug( MSG ); assertEquals( "Additivity debug output", RMSG, getResult( output ) ); bcd.setAdditivity( true ); b.debug( MSG ); assertEquals( "Additivity debug output", RMSG, getResult( output ) ); bc.debug( MSG ); assertEquals( "Additivity debug output", RMSG + RMSG, getResult( output ) ); bcd.debug( MSG ); assertEquals( "Additivity debug output", RMSG + RMSG + RMSG, getResult( output ) ); bcd.setAdditivity( false ); b.debug( MSG ); assertEquals( "Additivity debug output", RMSG, getResult( output ) ); bc.debug( MSG ); assertEquals( "Additivity debug output", RMSG + RMSG, getResult( output ) ); bcd.debug( MSG ); assertEquals( "Additivity debug output", RMSG, getResult( output ) ); bc.setAdditivity( false ); b.debug( MSG ); assertEquals( "Additivity debug output", RMSG, getResult( output ) ); bc.debug( MSG ); assertEquals( "Additivity debug output", RMSG, getResult( output ) ); bcd.debug( MSG ); assertEquals( "Additivity debug output", RMSG, getResult( output ) ); b.setAdditivity( false ); b.debug( MSG ); assertEquals( "Additivity debug output", RMSG, getResult( output ) ); bc.debug( MSG ); assertEquals( "Additivity debug output", RMSG, getResult( output ) ); bcd.debug( MSG ); assertEquals( "Additivity debug output", RMSG, getResult( output ) ); } public void testChainedAdditivity() throws Exception { final Hierarchy hierarchy = new Hierarchy(); final ByteArrayOutputStream output1 = new ByteArrayOutputStream(); final ByteArrayOutputStream output2 = new ByteArrayOutputStream(); final StreamTarget target1 = new StreamTarget( output1, FORMATTER ); final StreamTarget target2 = new StreamTarget( output2, FORMATTER ); final LogTarget[] targets1 = new LogTarget[]{target1}; final LogTarget[] targets2 = new LogTarget[]{target2}; final Logger b = hierarchy.getLoggerFor( "b" ); final Logger bc = hierarchy.getLoggerFor( "b.c" ); final Logger bcd = hierarchy.getLoggerFor( "b.c.d" ); b.setLogTargets( targets1 ); bc.setLogTargets( targets2 ); bc.setAdditivity( true ); bcd.setAdditivity( true ); b.debug( MSG ); assertEquals( "Additivity debug output1", RMSG, getResult( output1 ) ); bc.debug( MSG ); assertEquals( "Additivity debug output1", RMSG, getResult( output1 ) ); assertEquals( "Additivity debug output2", RMSG, getResult( output2 ) ); bcd.debug( MSG ); assertEquals( "Additivity debug output1", RMSG, getResult( output1 ) ); assertEquals( "Additivity debug output2", RMSG, getResult( output2 ) ); } } avalon-logkit-2.0.dev-0/src/test/org/apache/log/test/LoggerListenerTestCase.java100644 0 0 5576 10036267317 24747 0ustar 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.log.test; import junit.framework.TestCase; import org.apache.log.Hierarchy; import org.apache.log.Logger; /** * Test suite for logger listener features of Logger. * * @author Peter Donald */ public final class LoggerListenerTestCase extends TestCase { public LoggerListenerTestCase( final String name ) { super( name ); } public void testUnicastLoggerListener() { final Hierarchy hierarchy = new Hierarchy(); final RecordingLoggerListener listener = new RecordingLoggerListener(); try { hierarchy.addLoggerListener( listener ); hierarchy.addLoggerListener( listener ); fail( "You should only be able to add one listener." ); } catch (UnsupportedOperationException uoe) { // It passed, yay! } } public void testRemoveLoggerListener() { final Hierarchy hierarchy = new Hierarchy(); final RecordingLoggerListener listener = new RecordingLoggerListener(); hierarchy.addLoggerListener( listener ); hierarchy.removeLoggerListener( listener ); hierarchy.addLoggerListener( listener ); // If no exceptions have been thrown, we are in business! } public void testPriorityInheritance() throws Exception { final RecordingLoggerListener listener = new RecordingLoggerListener(); final Hierarchy hierarchy = new Hierarchy(); hierarchy.addLoggerListener( listener ); final Logger root = hierarchy.getRootLogger(); final Logger l1 = root.getChildLogger( "logger1" ); final Logger l2 = root.getChildLogger( "logger2" ); final Logger l3 = root.getChildLogger( "logger1.logger3" ); final Logger l4 = root.getChildLogger( "logger5.logger4" ); final Logger l5 = root.getChildLogger( "logger5" ); final Logger[] loggers = listener.getLoggers(); assertEquals( "Logger Count", 5, loggers.length ); assertEquals( "Logger[0]", l1, loggers[ 0 ] ); assertEquals( "Logger[1]", l2, loggers[ 1 ] ); assertEquals( "Logger[2]", l3, loggers[ 2 ] ); assertEquals( "Logger[3]", l5, loggers[ 3 ] ); assertEquals( "Logger[4]", l4, loggers[ 4 ] ); } } avalon-logkit-2.0.dev-0/src/sql/basic.sql100644 0 0 1602 10036267317 15357 0ustar 0 0 CREATE TABLE LOG_ENTRYS ( TIME DATETIME NOT NULL, PRIORITY VARCHAR(10) NOT NULL, CATEGORY VARCHAR(64) NOT NULL, MESSAGE VARCHAR(255) NOT NULL, THROWABLE VARCHAR(255), HOSTNAME VARCHAR(255) ); DROP TABLE LOG_ENTRYS2; DROP TABLE LOG_ENTRYS2_PRIORITY_SET; DROP TABLE LOG_ENTRYS2_CATEGORY_SET; CREATE TABLE LOG_ENTRYS2_PRIORITY_SET ( ID INT PRIMARY KEY, NAME VARCHAR(255) NOT NULL ); CREATE TABLE LOG_ENTRYS2_CATEGORY_SET ( ID INT PRIMARY KEY, NAME VARCHAR(255) NOT NULL ); CREATE TABLE LOG_ENTRYS2 ( TIME DATETIME NOT NULL, PRIORITY INT NOT NULL REFERENCES LOG_ENTRYS2_PRIORITY_SET(ID), CATEGORY INT NOT NULL REFERENCES LOG_ENTRYS2_CATEGORY_SET(ID), MESSAGE VARCHAR(255) NOT NULL, THROWABLE VARCHAR(255), HOSTNAME VARCHAR(255) ); t( output, FORMATTER ); final LogTarget[] targets = new LogTarget[]{target}; final Logger b = hierarchy.getLoggerFor( "b" ); final Logger bc = hierarchy.getLoggerFor( "b.c" ); final Logger bcd = hierarchy.getLoggerFor( "b.c.d" ); b.setLogTargets( targets ); bc.setLogTargets( targets ); bcd.setLogTargets( targets ); b.debug( MSG ); assertEquals( "Additivity debug output", RMSG, getResult( output ) ); bc.debug( MSG ); assertEquals( "Additivity debug output", RMSG, getResult( output ) ); bcd.debug( MSG ); assertEquals( "Additivity debug output", RMSG, getResult( output ) ); b.setAdditivity( true ); b.debug( MSG ); assertEquals( "Additivity debug output", RMSG, getResult( output ) ); bc.debug( MSG ); assertEquals( "Additivity debug output", RMSG, getResult( output ) ); bcd.debug( MSG ); assertEquals( "Additivity debug output", RMSG, getResult( output ) ); bc.setAdditivity( true ); b.debug( MSG ); assertEquals( "Additivity debug output", RMSG, getResult( output ) ); bc.debug( MSG ); assertEquals( "Additivity debug output", RMSG + RMSG, getResult( output ) ); bcd.debug( MSG ); assertEquals( "Additivity debug output", RMSG, getResult( output ) ); bcd.setAdditivity( true ); b.debug( MSG ); assertEquals( "Additivity debug output", RMSG, getResult( output ) ); bc.debug( M