pax_global_header00006660000000000000000000000064125274276420014525gustar00rootroot0000000000000052 comment=39cc12afcca44575ba6f0689b92f66e777adc574 apache-log4j-extras1.2-1.2.17/000077500000000000000000000000001252742764200156005ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/LICENSE000066400000000000000000000261461252742764200166160ustar00rootroot00000000000000 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. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 1999-2005 The Apache Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. apache-log4j-extras1.2-1.2.17/NOTICE000066400000000000000000000002731252742764200165060ustar00rootroot00000000000000Apache Extras Companion for log4j 1.2. Copyright 2010 The Apache Software Foundation This product includes software developed at The Apache Software Foundation (http://www.apache.org/). apache-log4j-extras1.2-1.2.17/pom.xml000066400000000000000000000334021252742764200171170ustar00rootroot00000000000000 4.0.0 org.apache apache 13 log4j apache-log4j-extras bundle 1.2.17 Apache Extras™ for Apache log4j™. This package provides additional appenders, filters and other capabilities for version 1.2 of Apache log4j™. Several of these were backported from the abandoned Apache log4j 1.3 development effort. http://logging.apache.org/log4j/extras Bugzilla https://issues.apache.org/bugzilla/buglist.cgi?product=Log4j&component=Companions Gump http://vmgump.apache.org/gump/public/logging-log4j-extras/logging-log4j-extras/index.html log4j-user log4j-user-subscribe@logging.apache.org log4j-user-unsubscribe@logging.apache.org log4j-user@logging.apache.org http://mail-archives.apache.org/mod_mbox/logging-log4j-user/ http://marc.theaimsgroup.com/?l=log4j-user&r=1&w=2 http://dir.gmane.org/gmane.comp.jakarta.log4j.user log4j-dev log4j-dev-subscribe@logging.apache.org log4j-dev-unsubscribe@logging.apache.org log4j-dev@logging.apache.org http://mail-archives.apache.org/mod_mbox/logging-log4j-dev/ http://marc.theaimsgroup.com/?l=log4j-dev&r=1&w=2 http://dir.gmane.org/gmane.comp.jakarta.log4j.devel scm:svn:http://svn.apache.org/repos/asf/logging/log4j/companions/extras/tags/apache-log4j-extras-1.2.17 scm:svn:https://svn.apache.org/repos/asf/logging/log4j/companions/extras/tags/apache-log4j-extras-1.2.17 http://svn.apache.org/viewcvs.cgi/logging/log4j/companions/extras/tags/apache-log4j-extras-1.2.17 maven-compiler-plugin 1.4 1.4 UTF-8 org.apache.rat apache-rat-plugin 0.8 src/test/resources/org/apache/log4j/**/*.log src/test/resources/org/apache/log4j/**/*.null src/test/resources/org/apache/log4j/**/*.throwable src/test/resources/org/apache/log4j/**/*.0 src/test/resources/org/apache/log4j/**/*.1 src/test/resources/org/apache/log4j/**/*.2 src/test/resources/org/apache/log4j/**/*.3 src/test/resources/org/apache/log4j/**/*.4 src/test/resources/org/apache/log4j/**/*.5 src/test/resources/org/apache/log4j/**/*.6 src/test/resources/org/apache/log4j/**/*.7 src/test/resources/org/apache/log4j/**/*.8 src/test/resources/org/apache/log4j/**/*.9 src/test/resources/org/apache/log4j/**/*.9 src/test/resources/org/apache/log4j/**/*.10 src/test/resources/org/apache/log4j/**/*.11 src/test/resources/org/apache/log4j/**/*.12 src/test/resources/org/apache/log4j/**/*.13 src/test/resources/org/apache/log4j/**/*.14 src/test/resources/org/apache/log4j/**/*.15 src/test/resources/org/apache/log4j/**/*.17 site/**/*-frame.html site/**/*-summary.html site/xref*/index.html site/pmd.xml site/cpd.xml site/apidocs/**/* site/testapidocs/**/* site/css/maven-theme.css org.apache.maven.plugins maven-resources-plugin UTF-8 maven-site-plugin 3.0 org.apache.maven.wagon wagon-ssh 2.2 ${basedir}/src/site/maven-site.vm maven-project-info-reports-plugin 2.4 scm dependencies cim issue-tracking mailing-list maven-changes-plugin 2.8 changes-report %URL%/show_bug.cgi?id=%ISSUE% maven-pmd-plugin 2.7.1 UTF-8 maven-javadoc-plugin UTF-8 Copyright ]]>© {currentYear} The Apache Software Foundation. Licensed under the Apache License, Version 2.0

Apache Extras for Apache log4j, Apache log4j and Apache are trademarks of the Apache Software Foundation.

]]>
org.apache.rat apache-rat-plugin 0.8 src/test/resources/org/apache/log4j/**/*.log src/test/resources/org/apache/log4j/**/*.null src/test/resources/org/apache/log4j/**/*.throwable src/test/resources/org/apache/log4j/**/*.0 src/test/resources/org/apache/log4j/**/*.1 src/test/resources/org/apache/log4j/**/*.2 src/test/resources/org/apache/log4j/**/*.3 src/test/resources/org/apache/log4j/**/*.4 src/test/resources/org/apache/log4j/**/*.5 src/test/resources/org/apache/log4j/**/*.6 src/test/resources/org/apache/log4j/**/*.7 src/test/resources/org/apache/log4j/**/*.8 src/test/resources/org/apache/log4j/**/*.9 src/test/resources/org/apache/log4j/**/*.9 src/test/resources/org/apache/log4j/**/*.10 src/test/resources/org/apache/log4j/**/*.11 src/test/resources/org/apache/log4j/**/*.12 src/test/resources/org/apache/log4j/**/*.13 src/test/resources/org/apache/log4j/**/*.14 src/test/resources/org/apache/log4j/**/*.15 src/test/resources/org/apache/log4j/**/*.17 site/**/*-frame.html site/**/*-summary.html site/xref*/index.html site/pmd.xml site/cpd.xml site/apidocs/**/* site/testapidocs/**/* site/css/maven-theme.css
org.apache.felix maven-bundle-plugin 2.3.5 true org.apache.log4j.extras;version=1.1, org.apache.log4j.filter;version=1.1, org.apache.log4j.rolling;version=1.1, org.apache.log4j.rule;version=1.1 !com.ibm.uvm.tools.*,* http://logging.apache.org/log4j/extras/index.html maven-assembly-plugin 2.4 bin src make-assembly package single
log4j log4j 1.2.17 javax.jms jms com.sun.jdmk jmxtools com.sun.jmx jmxri mail javax.mail junit junit 3.8.1 test hsqldb hsqldb 1.8.0.7 test org.apache.geronimo.specs geronimo-jms_1.1_spec 1.0 true apache.website scp://people.apache.org/www/logging.apache.org/log4j/extras
apache-log4j-extras1.2-1.2.17/src/000077500000000000000000000000001252742764200163675ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/changes/000077500000000000000000000000001252742764200177775ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/changes/changes.xml000066400000000000000000000123121252742764200221300ustar00rootroot00000000000000 apache-log4j-extras RollingFileAppender with TimeBasedRolling policy doesn't create parent-path if FileNamePattern contains date pattern as directory (thanks to Daniel Stankiewicz) DBAppender has a compile error (thanks to Antonio Petrelli) Prefixed FormattingInfo and PatternParser with Extras to avoid classloading conflict Fixed product naming Removed duplicated classes (thanks to Jess Holle for spotting it) Removed ant build Made tests writing to target folder Merged all companions into the extras companion Switched Parent to Apache parent Upgraded to Apache Maven 3 Mangled source-repository.html Extra NPE error message when using missing appender class with DOMConfigurator. Track changes of default timezone in EnhancedPatternLayout's %d conversion pattern. DOMConfigurator.configure(URL) fails on JRE 1.5.0_16. Misuse of "it's" in Javadoc for EnhancedPatternLayout. Leaving out %throwable in ConversionPattern adds throwable to logging message regardless. Unit tests fail for system dates after 2009-12-31 LogMF performance improvement for number and date types. LogSF did not support \\{ escape sequence. LogMF did not optimize simple patterns on multiple parameter log requests. EnhancedPatternLayout tests conflict with PatternLayout tests. Add %p{-2} pattern to EnhancedPatternLayout to drop two leading elements from name. Add %throwable{n} and {-n} pattern to EnhancedPatternLayout to print n or drop last n lines. Improve javadoc for LogMF, LogSF, LogXF CachedDateFormatTest fails on Apache Harmony. Unused imports and variables in test code cause gcj compile warnings. Add OSGi packaging info. DOMConfigurator does not close input stream when configured based on URL. javadoc.jar was missing NOTICE and LICENSE. Add right truncation modifier to EnhancedPatternLayout. Update for Apache Project Branding Requirements. Create an "extras" companion for log4j 1.2 Backport log4j 1.3 rolling file appender for use with log4j 1.2. ExpressionFilter backport. Add TimeFilter. Add XSLTLayout. Parameterized logging for log4j 1.2. FilterBasedTriggeringPolicy now usable with SMTPAppender. Avoid Turkish-i problem in ExpressionFilter. Enhance DOMConfigurator to delegate unrecognized elements to created objects. apache-log4j-extras1.2-1.2.17/src/main/000077500000000000000000000000001252742764200173135ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/assembly/000077500000000000000000000000001252742764200211325ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/assembly/bin.xml000066400000000000000000000024131252742764200224240ustar00rootroot00000000000000 bin zip tar.gz apache-log4j-extras-${project.version} LICENSE NOTICE target . apache-log4j-extras-${project.version}.jar apache-log4j-extras1.2-1.2.17/src/main/assembly/src.xml000066400000000000000000000022401252742764200224410ustar00rootroot00000000000000 src zip tar.gz apache-log4j-extras-${project.version} LICENSE NOTICE pom.xml src apache-log4j-extras1.2-1.2.17/src/main/java/000077500000000000000000000000001252742764200202345ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/000077500000000000000000000000001252742764200210235ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/000077500000000000000000000000001252742764200222445ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/000077500000000000000000000000001252742764200232635ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/DBAppender.java000066400000000000000000000342221252742764200260750ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.receivers.db.ConnectionSource; import org.apache.log4j.receivers.db.DBHelper; import org.apache.log4j.receivers.db.dialect.SQLDialect; import org.apache.log4j.receivers.db.dialect.Util; import org.apache.log4j.spi.LocationInfo; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.xml.DOMConfigurator; import org.apache.log4j.xml.UnrecognizedElementHandler; import org.w3c.dom.Element; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Iterator; import java.util.Properties; import java.util.Set; /** * The DBAppender inserts loggin events into three database tables in a format * independent of the Java programming language. The three tables that * DBAppender inserts to must exists before DBAppender can be used. These tables * may be created with the help of SQL scripts found in the * src/java/org/apache/log4j/db/dialect directory. There is a * specific script for each of the most popular database systems. If the script * for your particular type of database system is missing, it should be quite * easy to write one, taking example on the already existing scripts. If you * send them to us, we will gladly include missing scripts in future releases. * *

* If the JDBC driver you are using supports the * {@link java.sql.Statement#getGeneratedKeys}method introduced in JDBC 3.0 * specification, then you are all set. Otherwise, there must be an * {@link SQLDialect}appropriate for your database system. Currently, we have * dialects for PostgreSQL, MySQL, Oracle and MsSQL. As mentioed previously, an * SQLDialect is required only if the JDBC driver for your database system does * not support the {@link java.sql.Statement#getGeneratedKeys getGeneratedKeys} * method. *

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
RDBMSsupports
getGeneratedKeys() method
specific
SQLDialect support
PostgreSQLNOpresent and used
MySQLYESpresent, but not actually needed or used
OracleYESpresent, but not actually needed or used
DB2YESnot present, and not needed or used
MsSQLYESnot present, and not needed or used
HSQLNOpresent and used
*

* Performance: Experiments show that writing a single event into the * database takes approximately 50 milliseconds, on a "standard" PC. If pooled * connections are used, this figure drops to under 10 milliseconds. Note that * most JDBC drivers already ship with connection pooling support. *

* * * *

* Configuration DBAppender can be configured programmatically, or using * {@link org.apache.log4j.xml.DOMConfigurator JoranConfigurator}. Example * scripts can be found in the tests/input/db directory. * * @author Ceki Gülcü * @author Ray DeCampo */ public class DBAppender extends AppenderSkeleton implements UnrecognizedElementHandler { static final String insertPropertiesSQL = "INSERT INTO logging_event_property (event_id, mapped_key, mapped_value) VALUES (?, ?, ?)"; static final String insertExceptionSQL = "INSERT INTO logging_event_exception (event_id, i, trace_line) VALUES (?, ?, ?)"; static final String insertSQL; private static final Method GET_GENERATED_KEYS_METHOD; static { StringBuffer sql = new StringBuffer(); sql.append("INSERT INTO logging_event ("); sql.append("sequence_number, "); sql.append("timestamp, "); sql.append("rendered_message, "); sql.append("logger_name, "); sql.append("level_string, "); sql.append("ndc, "); sql.append("thread_name, "); sql.append("reference_flag, "); sql.append("caller_filename, "); sql.append("caller_class, "); sql.append("caller_method, "); sql.append("caller_line) "); sql.append(" VALUES (?, ?, ? ,?, ?, ?, ?, ?, ?, ?, ?, ?)"); insertSQL = sql.toString(); // // PreparedStatement.getGeneratedKeys added in JDK 1.4 // Method getGeneratedKeysMethod; try { getGeneratedKeysMethod = PreparedStatement.class.getMethod("getGeneratedKeys", null); } catch(Exception ex) { getGeneratedKeysMethod = null; } GET_GENERATED_KEYS_METHOD = getGeneratedKeysMethod; } ConnectionSource connectionSource; boolean cnxSupportsGetGeneratedKeys = false; boolean cnxSupportsBatchUpdates = false; SQLDialect sqlDialect; boolean locationInfo = false; public DBAppender() { super(false); } public void activateOptions() { LogLog.debug("DBAppender.activateOptions called"); if (connectionSource == null) { throw new IllegalStateException( "DBAppender cannot function without a connection source"); } sqlDialect = Util.getDialectFromCode(connectionSource.getSQLDialectCode()); if (GET_GENERATED_KEYS_METHOD != null) { cnxSupportsGetGeneratedKeys = connectionSource.supportsGetGeneratedKeys(); } else { cnxSupportsGetGeneratedKeys = false; } cnxSupportsBatchUpdates = connectionSource.supportsBatchUpdates(); if (!cnxSupportsGetGeneratedKeys && (sqlDialect == null)) { throw new IllegalStateException( "DBAppender cannot function if the JDBC driver does not support getGeneratedKeys method *and* without a specific SQL dialect"); } // all nice and dandy on the eastern front super.activateOptions(); } /** * @return Returns the connectionSource. */ public ConnectionSource getConnectionSource() { return connectionSource; } /** * @param connectionSource * The connectionSource to set. */ public void setConnectionSource(ConnectionSource connectionSource) { LogLog.debug("setConnectionSource called for DBAppender"); this.connectionSource = connectionSource; } protected void append(LoggingEvent event) { Connection connection = null; try { connection = connectionSource.getConnection(); connection.setAutoCommit(false); PreparedStatement insertStatement; if (cnxSupportsGetGeneratedKeys) { insertStatement = connection.prepareStatement(insertSQL, Statement.RETURN_GENERATED_KEYS); } else { insertStatement = connection.prepareStatement(insertSQL); } /* insertStatement.setLong(1, event.getSequenceNumber());*/ insertStatement.setLong(1, 0); insertStatement.setLong(2, event.getTimeStamp()); insertStatement.setString(3, event.getRenderedMessage()); insertStatement.setString(4, event.getLoggerName()); insertStatement.setString(5, event.getLevel().toString()); insertStatement.setString(6, event.getNDC()); insertStatement.setString(7, event.getThreadName()); insertStatement.setShort(8, DBHelper.computeReferenceMask(event)); LocationInfo li; if (event.locationInformationExists() || locationInfo) { li = event.getLocationInformation(); } else { li = LocationInfo.NA_LOCATION_INFO; } insertStatement.setString(9, li.getFileName()); insertStatement.setString(10, li.getClassName()); insertStatement.setString(11, li.getMethodName()); insertStatement.setString(12, li.getLineNumber()); int updateCount = insertStatement.executeUpdate(); if (updateCount != 1) { LogLog.warn("Failed to insert loggingEvent"); } ResultSet rs = null; Statement idStatement = null; boolean gotGeneratedKeys = false; if (cnxSupportsGetGeneratedKeys) { try { rs = (ResultSet) GET_GENERATED_KEYS_METHOD.invoke(insertStatement, null); gotGeneratedKeys = true; } catch(InvocationTargetException ex) { Throwable target = ex.getTargetException(); if (target instanceof SQLException) { throw (SQLException) target; } throw ex; } catch(IllegalAccessException ex) { LogLog.warn("IllegalAccessException invoking PreparedStatement.getGeneratedKeys", ex); } } if (!gotGeneratedKeys) { insertStatement.close(); insertStatement = null; idStatement = connection.createStatement(); idStatement.setMaxRows(1); rs = idStatement.executeQuery(sqlDialect.getSelectInsertId()); } // A ResultSet cursor is initially positioned before the first row; the // first call to the method next makes the first row the current row rs.next(); int eventId = rs.getInt(1); rs.close(); // we no longer need the insertStatement if(insertStatement != null) { insertStatement.close(); insertStatement = null; } if(idStatement != null) { idStatement.close(); idStatement = null; } Set propertiesKeys = event.getPropertyKeySet(); if (propertiesKeys.size() > 0) { PreparedStatement insertPropertiesStatement = connection.prepareStatement(insertPropertiesSQL); for (Iterator i = propertiesKeys.iterator(); i.hasNext();) { String key = (String) i.next(); String value = event.getProperty(key); //LogLog.info("id " + eventId + ", key " + key + ", value " + value); insertPropertiesStatement.setInt(1, eventId); insertPropertiesStatement.setString(2, key); insertPropertiesStatement.setString(3, value); if (cnxSupportsBatchUpdates) { insertPropertiesStatement.addBatch(); } else { insertPropertiesStatement.execute(); } } if (cnxSupportsBatchUpdates) { insertPropertiesStatement.executeBatch(); } insertPropertiesStatement.close(); insertPropertiesStatement = null; } String[] strRep = event.getThrowableStrRep(); if (strRep != null) { LogLog.debug("Logging an exception"); PreparedStatement insertExceptionStatement = connection.prepareStatement(insertExceptionSQL); for (short i = 0; i < strRep.length; i++) { insertExceptionStatement.setInt(1, eventId); insertExceptionStatement.setShort(2, i); insertExceptionStatement.setString(3, strRep[i]); if (cnxSupportsBatchUpdates) { insertExceptionStatement.addBatch(); } else { insertExceptionStatement.execute(); } } if (cnxSupportsBatchUpdates) { insertExceptionStatement.executeBatch(); } insertExceptionStatement.close(); insertExceptionStatement = null; } connection.commit(); } catch (Throwable sqle) { LogLog.error("problem appending event", sqle); } finally { DBHelper.closeConnection(connection); } } public void close() { closed = true; } /** * Returns value of the LocationInfo property which determines whether * caller's location info is written to the database. */ public boolean getLocationInfo() { return locationInfo; } /** * If true, the information written to the database will include caller's * location information. Due to performance concerns, by default no location * information is written to the database. */ public void setLocationInfo(boolean locationInfo) { this.locationInfo = locationInfo; } /** * Gets whether appender requires a layout. * @return false */ public boolean requiresLayout() { return false; } /** * {@inheritDoc} */ public boolean parseUnrecognizedElement(Element element, Properties props) throws Exception { if ("connectionSource".equals(element.getNodeName())) { Object instance = DOMConfigurator.parseElement(element, props, ConnectionSource.class); if (instance instanceof ConnectionSource) { ConnectionSource source = (ConnectionSource) instance; source.activateOptions(); setConnectionSource(source); } return true; } return false; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/LoggerRepositoryExImpl.java000066400000000000000000000465761252742764200306060ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j; import org.apache.log4j.component.plugins.Plugin; import org.apache.log4j.component.plugins.PluginRegistry; import org.apache.log4j.component.scheduler.Scheduler; import org.apache.log4j.component.spi.ErrorItem; import org.apache.log4j.component.spi.LoggerEventListener; import org.apache.log4j.component.spi.LoggerRepositoryEventListener; import org.apache.log4j.component.spi.LoggerRepositoryEx; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.or.ObjectRenderer; import org.apache.log4j.or.RendererMap; import org.apache.log4j.spi.HierarchyEventListener; import org.apache.log4j.spi.LoggerFactory; import org.apache.log4j.spi.LoggerRepository; import org.apache.log4j.spi.RendererSupport; import org.apache.log4j.xml.DOMConfigurator; import org.apache.log4j.xml.UnrecognizedElementHandler; import org.w3c.dom.Element; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Vector; /** * This class implements LoggerRepositoryEx by * wrapping an existing LoggerRepository implementation * and implementing the newly added capabilities. */ public final class LoggerRepositoryExImpl implements LoggerRepositoryEx, RendererSupport, UnrecognizedElementHandler { /** * Wrapped logger repository. */ private final LoggerRepository repo; /** * Logger factory. Does not affect class of logger * created by underlying repository. */ private LoggerFactory loggerFactory; /** * Renderer support. */ private final RendererSupport rendererSupport; /** * List of repository event listeners. */ private final ArrayList repositoryEventListeners = new ArrayList(); /** * Map of HierarchyEventListener keyed by LoggingEventListener. */ private final Map loggerEventListeners = new HashMap(); /** * Name of hierarchy. */ private String name; /** * Plug in registry. */ private PluginRegistry pluginRegistry; /** * Properties. */ private final Map properties = new Hashtable(); /** * Scheduler. */ private Scheduler scheduler; /** The repository can also be used as an object store * for various objects used by log4j components. */ private Map objectMap = new HashMap(); /** * Error list. */ private List errorList = new Vector(); /** * True if hierarchy has not been modified. */ private boolean pristine = true; /** Constructs a new logger hierarchy. @param repository Base implementation of repository. */ public LoggerRepositoryExImpl(final LoggerRepository repository) { super(); if (repository == null) { throw new NullPointerException("repository"); } repo = repository; if (repository instanceof RendererSupport) { rendererSupport = (RendererSupport) repository; } else { rendererSupport = new RendererSupportImpl(); } } /** Add a {@link LoggerRepositoryEventListener} to the repository. The listener will be called when repository events occur. @param listener listener */ public void addLoggerRepositoryEventListener( final LoggerRepositoryEventListener listener) { synchronized (repositoryEventListeners) { if (repositoryEventListeners.contains(listener)) { LogLog.warn( "Ignoring attempt to add a previously " + "registered LoggerRepositoryEventListener."); } else { repositoryEventListeners.add(listener); } } } /** Remove a {@link LoggerRepositoryEventListener} from the repository. @param listener listener */ public void removeLoggerRepositoryEventListener( final LoggerRepositoryEventListener listener) { synchronized (repositoryEventListeners) { if (!repositoryEventListeners.contains(listener)) { LogLog.warn( "Ignoring attempt to remove a " + "non-registered LoggerRepositoryEventListener."); } else { repositoryEventListeners.remove(listener); } } } /** Add a {@link LoggerEventListener} to the repository. The listener will be called when repository events occur. @param listener listener */ public void addLoggerEventListener(final LoggerEventListener listener) { synchronized (loggerEventListeners) { if (loggerEventListeners.get(listener) != null) { LogLog.warn( "Ignoring attempt to add a previously registerd LoggerEventListener."); } else { HierarchyEventListenerProxy proxy = new HierarchyEventListenerProxy(listener); loggerEventListeners.put(listener, proxy); repo.addHierarchyEventListener(proxy); } } } /** Add a {@link org.apache.log4j.spi.HierarchyEventListener} event to the repository. @param listener listener @deprecated Superceded by addLoggerEventListener */ public void addHierarchyEventListener(final HierarchyEventListener listener) { repo.addHierarchyEventListener(listener); } /** Remove a {@link LoggerEventListener} from the repository. @param listener listener to be removed */ public void removeLoggerEventListener(final LoggerEventListener listener) { synchronized (loggerEventListeners) { HierarchyEventListenerProxy proxy = (HierarchyEventListenerProxy) loggerEventListeners.get(listener); if (proxy == null) { LogLog.warn( "Ignoring attempt to remove a non-registered LoggerEventListener."); } else { loggerEventListeners.remove(listener); proxy.disable(); } } } /** * Issue warning that there are no appenders in hierarchy. * @param cat logger, not currently used. */ public void emitNoAppenderWarning(final Category cat) { repo.emitNoAppenderWarning(cat); } /** Check if the named logger exists in the hierarchy. If so return its reference, otherwise returns null. @param loggerName The name of the logger to search for. @return true if logger exists. */ public Logger exists(final String loggerName) { return repo.exists(loggerName); } /** * Return the name of this hierarchy. * @return name of hierarchy */ public String getName() { return name; } /** * Set the name of this repository. * * Note that once named, a repository cannot be rerenamed. * @param repoName name of hierarchy */ public void setName(final String repoName) { if (name == null) { name = repoName; } else if (!name.equals(repoName)) { throw new IllegalStateException( "Repository [" + name + "] cannot be renamed as [" + repoName + "]."); } } /** * {@inheritDoc} */ public Map getProperties() { return properties; } /** * {@inheritDoc} */ public String getProperty(final String key) { return (String) properties.get(key); } /** * Set a property by key and value. The property will be shared by all * events in this repository. * @param key property name * @param value property value */ public void setProperty(final String key, final String value) { properties.put(key, value); } /** The string form of {@link #setThreshold(Level)}. @param levelStr symbolic name for level */ public void setThreshold(final String levelStr) { repo.setThreshold(levelStr); } /** Enable logging for logging requests with level l or higher. By default all levels are enabled. @param l The minimum level for which logging requests are sent to their appenders. */ public void setThreshold(final Level l) { repo.setThreshold(l); } /** * {@inheritDoc} */ public PluginRegistry getPluginRegistry() { if (pluginRegistry == null) { pluginRegistry = new PluginRegistry(this); } return pluginRegistry; } /** Requests that a appender added event be sent to any registered {@link LoggerEventListener}. @param logger The logger to which the appender was added. @param appender The appender added to the logger. */ public void fireAddAppenderEvent(final Category logger, final Appender appender) { repo.fireAddAppenderEvent(logger, appender); } /** Requests that a appender removed event be sent to any registered {@link LoggerEventListener}. @param logger The logger from which the appender was removed. @param appender The appender removed from the logger. */ public void fireRemoveAppenderEvent(final Category logger, final Appender appender) { if (repo instanceof Hierarchy) { ((Hierarchy) repo).fireRemoveAppenderEvent(logger, appender); } } /** Requests that a level changed event be sent to any registered {@link LoggerEventListener}. @param logger The logger which changed levels. */ public void fireLevelChangedEvent(final Logger logger) { } /** * * Requests that a configuration changed event be sent to any registered * {@link LoggerRepositoryEventListener}. * */ public void fireConfigurationChangedEvent() { } /** Returns the current threshold. @return current threshold level @since 1.2 */ public Level getThreshold() { return repo.getThreshold(); } /** Return a new logger instance named as the first parameter using the default factory.

If a logger of that name already exists, then it will be returned. Otherwise, a new logger will be instantiated and then linked with its existing ancestors as well as children. @param loggerName The name of the logger to retrieve. @return logger */ public Logger getLogger(final String loggerName) { return repo.getLogger(loggerName); } /** Return a new logger instance named as the first parameter using factory.

If a logger of that name already exists, then it will be returned. Otherwise, a new logger will be instantiated by the factory parameter and linked with its existing ancestors as well as children. @param loggerName The name of the logger to retrieve. @param factory The factory that will make the new logger instance. @return logger */ public Logger getLogger(final String loggerName, final LoggerFactory factory) { return repo.getLogger(loggerName, factory); } /** Returns all the currently defined categories in this hierarchy as an {@link java.util.Enumeration Enumeration}.

The root logger is not included in the returned {@link Enumeration}. @return enumerator of current loggers */ public Enumeration getCurrentLoggers() { return repo.getCurrentLoggers(); } /** * Return the the list of previously encoutered {@link org.apache.log4j.component.spi.ErrorItem error items}. * @return list of errors */ public List getErrorList() { return errorList; } /** * Add an error item to the list of previously encountered errors. * @param errorItem error to add to list of errors. */ public void addErrorItem(final ErrorItem errorItem) { getErrorList().add(errorItem); } /** * Get enumerator over current loggers. * @return enumerator over current loggers @deprecated Please use {@link #getCurrentLoggers} instead. */ public Enumeration getCurrentCategories() { return repo.getCurrentCategories(); } /** Get the renderer map for this hierarchy. @return renderer map */ public RendererMap getRendererMap() { return rendererSupport.getRendererMap(); } /** Get the root of this hierarchy. @since 0.9.0 @return root of hierarchy */ public Logger getRootLogger() { return repo.getRootLogger(); } /** This method will return true if this repository is disabled for level value passed as parameter and false otherwise. See also the {@link #setThreshold(Level) threshold} method. @param level numeric value for level. @return true if disabled for specified level */ public boolean isDisabled(final int level) { return repo.isDisabled(level); } /** Reset all values contained in this hierarchy instance to their default. This removes all appenders from all categories, sets the level of all non-root categories to null, sets their additivity flag to true and sets the level of the root logger to DEBUG. Moreover, message disabling is set its default "off" value.

Existing categories are not removed. They are just reset.

This method should be used sparingly and with care as it will block all logging until it is completed.

@since 0.8.5 */ public void resetConfiguration() { repo.resetConfiguration(); } /** Used by subclasses to add a renderer to the hierarchy passed as parameter. @param renderedClass class @param renderer object used to render class. */ public void setRenderer(final Class renderedClass, final ObjectRenderer renderer) { rendererSupport.setRenderer(renderedClass, renderer); } /** * {@inheritDoc} */ public boolean isPristine() { return pristine; } /** * {@inheritDoc} */ public void setPristine(final boolean state) { pristine = state; } /** Shutting down a hierarchy will safely close and remove all appenders in all categories including the root logger.

Some appenders such as org.apache.log4j.net.SocketAppender and AsyncAppender need to be closed before the application exists. Otherwise, pending logging events might be lost.

The shutdown method is careful to close nested appenders before closing regular appenders. This is allows configurations where a regular appender is attached to a logger and again to a nested appender. @since 1.0 */ public void shutdown() { repo.shutdown(); } /** * Return this repository's own scheduler. * The scheduler is lazily instantiated. * @return this repository's own scheduler. */ public Scheduler getScheduler() { if (scheduler == null) { scheduler = new Scheduler(); scheduler.setDaemon(true); scheduler.start(); } return scheduler; } /** * Puts object by key. * @param key key, may not be null. * @param value object to associate with key. */ public void putObject(final String key, final Object value) { objectMap.put(key, value); } /** * Get object by key. * @param key key, may not be null. * @return object associated with key or null. */ public Object getObject(final String key) { return objectMap.get(key); } /** * Set logger factory. * @param factory logger factory. */ public void setLoggerFactory(final LoggerFactory factory) { if (factory == null) { throw new NullPointerException(); } this.loggerFactory = factory; } /** * Get logger factory. * @return logger factory. */ public LoggerFactory getLoggerFactory() { return loggerFactory; } /** {@inheritDoc} */ public boolean parseUnrecognizedElement( final Element element, final Properties props) throws Exception { if ("plugin".equals(element.getNodeName())) { Object instance = DOMConfigurator.parseElement(element, props, Plugin.class); if (instance instanceof Plugin) { Plugin plugin = (Plugin) instance; String pluginName = DOMConfigurator.subst(element.getAttribute("name"), props); if (pluginName.length() > 0) { plugin.setName(pluginName); } getPluginRegistry().addPlugin(plugin); plugin.setLoggerRepository(this); LogLog.debug("Pushing plugin on to the object stack."); plugin.activateOptions(); return true; } } return false; } /** * Implementation of RendererSupportImpl if not * provided by LoggerRepository. */ private static final class RendererSupportImpl implements RendererSupport { /** * Renderer map. */ private final RendererMap renderers = new RendererMap(); /** * Create new instance. */ public RendererSupportImpl() { super(); } /** {@inheritDoc} */ public RendererMap getRendererMap() { return renderers; } /** {@inheritDoc} */ public void setRenderer(final Class renderedClass, final ObjectRenderer renderer) { renderers.put(renderedClass, renderer); } } /** * Proxy that implements HierarchyEventListener * and delegates to LoggerEventListener. */ private static final class HierarchyEventListenerProxy implements HierarchyEventListener { /** * Wrapper listener. */ private LoggerEventListener listener; /** * Creates new instance. * @param l listener */ public HierarchyEventListenerProxy(final LoggerEventListener l) { super(); if (l == null) { throw new NullPointerException("l"); } listener = l; } /** {@inheritDoc} */ public void addAppenderEvent(final Category cat, final Appender appender) { if (isEnabled() && cat instanceof Logger) { listener.appenderAddedEvent((Logger) cat, appender); } } /** {@inheritDoc} */ public void removeAppenderEvent(final Category cat, final Appender appender) { if (isEnabled() && cat instanceof Logger) { listener.appenderRemovedEvent((Logger) cat, appender); } } /** * Disable forwarding of notifications to * simulate removal of listener. */ public synchronized void disable() { listener = null; } /** * Gets whether proxy is enabled. * @return true if proxy is enabled. */ private synchronized boolean isEnabled() { return listener != null; } } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/component/000077500000000000000000000000001252742764200252655ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/component/ULogger.java000066400000000000000000000153601252742764200275010ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.component; /** * A proxy for org.slf4j.ULogger. In slf4j implementing builds, this * interface will extend org.slf4j.ULogger and add no additional methods. * * @author Ceki Gülcü * @author Curt Arnold */ public interface ULogger { /** * Is the logger instance enabled for the DEBUG level? * @return true if debug is enabled. */ boolean isDebugEnabled(); /** * Log a message object with the DEBUG level. * @param msg - the message object to be logged */ void debug(Object msg); /** * Log a parameterized message object at the DEBUG level. * *

This form is useful in avoiding the superflous object creation * problem when invoking this method while it is disabled. *

* @param parameterizedMsg - the parameterized message object * @param param1 - the parameter */ void debug(Object parameterizedMsg, Object param1); /** * Log a parameterized message object at the DEBUG level. * *

This form is useful in avoiding the superflous object creation * problem when invoking this method while it is disabled. *

* @param parameterizedMsg - the parameterized message object * @param param1 - the first parameter * @param param2 - the second parameter */ void debug(String parameterizedMsg, Object param1, Object param2); /** * Log a message object with the DEBUG level including the * stack trace of the {@link Throwable}t passed as parameter. * * * @param msg the message object to log. * @param t the exception to log, including its stack trace. */ void debug(Object msg, Throwable t); /** * Is the logger instance enabled for the INFO level? * @return true if debug is enabled. */ boolean isInfoEnabled(); /** * Log a message object with the INFO level. * @param msg - the message object to be logged */ void info(Object msg); /** * Log a parameterized message object at the INFO level. * *

This form is useful in avoiding the superflous object creation * problem when invoking this method while it is disabled. *

* @param parameterizedMsg - the parameterized message object * @param param1 - the parameter */ void info(Object parameterizedMsg, Object param1); /** * Log a parameterized message object at the INFO level. * *

This form is useful in avoiding the superflous object creation * problem when invoking this method while it is disabled. *

* @param parameterizedMsg - the parameterized message object * @param param1 - the first parameter * @param param2 - the second parameter */ void info(String parameterizedMsg, Object param1, Object param2); /** * Log a message object with the INFO level including the * stack trace of the {@link Throwable}t passed as parameter. * * * @param msg the message object to log. * @param t the exception to log, including its stack trace. */ void info(Object msg, Throwable t); /** * Is the logger instance enabled for the WARN level? * @return true if debug is enabled. */ boolean isWarnEnabled(); /** * Log a message object with the WARN level. * @param msg - the message object to be logged */ void warn(Object msg); /** * Log a parameterized message object at the WARN level. * *

This form is useful in avoiding the superflous object creation * problem when invoking this method while it is disabled. *

* @param parameterizedMsg - the parameterized message object * @param param1 - the parameter */ void warn(Object parameterizedMsg, Object param1); /** * Log a parameterized message object at the WARN level. * *

This form is useful in avoiding the superflous object creation * problem when invoking this method while it is disabled. *

* @param parameterizedMsg - the parameterized message object * @param param1 - the first parameter * @param param2 - the second parameter */ void warn(String parameterizedMsg, Object param1, Object param2); /** * Log a message object with the WARN level including the * stack trace of the {@link Throwable}t passed as parameter. * * * @param msg the message object to log. * @param t the exception to log, including its stack trace. */ void warn(Object msg, Throwable t); /** * Is the logger instance enabled for the ERROR level? * @return true if debug is enabled. */ boolean isErrorEnabled(); /** * Log a message object with the ERROR level. * @param msg - the message object to be logged */ void error(Object msg); /** * Log a parameterized message object at the ERROR level. * *

This form is useful in avoiding the superflous object creation * problem when invoking this method while it is disabled. *

* @param parameterizedMsg - the parameterized message object * @param param1 - the parameter */ void error(Object parameterizedMsg, Object param1); /** * Log a parameterized message object at the ERROR level. * *

This form is useful in avoiding the superflous object creation * problem when invoking this method while it is disabled. *

* @param parameterizedMsg - the parameterized message object * @param param1 - the first parameter * @param param2 - the second parameter */ void error(String parameterizedMsg, Object param1, Object param2); /** * Log a message object with the ERROR level including the * stack trace of the {@link Throwable}t passed as parameter. * * * @param msg the message object to log. * @param t the exception to log, including its stack trace. */ void error(Object msg, Throwable t); } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/component/helpers/000077500000000000000000000000001252742764200267275ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/component/helpers/Constants.java000066400000000000000000000066161252742764200315570ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.component.helpers; /** * Constants used internally throughout log4j. * */ public interface Constants { /** * log4j package name string literal. */ String LOG4J_PACKAGE_NAME = "org.apache.log4j"; /** * The name of the default repository is "default" (without the quotes). */ String DEFAULT_REPOSITORY_NAME = "default"; /** * application string literal. */ String APPLICATION_KEY = "application"; /** * hostname string literal. */ String HOSTNAME_KEY = "hostname"; /** * receiver string literal. */ String RECEIVER_NAME_KEY = "receiver"; /** * log4jid string literal. */ String LOG4J_ID_KEY = "log4jid"; /** * time stamp pattern string literal. */ String TIMESTAMP_RULE_FORMAT = "yyyy/MM/dd HH:mm:ss"; /** * The default property file name for automatic configuration. */ String DEFAULT_CONFIGURATION_FILE = "log4j.properties"; /** * The default XML configuration file name for automatic configuration. */ String DEFAULT_XML_CONFIGURATION_FILE = "log4j.xml"; /** * log4j.configuration string literal. */ String DEFAULT_CONFIGURATION_KEY = "log4j.configuration"; /** * log4j.configuratorClass string literal. */ String CONFIGURATOR_CLASS_KEY = "log4j.configuratorClass"; /** * JNDI context name string literal. */ String JNDI_CONTEXT_NAME = "java:comp/env/log4j/context-name"; /** * TEMP_LIST_APPENDER string literal. */ String TEMP_LIST_APPENDER_NAME = "TEMP_LIST_APPENDER"; /** * TEMP_CONSOLE_APPENDER string literal. */ String TEMP_CONSOLE_APPENDER_NAME = "TEMP_CONSOLE_APPENDER"; /** * Codes URL string literal. */ String CODES_HREF = "http://logging.apache.org/log4j/docs/codes.html"; /** * ABSOLUTE string literal. */ String ABSOLUTE_FORMAT = "ABSOLUTE"; /** * SimpleTimePattern for ABSOLUTE. */ String ABSOLUTE_TIME_PATTERN = "HH:mm:ss,SSS"; /** * SimpleTimePattern for ABSOLUTE. */ String SIMPLE_TIME_PATTERN = "HH:mm:ss"; /** * DATE string literal. */ String DATE_AND_TIME_FORMAT = "DATE"; /** * SimpleTimePattern for DATE. */ String DATE_AND_TIME_PATTERN = "dd MMM yyyy HH:mm:ss,SSS"; /** * ISO8601 string literal. */ String ISO8601_FORMAT = "ISO8601"; /** * SimpleTimePattern for ISO8601. */ String ISO8601_PATTERN = "yyyy-MM-dd HH:mm:ss,SSS"; } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/component/helpers/MessageFormatter.java000066400000000000000000000131431252742764200330440ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.component.helpers; /** * Formats messages according to very simple rules. * See {@link #format(String,Object)} and * {@link #format(String,Object,Object)} for more details. * * @author Ceki Gülcü */ public final class MessageFormatter { /** * Private formatter since all methods and members are static. */ private MessageFormatter() { super(); } /** * Start of replacement block. */ private static final char DELIM_START = '{'; /** * End of replacement block. */ private static final char DELIM_STOP = '}'; /** * Performs single argument substitution for the 'messagePattern' passed as * parameter. *

* For example, MessageFormatter.format("Hi {}.", "there"); * will return the string "Hi there.". *

* The {} pair is called the formatting element. It serves to designate the * location where the argument needs to be inserted within the pattern. * * @param messagePattern * The message pattern which will be parsed and formatted * @param argument * The argument to be inserted instead of the formatting element * @return The formatted message */ public static String format(final String messagePattern, final Object argument) { int j = messagePattern.indexOf(DELIM_START); int len = messagePattern.length(); char escape = 'x'; // if there are no { characters or { is the last character // then we just return messagePattern if (j == -1 || (j + 1 == len)) { return messagePattern; } else { char delimStop = messagePattern.charAt(j + 1); if (j > 0) { escape = messagePattern.charAt(j - 1); } if ((delimStop != DELIM_STOP) || (escape == '\\')) { // invalid DELIM_START/DELIM_STOP pair or espace character is // present return messagePattern; } else { StringBuffer sbuf = new StringBuffer(len + 20); sbuf.append(messagePattern.substring(0, j)); sbuf.append(argument); sbuf.append(messagePattern.substring(j + 2)); return sbuf.toString(); } } } /** * /** * Performs a two argument substitution for the 'messagePattern' passed as * parameter. *

* For example, MessageFormatter.format("Hi {}. My name is {}.", * "there", "David"); will return the string * "Hi there. My name is David.". *

* The '{}' pair is called a formatting element. It serves to designate the * location where the arguments need to be inserted within * the message pattern. * * @param messagePattern * The message pattern which will be parsed and formatted * @param arg1 * The first argument to replace the first formatting element * @param arg2 * The second argument to replace the second formatting element * @return The formatted message */ public static String format(final String messagePattern, final Object arg1, final Object arg2) { int i = 0; int len = messagePattern.length(); StringBuffer sbuf = new StringBuffer(messagePattern.length() + 50); for (int l = 0; l < 2; l++) { int j = messagePattern.indexOf(DELIM_START, i); if (j == -1 || (j + 1 == len)) { // no more variables if (i == 0) { // this is a simple string return messagePattern; } else { // add the tail string which contains no variables // and return the result. sbuf.append(messagePattern.substring(i, messagePattern.length())); return sbuf.toString(); } } else { char delimStop = messagePattern.charAt(j + 1); if ((delimStop != DELIM_STOP)) { // invalid DELIM_START/DELIM_STOP pair sbuf.append(messagePattern.substring(i, messagePattern.length())); return sbuf.toString(); } sbuf.append(messagePattern.substring(i, j)); if (l == 0) { sbuf.append(arg1); } else { sbuf.append(arg2); } i = j + 2; } } // append the characters following the second {} pair. sbuf.append(messagePattern.substring(i, messagePattern.length())); return sbuf.toString(); } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/component/plugins/000077500000000000000000000000001252742764200267465ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/component/plugins/Pauseable.java000066400000000000000000000022531252742764200315140ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.component.plugins; /** * Instances of this interface can be paused, and resumed. * * @author Paul Smith (psmith@apache.org) * */ public interface Pauseable { /** * Set paused state. * @param paused new value */ void setPaused(boolean paused); /** * Get paused state. * @return paused state. */ boolean isPaused(); } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/component/plugins/Plugin.java000066400000000000000000000117321252742764200310530ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.component.plugins; import org.apache.log4j.spi.LoggerRepository; import org.apache.log4j.spi.OptionHandler; import java.beans.PropertyChangeListener; /** * Defines the required interface for all Plugin objects. *

*

A plugin implements some specific functionality to extend * the log4j framework. Each plugin is associated with a specific * LoggerRepository, which it then uses/acts upon. The functionality * of the plugin is up to the developer. *

*

Examples of plugins are Receiver and Watchdog. Receiver plugins * allow for remote logging events to be received and processed by * a repository as if the event was sent locally. Watchdog plugins * allow for a repository to be reconfigured when some "watched" * configuration data changes. * * @author Mark Womack (mwomack@apache.org) * @author Nicko Cadell * @author Paul Smith (psmith@apache.org) */ public interface Plugin extends OptionHandler { /** * Gets the name of the plugin. * * @return String the name of the plugin. */ String getName(); /** * Sets the name of the plugin. * * @param name the name of the plugin. */ void setName(String name); /** * Gets the logger repository for this plugin. * * @return the logger repository to which this plugin is attached. */ LoggerRepository getLoggerRepository(); /** * Sets the logger repository used by this plugin. This * repository will be used by the plugin functionality. * * @param repository the logger repository to attach this plugin to. */ void setLoggerRepository(LoggerRepository repository); /** * Adds a PropertyChangeListener to this instance which is * notified only by changes of the property with name propertyName. * * @param propertyName * the name of the property in standard JavaBean syntax * (e.g. for setName(), property="name") * @param l listener */ void addPropertyChangeListener( String propertyName, PropertyChangeListener l); /** * Adds a PropertyChangeListener that will be notified of all property * changes. * * @param l The listener to add. */ void addPropertyChangeListener(PropertyChangeListener l); /** * Removes a specific PropertyChangeListener from this instances * registry that has been mapped to be notified of all property * changes. * * @param l The listener to remove. */ void removePropertyChangeListener(PropertyChangeListener l); /** * Removes a specific PropertyChangeListener from this instance's * registry which has been previously registered to be notified * of only a specific property change. * * @param propertyName property name, may not be null. * @param l listener to be removed. */ void removePropertyChangeListener( String propertyName, PropertyChangeListener l); /** * True if the plugin is active and running. * * @return boolean true if the plugin is currently active. */ boolean isActive(); /** * Returns true if the testPlugin is considered to be "equivalent" to the * this plugin. The equivalency test is at the discretion of the plugin * implementation. The PluginRegistry will use this method when starting * new plugins to see if a given plugin is considered equivalent to an * already running plugin with the same name. If they are considered to * be equivalent, the currently running plugin will be left in place, and * the new plugin will not be started. *

* It is possible to override the equals() method, however this has * more meaning than is required for this simple test and would also * require the overriding of the hashCode() method as well. All of this * is more work than is needed, so this simple method is used instead. * * @param testPlugin The plugin to test equivalency against. * @return Returns true if testPlugin is considered to be equivelent. */ boolean isEquivalent(Plugin testPlugin); /** * Call when the plugin should be stopped. */ void shutdown(); } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/component/plugins/PluginEvent.java000066400000000000000000000027471252742764200320630ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.component.plugins; import java.util.EventObject; /** * All Plugin events are encapsulated in this class, which * simply contains the source Plugin, but may in future include more * information. * * @author Paul Smith */ public class PluginEvent extends EventObject { /** * @param source The source plugin of the event */ PluginEvent(final Plugin source) { super(source); } /** * Returns the source Plugin of this event, which is simple * the getSource() method casted to Plugin for convenience. * * @return Plugin source of this event */ public Plugin getPlugin() { return (Plugin) getSource(); } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/component/plugins/PluginListener.java000066400000000000000000000024701252742764200325600ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.component.plugins; import java.util.EventListener; /** * PluginListeners are notified when plugins are started or stopped * by the PluginRegistry. * * @author Paul Smith (psmith@apache.org) */ public interface PluginListener extends EventListener { /** * Notification that plugin has started. * @param e event */ void pluginStarted(PluginEvent e); /** * Notification that plugin has stopped. * @param e event */ void pluginStopped(PluginEvent e); } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/component/plugins/PluginRegistry.java000066400000000000000000000214131252742764200326010ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.component.plugins; import org.apache.log4j.component.spi.LoggerRepositoryEventListener; import org.apache.log4j.component.spi.LoggerRepositoryEx; import org.apache.log4j.spi.LoggerRepository; import java.util.*; /** * This is a registry for Plugin instances. It provides methods to * start and stop plugin objects individually and to stop all * plugins for a repository. * * @author Mark Womack * @author Paul Smith */ public final class PluginRegistry { /** * The pluginMap is keyed by plugin name and contains plugins as values. * key=plugin.getName, value=plugin */ private final Map pluginMap; /** * Logger repository. */ private final LoggerRepositoryEx loggerRepository; /** * the listener used to listen for repository events. */ private final RepositoryListener listener = new RepositoryListener(); /** * List of listeners. */ private final List listenerList = Collections.synchronizedList(new ArrayList()); /** * Creates a new instance. * @param repository logger repository. */ public PluginRegistry(final LoggerRepositoryEx repository) { super(); pluginMap = new HashMap(); this.loggerRepository = repository; this.loggerRepository.addLoggerRepositoryEventListener(listener); } /** * Get logger repository. * @return logger repository. */ public LoggerRepositoryEx getLoggerRepository() { return loggerRepository; } /** * Returns true if the specified name is already taken by * an existing Plugin registered within the scope of the specified * LoggerRepository. * * @param name The name to check the repository for * @return true if the name is already in use, otherwise false */ public boolean pluginNameExists(final String name) { synchronized (pluginMap) { return pluginMap.containsKey(name); } } /** * Adds a plugin to the plugin registry. * If a plugin with the same name exists * already, it is shutdown and removed. * * @param plugin the plugin to add. */ public void addPlugin(final Plugin plugin) { // put plugin into the repository's reciever map synchronized (pluginMap) { String name = plugin.getName(); // make sure the plugin has reference to repository plugin.setLoggerRepository(getLoggerRepository()); Plugin existingPlugin = (Plugin) pluginMap.get(name); if (existingPlugin != null) { existingPlugin.shutdown(); } // put the new plugin into the map pluginMap.put(name, plugin); firePluginStarted(plugin); } } /** * Calls the pluginStarted method on every registered PluginListener. * * @param plugin The plugin that has been started. */ private void firePluginStarted(final Plugin plugin) { PluginEvent e = null; synchronized (listenerList) { for (Iterator iter = listenerList.iterator(); iter.hasNext();) { PluginListener l = (PluginListener) iter.next(); if (e == null) { e = new PluginEvent(plugin); } l.pluginStarted(e); } } } /** * Calls the pluginStopped method for every registered PluginListner. * * @param plugin The plugin that has been stopped. */ private void firePluginStopped(final Plugin plugin) { PluginEvent e = null; synchronized (listenerList) { for (Iterator iter = listenerList.iterator(); iter.hasNext();) { PluginListener l = (PluginListener) iter.next(); if (e == null) { e = new PluginEvent(plugin); } l.pluginStopped(e); } } } /** * Returns all the plugins for a given repository. * * @return List list of plugins from the repository. */ public List getPlugins() { synchronized (pluginMap) { List pluginList = new ArrayList(pluginMap.size()); Iterator iter = pluginMap.values().iterator(); while (iter.hasNext()) { pluginList.add(iter.next()); } return pluginList; } } /** * Returns all the plugins for a given repository that are instances * of a certain class. * * @param pluginClass the class the plugin must implement to be selected. * @return List list of plugins from the repository. */ public List getPlugins(final Class pluginClass) { synchronized (pluginMap) { List pluginList = new ArrayList(pluginMap.size()); Iterator iter = pluginMap.values().iterator(); while (iter.hasNext()) { Object plugin = iter.next(); if (pluginClass.isInstance(plugin)) { pluginList.add(plugin); } } return pluginList; } } /** * Stops a plugin by plugin name and repository. * * @param pluginName the name of the plugin to stop. * @return Plugin the plugin, if stopped, or null if the * the plugin was not found in the registry. */ public Plugin stopPlugin(final String pluginName) { synchronized (pluginMap) { Plugin plugin = (Plugin) pluginMap.get(pluginName); if (plugin == null) { return null; } // shutdown the plugin plugin.shutdown(); // remove it from the plugin map pluginMap.remove(pluginName); firePluginStopped(plugin); // return it for future use return plugin; } } /** * Stops all plugins in the given logger repository. */ public void stopAllPlugins() { synchronized (pluginMap) { // remove the listener for this repository loggerRepository.removeLoggerRepositoryEventListener(listener); Iterator iter = pluginMap.values().iterator(); while (iter.hasNext()) { Plugin plugin = (Plugin) iter.next(); plugin.shutdown(); firePluginStopped(plugin); } } } /** * Adds a PluginListener to this registry to be notified * of PluginEvents. * * @param l PluginListener to add to this registry */ public void addPluginListener(final PluginListener l) { listenerList.add(l); } /** * Removes a particular PluginListener from this registry * such that it will no longer be notified of PluginEvents. * * @param l PluginListener to remove */ public void removePluginListener(final PluginListener l) { listenerList.remove(l); } /** * Internal class used to handle listener events from repositories. */ private class RepositoryListener implements LoggerRepositoryEventListener { /** * Stops all plugins associated with the repository being reset. * * @param repository the repository that was reset. */ public void configurationResetEvent(final LoggerRepository repository) { PluginRegistry.this.stopAllPlugins(); } /** * Called when the repository configuration is changed. * * @param repository the repository that was changed. */ public void configurationChangedEvent( final LoggerRepository repository) { // do nothing with this event } /** * Stops all plugins associated with the repository being shutdown. * * @param repository the repository being shutdown. */ public void shutdownEvent(final LoggerRepository repository) { PluginRegistry.this.stopAllPlugins(); } } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/component/plugins/PluginSkeleton.java000066400000000000000000000156701252742764200325650ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.component.plugins; import org.apache.log4j.component.spi.ComponentBase; import org.apache.log4j.spi.LoggerRepository; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; /** * A convienent abstract class for plugin subclasses that implements * the basic methods of the Plugin interface. Subclasses are required * to implement the isActive(), activateOptions(), and shutdown() * methods. *

*

Developers are not required to subclass PluginSkeleton to * develop their own plugins (they are only required to implement the * Plugin interface), but it provides a convenient base class to start * from. *

* Contributors: Nicko Cadell * * @author Mark Womack (mwomack@apache.org) * @author Paul Smith (psmith@apache.org) */ public abstract class PluginSkeleton extends ComponentBase implements Plugin { /** * Name of this plugin. */ protected String name = "plugin"; /** * Active state of plugin. */ protected boolean active; /** * This is a delegate that does all the PropertyChangeListener * support. */ private PropertyChangeSupport propertySupport = new PropertyChangeSupport(this); /** * Construct new instance. */ protected PluginSkeleton() { super(); } /** * Gets the name of the plugin. * * @return String the name of the plugin. */ public String getName() { return name; } /** * Sets the name of the plugin and notifies * PropertyChangeListeners of the change. * * @param newName the name of the plugin to set. */ public void setName(final String newName) { String oldName = this.name; this.name = newName; propertySupport.firePropertyChange("name", oldName, this.name); } /** * Gets the logger repository for this plugin. * * @return LoggerRepository the logger repository this plugin will affect. */ public LoggerRepository getLoggerRepository() { return repository; } /** * Sets the logger repository used by this plugin and notifies a * relevant PropertyChangeListeners registered. This * repository will be used by the plugin functionality. * * @param repository the logger repository that this plugin should affect. */ public void setLoggerRepository(final LoggerRepository repository) { Object oldValue = this.repository; this.repository = repository; firePropertyChange("loggerRepository", oldValue, this.repository); } /** * Returns whether this plugin is Active or not. * * @return true/false */ public synchronized boolean isActive() { return active; } /** * Returns true if the plugin has the same name and logger repository as the * testPlugin passed in. * * @param testPlugin The plugin to test equivalency against. * @return Returns true if testPlugin is considered to be equivalent. */ public boolean isEquivalent(final Plugin testPlugin) { return (repository == testPlugin.getLoggerRepository()) && ((this.name == null && testPlugin.getName() == null) || (this.name != null && name.equals(testPlugin.getName()))) && this.getClass().equals(testPlugin.getClass()); } /** * Add property change listener. * @param listener listener. */ public final void addPropertyChangeListener( final PropertyChangeListener listener) { propertySupport.addPropertyChangeListener(listener); } /** * Add property change listener for one property only. * @param propertyName property name. * @param listener listener. */ public final void addPropertyChangeListener( final String propertyName, final PropertyChangeListener listener) { propertySupport.addPropertyChangeListener(propertyName, listener); } /** * Remove property change listener. * @param listener listener. */ public final void removePropertyChangeListener( final PropertyChangeListener listener) { propertySupport.removePropertyChangeListener(listener); } /** * Remove property change listener on a specific property. * @param propertyName property name. * @param listener listener. */ public final void removePropertyChangeListener( final String propertyName, final PropertyChangeListener listener) { propertySupport.removePropertyChangeListener(propertyName, listener); } /** * Fire a property change event to appropriate listeners. * @param evt change event. */ protected final void firePropertyChange( final PropertyChangeEvent evt) { propertySupport.firePropertyChange(evt); } /** * Fire property change event to appropriate listeners. * @param propertyName property name. * @param oldValue old value. * @param newValue new value. */ protected final void firePropertyChange( final String propertyName, final boolean oldValue, final boolean newValue) { propertySupport.firePropertyChange(propertyName, oldValue, newValue); } /** * Fire property change event to appropriate listeners. * @param propertyName property name. * @param oldValue old value. * @param newValue new value. */ protected final void firePropertyChange( final String propertyName, final int oldValue, final int newValue) { propertySupport.firePropertyChange(propertyName, oldValue, newValue); } /** * Fire property change event to appropriate listeners. * @param propertyName property name. * @param oldValue old value. * @param newValue new value. */ protected final void firePropertyChange( final String propertyName, final Object oldValue, final Object newValue) { propertySupport.firePropertyChange(propertyName, oldValue, newValue); } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/component/plugins/Receiver.java000066400000000000000000000111621252742764200313560ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.component.plugins; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.component.spi.Thresholdable; /** * Defines the base class for Receiver plugins. *

*

Just as Appenders send logging events outside of the log4j * environment (to files, to smtp, to sockets, etc), Receivers bring * logging events inside the log4j environment. *

*

Receivers are meant to support the receiving of * remote logging events from another process. For example, * SocketAppender "appends" a logging event to a socket, configured * for a specific host and port number. On the receiving side of * the socket can be a SocketReceiver object. The SocketReceiver * object receives the logging event, and then "posts" it to the * log4j environment (LoggerRepository) on the receiving machine, to * be handled by the configured appenders, etc. The various * settings in this environment (Logger levels, Appender filters & * thresholds) are applied to the received logging event. *

*

Receivers can also be used to "import" log messages from other * logging packages into the log4j environment. *

*

Receivers can be configured to post events to a given * LoggerRepository. *

*

Subclasses of Receiver must implement the isActive(), * activateOptions(), and shutdown() methods. The doPost() method * is provided to standardize the "import" of remote events into * the repository. * * @author Mark Womack * @author Ceki Gülcü * @author Paul Smith (psmith@apache.org) */ public abstract class Receiver extends PluginSkeleton implements Thresholdable { /** * Threshold level. */ protected Level thresholdLevel; /** * Create new instance. */ protected Receiver() { super(); } /** * Sets the receiver theshold to the given level. * * @param level The threshold level events must equal or be greater * than before further processing can be done. */ public void setThreshold(final Level level) { Level oldValue = this.thresholdLevel; thresholdLevel = level; firePropertyChange("threshold", oldValue, this.thresholdLevel); } /** * Gets the current threshold setting of the receiver. * * @return Level The current threshold level of the receiver. */ public Level getThreshold() { return thresholdLevel; } /** * Returns true if the given level is equals or greater than the current * threshold value of the receiver. * * @param level The level to test against the receiver threshold. * @return boolean True if level is equal or greater than the * receiver threshold. */ public boolean isAsSevereAsThreshold(final Level level) { return ((thresholdLevel == null) || level.isGreaterOrEqual(thresholdLevel)); } /** * Posts the logging event to a logger in the configured logger * repository. * * @param event the log event to post to the local log4j environment. */ public void doPost(final LoggingEvent event) { // if event does not meet threshold, exit now if (!isAsSevereAsThreshold(event.getLevel())) { return; } // get the "local" logger for this event from the // configured repository. Logger localLogger = getLoggerRepository().getLogger(event.getLoggerName()); // if the logger level is greater or equal to the level // of the event, use the logger to append the event. if (event.getLevel() .isGreaterOrEqual(localLogger.getEffectiveLevel())) { // call the loggers appenders to process the event localLogger.callAppenders(event); } } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/component/scheduler/000077500000000000000000000000001252742764200272435ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/component/scheduler/Job.java000066400000000000000000000023441252742764200306230ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.component.scheduler; /** * Job is a very simple interface. It only has a single method {@link #execute} * which is called by the {@link Scheduler} when a task is ready for execution. *

* It is assumed that the execution context * are contained within the implementing * {@link Job} itself. * * @author Ceki Gülcü */ public interface Job { /** * Execute job. */ void execute(); } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/component/scheduler/Scheduler.java000066400000000000000000000213611252742764200320270ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.component.scheduler; import java.util.List; import java.util.Vector; /** * A simple but still useful implementation of a Scheduler (in memory only). *

* This implementation will work very well when the number of scheduled job is * small, say less than 100 jobs. If a larger number of events need to be * scheduled, than a better adapted data structure for the jobList can give * improved performance. * * @author Ceki */ public class Scheduler extends Thread { /** * Job list. */ List jobList; /** * If set true, scheduler has or should shut down. */ boolean shutdown = false; /** * Create new instance. */ public Scheduler() { super(); jobList = new Vector(); } /** * Find the index of a given job. * @param job job * @return -1 if the job could not be found. */ int findIndex(final Job job) { int size = jobList.size(); boolean found = false; int i = 0; for (; i < size; i++) { ScheduledJobEntry se = (ScheduledJobEntry) jobList.get(i); if (se.job == job) { found = true; break; } } if (found) { return i; } else { return -1; } } /** * Delete the given job. * @param job job. * @return true if the job could be deleted, and * false if the job could not be found or if the Scheduler is about to * shutdown in which case deletions are not permitted. */ public synchronized boolean delete(final Job job) { // if already shutdown in the process of shutdown, there is no // need to remove Jobs as they will never be executed. if (shutdown) { return false; } int i = findIndex(job); if (i != -1) { ScheduledJobEntry se = (ScheduledJobEntry) jobList.remove(i); if (se.job != job) { // this should never happen new IllegalStateException("Internal programming error"); } // if the job is the first on the list, // then notify the scheduler thread to schedule a new job if (i == 0) { this.notifyAll(); } return true; } else { return false; } } /** * Schedule a {@link Job} for execution at system time given by * the desiredTime parameter. * @param job job to schedule. * @param desiredTime desired time of execution. */ public synchronized void schedule(final Job job, final long desiredTime) { schedule(new ScheduledJobEntry(job, desiredTime)); } /** * Schedule a {@link Job} for execution at system time given by * the desiredTime parameter. *

* The job will be rescheduled. It will execute with a frequency determined * by the period parameter. * @param job job to schedule. * @param desiredTime desired time of execution. * @param period repeat period. */ public synchronized void schedule(final Job job, final long desiredTime, final long period) { schedule(new ScheduledJobEntry(job, desiredTime, period)); } /** * Change the period of a job. The original job must exist for its period * to be changed. *

* The method returns true if the period could be changed, and false * otherwise. * @param job job. * @param newPeriod new repeat period. * @return true if period could be changed. */ public synchronized boolean changePeriod(final Job job, final long newPeriod) { if (newPeriod <= 0) { throw new IllegalArgumentException( "Period must be an integer langer than zero"); } int i = findIndex(job); if (i == -1) { return false; } else { ScheduledJobEntry se = (ScheduledJobEntry) jobList.get(i); se.period = newPeriod; return true; } } /** * Schedule a job. * @param newSJE new job entry. */ private synchronized void schedule(final ScheduledJobEntry newSJE) { // disallow new jobs after shutdown if (shutdown) { return; } int max = jobList.size(); long desiredExecutionTime = newSJE.desiredExecutionTime; // find the index i such that timeInMillis < jobList[i] int i = 0; for (; i < max; i++) { ScheduledJobEntry sje = (ScheduledJobEntry) jobList.get(i); if (desiredExecutionTime < sje.desiredExecutionTime) { break; } } jobList.add(i, newSJE); // if the jobList was empty, then notify the scheduler thread if (i == 0) { this.notifyAll(); } } /** * Shut down scheduler. */ public synchronized void shutdown() { shutdown = true; } /** * Run scheduler. */ public synchronized void run() { while (!shutdown) { if (jobList.isEmpty()) { linger(); } else { ScheduledJobEntry sje = (ScheduledJobEntry) jobList.get(0); long now = System.currentTimeMillis(); if (now >= sje.desiredExecutionTime) { executeInABox(sje.job); jobList.remove(0); if (sje.period > 0) { sje.desiredExecutionTime = now + sje.period; schedule(sje); } } else { linger(sje.desiredExecutionTime - now); } } } // clear out the job list to facilitate garbage collection jobList.clear(); jobList = null; System.out.println("Leaving scheduler run method"); } /** * We do not want a single failure to affect the whole scheduler. * @param job job to execute. */ void executeInABox(final Job job) { try { job.execute(); } catch (Exception e) { System.err.println("The execution of the job threw an exception"); e.printStackTrace(System.err); } } /** * Wait for notification. */ void linger() { try { while (jobList.isEmpty() && !shutdown) { this.wait(); } } catch (InterruptedException ie) { shutdown = true; } } /** * Wait for notification or time to elapse. * @param timeToLinger time to linger. */ void linger(final long timeToLinger) { try { this.wait(timeToLinger); } catch (InterruptedException ie) { shutdown = true; } } /** * Represents an entry in job scheduler. */ static final class ScheduledJobEntry { /** * Desired execution time. */ long desiredExecutionTime; /** * Job to run. */ Job job; /** * Repeat period. */ long period = 0; /** * Create new instance. * @param job job * @param desiredTime desired time. */ ScheduledJobEntry(final Job job, final long desiredTime) { this(job, desiredTime, 0); } /** * Create new instance. * @param job job * @param desiredTime desired time * @param period repeat period */ ScheduledJobEntry(final Job job, final long desiredTime, final long period) { super(); this.desiredExecutionTime = desiredTime; this.job = job; this.period = period; } } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/component/spi/000077500000000000000000000000001252742764200260605ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/component/spi/Component.java000066400000000000000000000025011252742764200306630ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.component.spi; import org.apache.log4j.spi.LoggerRepository; /** * A common interface shared by log4j components. * * @author Ceki Gulcu */ public interface Component { /** * Set owning logger repository for this component. This operation can * only be performed once. * Once set, a subsequent attempt will throw an IllegalStateException. * * @param repository The repository where this appender is attached. */ void setLoggerRepository(LoggerRepository repository); } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/component/spi/ComponentBase.java000066400000000000000000000072371252742764200314710ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.component.spi; import org.apache.log4j.Logger; import org.apache.log4j.component.ULogger; import org.apache.log4j.spi.LoggerRepository; /** * Most log4j components derive from this class. * * @author Ceki Gulcu */ public class ComponentBase implements Component { /** * Error count limit. */ private static final int ERROR_COUNT_LIMIT = 3; /** * Logger repository. */ protected LoggerRepository repository; /** * Logger. */ private ULogger logger; /** * Error count. */ private int errorCount = 0; /** * Construct a new instance. */ protected ComponentBase() { super(); } /** * Called by derived classes when they deem that the component has recovered * from an erroneous state. */ protected void resetErrorCount() { errorCount = 0; } /** * Set the owning repository. The owning repository cannot be set more than * once. * * @param repository repository */ public void setLoggerRepository(final LoggerRepository repository) { if (this.repository == null) { this.repository = repository; } else if (this.repository != repository) { throw new IllegalStateException("Repository has been already set"); } } /** * Return the LoggerRepository to which this component is attached. * * @return Owning LoggerRepository */ protected LoggerRepository getLoggerRepository() { return repository; } /** * Return an instance specific logger to be used by the component itself. * This logger is not intended to be accessed by the end-user, hence the * protected keyword. *

*

In case the repository for this component is not set, * this implementations returns a {@link SimpleULogger} instance. * * @return A ULogger instance. */ protected ULogger getLogger() { if (logger == null) { if (repository != null) { Logger l = repository.getLogger(this.getClass().getName()); if (l instanceof ULogger) { logger = (ULogger) l; } else { logger = new Log4JULogger(l); } } else { logger = SimpleULogger.getLogger(this.getClass().getName()); } } return logger; } /** * Frequently called methods in log4j components can invoke this method in * order to avoid flooding the output when logging lasting error conditions. * * @return a regular logger, or a NOPLogger if called too frequently. */ protected ULogger getNonFloodingLogger() { if (errorCount++ >= ERROR_COUNT_LIMIT) { return NOPULogger.NOP_LOGGER; } else { return getLogger(); } } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/component/spi/ErrorItem.java000066400000000000000000000074011252742764200306350ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.component.spi; import java.io.PrintStream; /** * Used to store special log4j errors which cannot be logged using internal * logging. Such errors include those occurring during the initial phases * of log4j configuration or errors emanating from core components such as * Logger or Hierarchy. * * @author Ceki Gulcu */ public class ErrorItem { /** * Message. */ String message; /** * Column. */ int colNumber = -1; /** * Line number. */ int lineNumber = -1; /** * Exception. */ Throwable exception; /** * Create new instance. * @param message message * @param e exception */ public ErrorItem(final String message, final Exception e) { super(); this.message = message; exception = e; } /** * Creaet new instance. * @param message message. */ public ErrorItem(final String message) { this(message, null); } /** * Get column number. * @return column number. */ public int getColNumber() { return colNumber; } /** * Set column number. * @param colNumber new column number. */ public void setColNumber(int colNumber) { this.colNumber = colNumber; } /** * Get exception. * @return exception. */ public Throwable getException() { return exception; } /** * Set exception. * @param exception exception */ public void setException(final Throwable exception) { this.exception = exception; } /** * Get line number. * @return line number. */ public int getLineNumber() { return lineNumber; } /** * Set line number. * @param lineNumber line number. */ public void setLineNumber(final int lineNumber) { this.lineNumber = lineNumber; } /** * Get message. * @return message. */ public String getMessage() { return message; } /** * Set message. * @param message message. */ public void setMessage(final String message) { this.message = message; } /** * String representation of ErrorItem. * @return string. */ public String toString() { String str = "Reported error: \"" + message + "\""; if (lineNumber != -1) { str += " at line " + lineNumber + " column " + colNumber; } if (exception != null) { str += (" with exception " + exception); } return str; } /** * Dump the details of this ErrorItem to System.out. */ public void dump() { dump(System.out); } /** * Dump the details of this ErrorItem on the specified {@link PrintStream}. * @param ps print stream. */ public void dump(final PrintStream ps) { String str = "Reported error: \"" + message + "\""; if (lineNumber != -1) { str += " at line " + lineNumber + " column " + colNumber; } ps.println(str); if (exception != null) { exception.printStackTrace(ps); } } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/component/spi/Log4JULogger.java000066400000000000000000000127751252742764200311430ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.component.spi; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.component.ULogger; import org.apache.log4j.component.helpers.MessageFormatter; /** * An implementation of ULogger on org.apache.log4j.Logger. */ public final class Log4JULogger implements ULogger { /** * Wrapped log4j logger. */ private final Logger logger; /** * Create a new instance. * * @param l logger, may not be null. */ public Log4JULogger(final Logger l) { super(); if (l == null) { throw new NullPointerException("l"); } logger = l; } /** * {@inheritDoc} */ public boolean isDebugEnabled() { return logger.isDebugEnabled(); } /** * {@inheritDoc} */ public void debug(final Object msg) { logger.debug(msg); } /** * {@inheritDoc} */ public void debug(final Object parameterizedMsg, final Object param1) { if (logger.isDebugEnabled()) { logger.debug(MessageFormatter.format( parameterizedMsg.toString(), param1)); } } /** * {@inheritDoc} */ public void debug(final String parameterizedMsg, final Object param1, final Object param2) { if (logger.isDebugEnabled()) { logger.debug(MessageFormatter.format( parameterizedMsg.toString(), param1, param2)); } } /** * {@inheritDoc} */ public void debug(final Object msg, final Throwable t) { logger.debug(msg, t); } /** * {@inheritDoc} */ public boolean isInfoEnabled() { return logger.isInfoEnabled(); } /** * {@inheritDoc} */ public void info(final Object msg) { logger.info(msg); } /** * {@inheritDoc} */ public void info(final Object parameterizedMsg, final Object param1) { if (logger.isInfoEnabled()) { logger.info(MessageFormatter.format( parameterizedMsg.toString(), param1)); } } /** * {@inheritDoc} */ public void info(final String parameterizedMsg, final Object param1, final Object param2) { if (logger.isInfoEnabled()) { logger.info(MessageFormatter.format( parameterizedMsg.toString(), param1, param2)); } } /** * {@inheritDoc} */ public void info(final Object msg, final Throwable t) { logger.info(msg, t); } /** * {@inheritDoc} */ public boolean isWarnEnabled() { return logger.isEnabledFor(Level.WARN); } /** * {@inheritDoc} */ public void warn(final Object msg) { logger.warn(msg); } /** * {@inheritDoc} */ public void warn(final Object parameterizedMsg, final Object param1) { if (logger.isEnabledFor(Level.WARN)) { logger.warn(MessageFormatter.format( parameterizedMsg.toString(), param1)); } } /** * {@inheritDoc} */ public void warn(final String parameterizedMsg, final Object param1, final Object param2) { if (logger.isEnabledFor(Level.WARN)) { logger.warn(MessageFormatter.format( parameterizedMsg.toString(), param1, param2)); } } /** * {@inheritDoc} */ public void warn(final Object msg, final Throwable t) { logger.warn(msg, t); } /** * {@inheritDoc} */ public boolean isErrorEnabled() { return logger.isEnabledFor(Level.ERROR); } /** * {@inheritDoc} */ public void error(final Object msg) { logger.error(msg); } /** * {@inheritDoc} */ public void error(final Object parameterizedMsg, final Object param1) { if (logger.isEnabledFor(Level.ERROR)) { logger.error(MessageFormatter.format( parameterizedMsg.toString(), param1)); } } /** * {@inheritDoc} */ public void error(final String parameterizedMsg, final Object param1, final Object param2) { if (logger.isEnabledFor(Level.ERROR)) { logger.error(MessageFormatter.format( parameterizedMsg.toString(), param1, param2)); } } /** * {@inheritDoc} */ public void error(final Object msg, final Throwable t) { logger.error(msg, t); } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/component/spi/LoggerEventListener.java000066400000000000000000000041111252742764200326470ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.component.spi; import org.apache.log4j.Appender; import org.apache.log4j.Logger; /** Interface used to listen for Logger related events such as add/remove appender or changing levels. Clients register an instance of the interface and the instance is called back when the various events occur. LoggerRepository provides methods for adding and removing LoggerEventListener instances. When implementing the methods of this interface, it is useful to remember that the Logger can access the repository using its getRepository() method. @author Ceki Gülcü @author Mark Womack */ public interface LoggerEventListener { /** Called when an appender is added to the logger. @param logger The logger to which the appender was added. @param appender The appender added to the logger. */ void appenderAddedEvent(Logger logger, Appender appender); /** Called when an appender is removed from the logger. @param logger The logger from which the appender was removed. @param appender The appender removed from the logger. */ void appenderRemovedEvent(Logger logger, Appender appender); /** Called when level changed on the logger. @param logger The logger that changed levels. */ void levelChangedEvent(Logger logger); } LoggerRepositoryEventListener.java000066400000000000000000000036121252742764200346750ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/component/spi/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.component.spi; import org.apache.log4j.spi.LoggerRepository; /** Interface used to listen for LoggerRepository related events such as startup, reset, and shutdown. Clients register an instance of the interface and the instance is called back when the various events occur. LoggerRepository provides methods for adding and removing LoggerRepositoryEventListener instances. @author Ceki Gülcü @author Mark Womack */ public interface LoggerRepositoryEventListener { /** Called when the repository configuration is reset. @param repository repository */ void configurationResetEvent(LoggerRepository repository); /** Called when the repository configuration is changed. @param repository repository */ void configurationChangedEvent(LoggerRepository repository); /** Called when the repository is shutdown. When this method is invoked, the repository is still valid (ie it has not been shutdown, but will be after this method returns). @param repository repository. */ void shutdownEvent(LoggerRepository repository); } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/component/spi/LoggerRepositoryEx.java000066400000000000000000000132161252742764200325420ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.component.spi; import org.apache.log4j.Appender; import org.apache.log4j.Category; import org.apache.log4j.Logger; import org.apache.log4j.component.plugins.PluginRegistry; import org.apache.log4j.component.scheduler.Scheduler; import org.apache.log4j.spi.LoggerFactory; import org.apache.log4j.spi.LoggerRepository; import java.util.List; import java.util.Map; /** A LoggerRepository is used to create and retrieve Loggers. The relation between loggers in a repository depends on the repository but typically loggers are arranged in a named hierarchy.

In addition to the creational methods, a LoggerRepository can be queried for existing loggers, can act as a point of registry for events related to loggers. @author Ceki Gülcü @author Mark Womack @author Curt Arnold */ public interface LoggerRepositoryEx extends LoggerRepository { /** Add a {@link LoggerRepositoryEventListener} to the repository. The listener will be called when repository events occur. @param listener event listener, may not be null. */ void addLoggerRepositoryEventListener( LoggerRepositoryEventListener listener); /** Remove a {@link LoggerRepositoryEventListener} from the repository. @param listener listener. */ void removeLoggerRepositoryEventListener( LoggerRepositoryEventListener listener); /** Add a {@link LoggerEventListener} to the repository. The listener will be called when repository events occur. @param listener listener, may not be null. */ void addLoggerEventListener(LoggerEventListener listener); /** Remove a {@link LoggerEventListener} from the repository. @param listener listener, may not be null. */ void removeLoggerEventListener(LoggerEventListener listener); /** * Get the name of this logger repository. * @return name, may not be null. */ String getName(); /** * A logger repository is a named entity. * @param repoName new name, may not be null. */ void setName(String repoName); /** * Is the current configuration of the repository in its original (pristine) * state? * @return true if repository is in original state. * */ boolean isPristine(); /** * Set the pristine flag. * @param state state * @see #isPristine */ void setPristine(boolean state); /** Requests that a appender removed event be sent to any registered {@link LoggerEventListener}. @param logger The logger from which the appender was removed. @param appender The appender removed from the logger. */ void fireRemoveAppenderEvent(Category logger, Appender appender); /** Requests that a level changed event be sent to any registered {@link LoggerEventListener}. @param logger The logger which changed levels. */ void fireLevelChangedEvent(Logger logger); /** Requests that a configuration changed event be sent to any registered {@link LoggerRepositoryEventListener}. */ void fireConfigurationChangedEvent(); /** * Return the PluginRegisty for this LoggerRepository. * @return plug in registry. */ PluginRegistry getPluginRegistry(); /** * Return the {@link Scheduler} for this LoggerRepository. * @return scheduler. */ Scheduler getScheduler(); /** * Get the properties specific for this repository. * @return property map. */ Map getProperties(); /** * Get the property of this repository. * @param key property key. * @return key value or null if not set. */ String getProperty(String key); /** * Set a property of this repository. * @param key key, may not be null. * @param value new value, if null, property will be removed. */ void setProperty(String key, String value); /** * Errors which cannot be logged, go to the error list. * * @return List */ List getErrorList(); /** * Errors which cannot be logged, go to the error list. * * @param errorItem an ErrorItem to add to the error list */ void addErrorItem(ErrorItem errorItem); /** * A LoggerRepository can also act as a store for various objects used * by log4j components. * * @param key key, may not be null. * @return The object stored under 'key'. */ Object getObject(String key); /** * Store an object under 'key'. If no object can be found, null is returned. * * @param key key, may not be null. * @param value value, may be null. */ void putObject(String key, Object value); /** * Sets the logger factory used by LoggerRepository.getLogger(String). * @param loggerFactory factory to use, may not be null */ void setLoggerFactory(LoggerFactory loggerFactory); /** * Returns the logger factory used by * LoggerRepository.getLogger(String). * * @return non-null factory */ LoggerFactory getLoggerFactory(); } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/component/spi/NOPULogger.java000066400000000000000000000101301252742764200306370ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.component.spi; import org.apache.log4j.component.ULogger; /** * A no operation (NOP) implementation of {@link ULogger}. * * @author Ceki Gülcü */ public final class NOPULogger implements ULogger { /** * The unique instance of NOPLogger. */ public static final NOPULogger NOP_LOGGER = new NOPULogger(); /** * There is no point in people creating multiple instances of NullLogger. * Hence, the private access modifier. */ private NOPULogger() { super(); } /** * Get instance. * @param name logger name. * @return logger. */ public static NOPULogger getLogger(final String name) { return NOP_LOGGER; } /** * {@inheritDoc} */ public boolean isDebugEnabled() { return false; } /** * {@inheritDoc} */ public void debug(final Object msg) { // NOP } /** * {@inheritDoc} */ public void debug(final Object parameterizedMsg, final Object param1) { // NOP } /** * {@inheritDoc} */ public void debug(final String parameterizedMsg, final Object param1, final Object param2) { // NOP } /** * {@inheritDoc} */ public void debug(final Object msg, final Throwable t) { // NOP } /** * {@inheritDoc} */ public boolean isInfoEnabled() { // NOP return false; } /** * {@inheritDoc} */ public void info(final Object msg) { // NOP } /** * {@inheritDoc} */ public void info(final Object parameterizedMsg, final Object param1) { // NOP } /** * {@inheritDoc} */ public void info(final String parameterizedMsg, final Object param1, final Object param2) { // NOP } /** * {@inheritDoc} */ public void info(final Object msg, final Throwable t) { // NOP } /** * {@inheritDoc} */ public boolean isWarnEnabled() { return false; } /** * {@inheritDoc} */ public void warn(final Object msg) { // NOP } /** * {@inheritDoc} */ public void warn(final Object parameterizedMsg, final Object param1) { // NOP } /** * {@inheritDoc} */ public void warn(final String parameterizedMsg, final Object param1, final Object param2) { // NOP } /** * {@inheritDoc} */ public void warn(final Object msg, final Throwable t) { // NOP } /** * {@inheritDoc} */ public boolean isErrorEnabled() { return false; } /** * {@inheritDoc} */ public void error(final Object msg) { // NOP } /** * {@inheritDoc} */ public void error(final Object parameterizedMsg, final Object param1) { // NOP } /** * {@inheritDoc} */ public void error(final String parameterizedMsg, final Object param1, final Object param2) { // NOP } /** * {@inheritDoc} */ public void error(final Object msg, final Throwable t) { // NOP } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/component/spi/SimpleULogger.java000066400000000000000000000167761252742764200314620ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.component.spi; import org.apache.log4j.component.ULogger; import org.apache.log4j.component.helpers.MessageFormatter; /** * A simple implementation that logs messages of level INFO or higher on * the console (System.out). *

* The output includes the relative time in milliseconds, thread name, level, * logger name, and the message followed by the line separator for the host. * In log4j terms it amounts to the "%r [%t] %level %logger - %m%n" pattern. *

176 [main] INFO examples.Sort - Populating an array of 2 elements in reverse.
225 [main] INFO examples.SortAlgo - Entered the sort method.
304 [main] INFO SortAlgo.DUMP - Dump of interger array:
317 [main] INFO SortAlgo.DUMP - Element [0] = 0
331 [main] INFO SortAlgo.DUMP - Element [1] = 1
343 [main] INFO examples.Sort - The next log statement should be an error msg.
346 [main] ERROR SortAlgo.DUMP - Tried to dump an uninitialized array.
        at org.log4j.examples.SortAlgo.dump(SortAlgo.java:58)
        at org.log4j.examples.Sort.main(Sort.java:64)
467 [main] INFO  examples.Sort - Exiting main method.
* * @author Ceki Gülcü */ public final class SimpleULogger implements ULogger { /** * Logger name. */ private final String loggerName; /** * Mark the time when this class gets loaded into memory. */ private static long startTime = System.currentTimeMillis(); /** * Line separator. */ public static final String LINE_SEPARATOR = System.getProperty("line.separator"); /** * INFO string literal. */ private static final String INFO_STR = "INFO"; /** * WARN string literal. */ private static final String WARN_STR = "WARN"; /** * ERROR string literal. */ private static final String ERROR_STR = "ERROR"; /** * Constructor is private to force construction through getLogger. * @param name logger name */ private SimpleULogger(final String name) { super(); this.loggerName = name; } /** * Creates a new instance. * * @param name logger name * @return logger. */ public static SimpleULogger getLogger(final String name) { return new SimpleULogger(name); } /** * {@inheritDoc} */ public boolean isDebugEnabled() { return false; } /** * {@inheritDoc} */ public void debug(final Object msg) { // NOP } /** * {@inheritDoc} */ public void debug(final Object parameterizedMsg, final Object param1) { // NOP } /** * {@inheritDoc} */ public void debug(final String parameterizedMsg, final Object param1, final Object param2) { // NOP } /** * {@inheritDoc} */ public void debug(final Object msg, final Throwable t) { // NOP } /** * This is our internal implementation for logging regular (non-parameterized) * log messages. * * @param level level * @param message message * @param t throwable */ private void log(final String level, final String message, final Throwable t) { StringBuffer buf = new StringBuffer(); long millis = System.currentTimeMillis(); buf.append(millis - startTime); buf.append(" ["); buf.append(Thread.currentThread().getName()); buf.append("] "); buf.append(level); buf.append(" "); buf.append(loggerName); buf.append(" - "); buf.append(message); buf.append(LINE_SEPARATOR); System.out.print(buf.toString()); if (t != null) { t.printStackTrace(System.out); } System.out.flush(); } /** * For parameterized messages, first substitute parameters and then log. * * @param level level * @param parameterizedMsg message pattern * @param param1 param1 * @param param2 param2 */ private void parameterizedLog(final String level, final Object parameterizedMsg, final Object param1, final Object param2) { if (parameterizedMsg instanceof String) { String msgStr = (String) parameterizedMsg; msgStr = MessageFormatter.format(msgStr, param1, param2); log(level, msgStr, null); } else { // To be failsafe, we handle the case where 'messagePattern' is not // a String. Unless the user makes a mistake, this should not happen. log(level, parameterizedMsg.toString(), null); } } /** * {@inheritDoc} */ public boolean isInfoEnabled() { return true; } /** * {@inheritDoc} */ public void info(final Object msg) { log(INFO_STR, msg.toString(), null); } /** * {@inheritDoc} */ public void info(final Object parameterizedMsg, final Object param1) { parameterizedLog(INFO_STR, parameterizedMsg, param1, null); } /** * {@inheritDoc} */ public void info(final String parameterizedMsg, final Object param1, final Object param2) { parameterizedLog(INFO_STR, parameterizedMsg, param1, param2); } /** * {@inheritDoc} */ public void info(final Object msg, final Throwable t) { log(INFO_STR, msg.toString(), t); } /** * {@inheritDoc} */ public boolean isWarnEnabled() { return true; } /** * {@inheritDoc} */ public void warn(final Object msg) { log(WARN_STR, msg.toString(), null); } /** * {@inheritDoc} */ public void warn(final Object parameterizedMsg, final Object param1) { parameterizedLog(WARN_STR, parameterizedMsg, param1, null); } /** * {@inheritDoc} */ public void warn(final String parameterizedMsg, final Object param1, final Object param2) { parameterizedLog(WARN_STR, parameterizedMsg, param1, param2); } /** * {@inheritDoc} */ public void warn(final Object msg, final Throwable t) { log(WARN_STR, msg.toString(), t); } /** * {@inheritDoc} */ public boolean isErrorEnabled() { return true; } /** * {@inheritDoc} */ public void error(final Object msg) { log(ERROR_STR, msg.toString(), null); } /** * {@inheritDoc} */ public void error(final Object parameterizedMsg, final Object param1) { parameterizedLog(ERROR_STR, parameterizedMsg, param1, null); } /** * {@inheritDoc} */ public void error(final String parameterizedMsg, final Object param1, final Object param2) { parameterizedLog(ERROR_STR, parameterizedMsg, param1, param2); } /** * {@inheritDoc} */ public void error(final Object msg, final Throwable t) { log(ERROR_STR, msg.toString(), t); } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/component/spi/Thresholdable.java000066400000000000000000000042231252742764200315040ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.component.spi; import org.apache.log4j.Level; /** * An interface that defines the required methods for supporting the * setting and getting of a level threshold. Components should implement * this interface if logging events they process should meet a certain * threshold before being processed further. Examples of this are * Appenders and Receivers which will not process logging events unless * the event level is at or greater than a set threshold level. * * @author Paul Smith (psmith@apache.org) * @author Mark Womack */ public interface Thresholdable { /** * Sets the component theshold to the given level. * * @param level The threshold level events must equal or be greater * than before further processing can be done. */ void setThreshold(Level level); /** * Gets the current threshold setting of the component. * * @return Level The current threshold level of the component. */ Level getThreshold(); /** * Returns true if the given level is equals or greater than the current * threshold value of the component. * * @param level The level to test against the component threshold. * @return boolean True if level is equal or greater than the * component threshold. */ boolean isAsSevereAsThreshold(Level level); } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/extras/000077500000000000000000000000001252742764200245715ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/extras/DOMConfigurator.java000066400000000000000000001072171252742764200304460ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.extras; import org.apache.log4j.Appender; import org.apache.log4j.Layout; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.apache.log4j.config.PropertySetter; import org.apache.log4j.helpers.FileWatchdog; import org.apache.log4j.helpers.Loader; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.helpers.OptionConverter; import org.apache.log4j.or.RendererMap; import org.apache.log4j.spi.AppenderAttachable; import org.apache.log4j.spi.Configurator; import org.apache.log4j.spi.ErrorHandler; import org.apache.log4j.spi.Filter; import org.apache.log4j.spi.LoggerFactory; import org.apache.log4j.spi.LoggerRepository; import org.apache.log4j.spi.OptionHandler; import org.apache.log4j.spi.RendererSupport; import org.apache.log4j.xml.SAXErrorHandler; import org.apache.log4j.xml.UnrecognizedElementHandler; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.lang.reflect.Method; import java.net.URL; import java.util.Hashtable; import java.util.Properties; /** * This is a duplicate (with minor modifications) * of the log4j 1.2.15 DOMConfigurator * renamed for use with earlier versions of log4j. * */ public class DOMConfigurator implements Configurator { static final String CONFIGURATION_TAG = "log4j:configuration"; static final String OLD_CONFIGURATION_TAG = "configuration"; static final String RENDERER_TAG = "renderer"; static final String APPENDER_TAG = "appender"; static final String APPENDER_REF_TAG = "appender-ref"; static final String PARAM_TAG = "param"; static final String LAYOUT_TAG = "layout"; static final String CATEGORY = "category"; static final String LOGGER = "logger"; static final String LOGGER_REF = "logger-ref"; static final String CATEGORY_FACTORY_TAG = "categoryFactory"; static final String LOGGER_FACTORY_TAG = "loggerFactory"; static final String NAME_ATTR = "name"; static final String CLASS_ATTR = "class"; static final String VALUE_ATTR = "value"; static final String ROOT_TAG = "root"; static final String ROOT_REF = "root-ref"; static final String LEVEL_TAG = "level"; static final String PRIORITY_TAG = "priority"; static final String FILTER_TAG = "filter"; static final String ERROR_HANDLER_TAG = "errorHandler"; static final String REF_ATTR = "ref"; static final String ADDITIVITY_ATTR = "additivity"; static final String THRESHOLD_ATTR = "threshold"; static final String CONFIG_DEBUG_ATTR = "configDebug"; static final String INTERNAL_DEBUG_ATTR = "debug"; private static final String RESET_ATTR = "reset"; static final String RENDERING_CLASS_ATTR = "renderingClass"; static final String RENDERED_CLASS_ATTR = "renderedClass"; static final String EMPTY_STR = ""; static final Class[] ONE_STRING_PARAM = new Class[] {String.class}; final static String dbfKey = "javax.xml.parsers.DocumentBuilderFactory"; // key: appenderName, value: appender private Hashtable appenderBag; private Properties props; private LoggerRepository repository; private LoggerFactory catFactory = null; /** No argument constructor. */ public DOMConfigurator() { appenderBag = new Hashtable(); } /** Used internally to parse appenders by IDREF name. */ protected Appender findAppenderByName(Document doc, String appenderName) { Appender appender = (Appender) appenderBag.get(appenderName); if(appender != null) { return appender; } else { // Doesn't work on DOM Level 1 : // Element element = doc.getElementById(appenderName); // Endre's hack: Element element = null; NodeList list = doc.getElementsByTagName("appender"); for (int t=0; t < list.getLength(); t++) { Node node = list.item(t); NamedNodeMap map= node.getAttributes(); Node attrNode = map.getNamedItem("name"); if (appenderName.equals(attrNode.getNodeValue())) { element = (Element) node; break; } } // Hack finished. if(element == null) { LogLog.error("No appender named ["+appenderName+"] could be found."); return null; } else { appender = parseAppender(element); if (appender != null) { appenderBag.put(appenderName, appender); } return appender; } } } /** Used internally to parse appenders by IDREF element. */ protected Appender findAppenderByReference(Element appenderRef) { String appenderName = subst(appenderRef.getAttribute(REF_ATTR)); Document doc = appenderRef.getOwnerDocument(); return findAppenderByName(doc, appenderName); } /** * Delegates unrecognized content to created instance if * it supports UnrecognizedElementParser. * @since 1.2.15 * @param instance instance, may be null. * @param element element, may not be null. * @param props properties * @throws IOException thrown if configuration of owner object * should be abandoned. */ private static void parseUnrecognizedElement(final Object instance, final Element element, final Properties props) throws Exception { boolean recognized = false; if (instance instanceof UnrecognizedElementHandler) { recognized = ((UnrecognizedElementHandler) instance).parseUnrecognizedElement( element, props); } if (!recognized) { LogLog.warn("Unrecognized element " + element.getNodeName()); } } /** * Delegates unrecognized content to created instance if * it supports UnrecognizedElementParser and catches and * logs any exception. * @since 1.2.15 * @param instance instance, may be null. * @param element element, may not be null. * @param props properties */ private static void quietParseUnrecognizedElement(final Object instance, final Element element, final Properties props) { try { parseUnrecognizedElement(instance, element, props); } catch (Exception ex) { LogLog.error("Error in extension content: ", ex); } } /** Used internally to parse an appender element. */ protected Appender parseAppender (Element appenderElement) { String className = subst(appenderElement.getAttribute(CLASS_ATTR)); LogLog.debug("Class name: [" + className+']'); try { Object instance = Loader.loadClass(className).newInstance(); Appender appender = (Appender)instance; PropertySetter propSetter = new PropertySetter(appender); appender.setName(subst(appenderElement.getAttribute(NAME_ATTR))); NodeList children = appenderElement.getChildNodes(); final int length = children.getLength(); for (int loop = 0; loop < length; loop++) { Node currentNode = children.item(loop); /* We're only interested in Elements */ if (currentNode.getNodeType() == Node.ELEMENT_NODE) { Element currentElement = (Element)currentNode; // Parse appender parameters if (currentElement.getTagName().equals(PARAM_TAG)) { setParameter(currentElement, propSetter); } // Set appender layout else if (currentElement.getTagName().equals(LAYOUT_TAG)) { appender.setLayout(parseLayout(currentElement)); } // Add filters else if (currentElement.getTagName().equals(FILTER_TAG)) { parseFilters(currentElement, appender); } else if (currentElement.getTagName().equals(ERROR_HANDLER_TAG)) { parseErrorHandler(currentElement, appender); } else if (currentElement.getTagName().equals(APPENDER_REF_TAG)) { String refName = subst(currentElement.getAttribute(REF_ATTR)); if(appender instanceof AppenderAttachable) { AppenderAttachable aa = (AppenderAttachable) appender; LogLog.debug("Attaching appender named ["+ refName+ "] to appender named ["+ appender.getName()+"]."); aa.addAppender(findAppenderByReference(currentElement)); } else { LogLog.error("Requesting attachment of appender named ["+ refName+ "] to appender named ["+ appender.getName()+ "] which does not implement org.apache.log4j.spi.AppenderAttachable."); } } else { parseUnrecognizedElement(instance, currentElement, props); } } } propSetter.activate(); return appender; } /* Yes, it's ugly. But all of these exceptions point to the same problem: we can't create an Appender */ catch (Exception oops) { LogLog.error("Could not create an Appender. Reported error follows.", oops); return null; } } /** Used internally to parse an {@link ErrorHandler} element. */ protected void parseErrorHandler(Element element, Appender appender) { ErrorHandler eh = (ErrorHandler) OptionConverter.instantiateByClassName( subst(element.getAttribute(CLASS_ATTR)), org.apache.log4j.spi.ErrorHandler.class, null); if(eh != null) { eh.setAppender(appender); PropertySetter propSetter = new PropertySetter(eh); NodeList children = element.getChildNodes(); final int length = children.getLength(); for (int loop = 0; loop < length; loop++) { Node currentNode = children.item(loop); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { Element currentElement = (Element) currentNode; String tagName = currentElement.getTagName(); if(tagName.equals(PARAM_TAG)) { setParameter(currentElement, propSetter); } else if(tagName.equals(APPENDER_REF_TAG)) { eh.setBackupAppender(findAppenderByReference(currentElement)); } else if(tagName.equals(LOGGER_REF)) { String loggerName = currentElement.getAttribute(REF_ATTR); Logger logger = (catFactory == null) ? repository.getLogger(loggerName) : repository.getLogger(loggerName, catFactory); eh.setLogger(logger); } else if(tagName.equals(ROOT_REF)) { Logger root = repository.getRootLogger(); eh.setLogger(root); } else { quietParseUnrecognizedElement(eh, currentElement, props); } } } propSetter.activate(); appender.setErrorHandler(eh); } } /** Used internally to parse a filter element. */ protected void parseFilters(Element element, Appender appender) { String clazz = subst(element.getAttribute(CLASS_ATTR)); Filter filter = (Filter) OptionConverter.instantiateByClassName(clazz, Filter.class, null); if(filter != null) { PropertySetter propSetter = new PropertySetter(filter); NodeList children = element.getChildNodes(); final int length = children.getLength(); for (int loop = 0; loop < length; loop++) { Node currentNode = children.item(loop); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { Element currentElement = (Element) currentNode; String tagName = currentElement.getTagName(); if(tagName.equals(PARAM_TAG)) { setParameter(currentElement, propSetter); } else { quietParseUnrecognizedElement(filter, currentElement, props); } } } propSetter.activate(); LogLog.debug("Adding filter of type ["+filter.getClass() +"] to appender named ["+appender.getName()+"]."); appender.addFilter(filter); } } /** Used internally to parse an category element. */ protected void parseCategory (Element loggerElement) { // Create a new org.apache.log4j.Category object from the element. String catName = subst(loggerElement.getAttribute(NAME_ATTR)); Logger cat; String className = subst(loggerElement.getAttribute(CLASS_ATTR)); if(EMPTY_STR.equals(className)) { LogLog.debug("Retreiving an instance of org.apache.log4j.Logger."); cat = (catFactory == null) ? repository.getLogger(catName) : repository.getLogger(catName, catFactory); } else { LogLog.debug("Desired logger sub-class: ["+className+']'); try { Class clazz = Loader.loadClass(className); Method getInstanceMethod = clazz.getMethod("getLogger", ONE_STRING_PARAM); cat = (Logger) getInstanceMethod.invoke(null, new Object[] {catName}); } catch (Exception oops) { LogLog.error("Could not retrieve category ["+catName+ "]. Reported error follows.", oops); return; } } // Setting up a category needs to be an atomic operation, in order // to protect potential log operations while category // configuration is in progress. synchronized(cat) { boolean additivity = OptionConverter.toBoolean( subst(loggerElement.getAttribute(ADDITIVITY_ATTR)), true); LogLog.debug("Setting ["+cat.getName()+"] additivity to ["+additivity+"]."); cat.setAdditivity(additivity); parseChildrenOfLoggerElement(loggerElement, cat, false); } } /** Used internally to parse the category factory element. */ protected void parseCategoryFactory(Element factoryElement) { String className = subst(factoryElement.getAttribute(CLASS_ATTR)); if(EMPTY_STR.equals(className)) { LogLog.error("Category Factory tag " + CLASS_ATTR + " attribute not found."); LogLog.debug("No Category Factory configured."); } else { LogLog.debug("Desired category factory: ["+className+']'); Object factory = OptionConverter.instantiateByClassName(className, LoggerFactory.class, null); if (factory instanceof LoggerFactory) { catFactory = (LoggerFactory) factory; } else { LogLog.error("Category Factory class " + className + " does not implement org.apache.log4j.LoggerFactory"); } PropertySetter propSetter = new PropertySetter(factory); Element currentElement = null; Node currentNode = null; NodeList children = factoryElement.getChildNodes(); final int length = children.getLength(); for (int loop=0; loop < length; loop++) { currentNode = children.item(loop); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { currentElement = (Element)currentNode; if (currentElement.getTagName().equals(PARAM_TAG)) { setParameter(currentElement, propSetter); } else { quietParseUnrecognizedElement(factory, currentElement, props); } } } } } /** Used internally to parse the roor category element. */ protected void parseRoot (Element rootElement) { Logger root = repository.getRootLogger(); // category configuration needs to be atomic synchronized(root) { parseChildrenOfLoggerElement(rootElement, root, true); } } /** Used internally to parse the children of a category element. */ protected void parseChildrenOfLoggerElement(Element catElement, Logger cat, boolean isRoot) { PropertySetter propSetter = new PropertySetter(cat); // Remove all existing appenders from cat. They will be // reconstructed if need be. cat.removeAllAppenders(); NodeList children = catElement.getChildNodes(); final int length = children.getLength(); for (int loop = 0; loop < length; loop++) { Node currentNode = children.item(loop); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { Element currentElement = (Element) currentNode; String tagName = currentElement.getTagName(); if (tagName.equals(APPENDER_REF_TAG)) { Element appenderRef = (Element) currentNode; Appender appender = findAppenderByReference(appenderRef); String refName = subst(appenderRef.getAttribute(REF_ATTR)); if(appender != null) LogLog.debug("Adding appender named ["+ refName+ "] to category ["+cat.getName()+"]."); else LogLog.debug("Appender named ["+ refName + "] not found."); cat.addAppender(appender); } else if(tagName.equals(LEVEL_TAG)) { parseLevel(currentElement, cat, isRoot); } else if(tagName.equals(PRIORITY_TAG)) { parseLevel(currentElement, cat, isRoot); } else if(tagName.equals(PARAM_TAG)) { setParameter(currentElement, propSetter); } else { quietParseUnrecognizedElement(cat, currentElement, props); } } } propSetter.activate(); } /** Used internally to parse a layout element. */ protected Layout parseLayout (Element layout_element) { String className = subst(layout_element.getAttribute(CLASS_ATTR)); LogLog.debug("Parsing layout of class: \""+className+"\""); try { Object instance = Loader.loadClass(className).newInstance(); Layout layout = (Layout)instance; PropertySetter propSetter = new PropertySetter(layout); NodeList params = layout_element.getChildNodes(); final int length = params.getLength(); for (int loop = 0; loop < length; loop++) { Node currentNode = (Node)params.item(loop); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { Element currentElement = (Element) currentNode; String tagName = currentElement.getTagName(); if(tagName.equals(PARAM_TAG)) { setParameter(currentElement, propSetter); } else { parseUnrecognizedElement(instance, currentElement, props); } } } propSetter.activate(); return layout; } catch (Exception oops) { LogLog.error("Could not create the Layout. Reported error follows.", oops); return null; } } protected void parseRenderer(Element element) { String renderingClass = subst(element.getAttribute(RENDERING_CLASS_ATTR)); String renderedClass = subst(element.getAttribute(RENDERED_CLASS_ATTR)); if(repository instanceof RendererSupport) { RendererMap.addRenderer((RendererSupport) repository, renderedClass, renderingClass); } } /** Used internally to parse a level element. */ protected void parseLevel(Element element, Logger logger, boolean isRoot) { String catName = logger.getName(); if(isRoot) { catName = "root"; } String priStr = subst(element.getAttribute(VALUE_ATTR)); LogLog.debug("Level value for "+catName+" is ["+priStr+"]."); if(INHERITED.equalsIgnoreCase(priStr) || NULL.equalsIgnoreCase(priStr)) { if(isRoot) { LogLog.error("Root level cannot be inherited. Ignoring directive."); } else { logger.setLevel(null); } } else { String className = subst(element.getAttribute(CLASS_ATTR)); if(EMPTY_STR.equals(className)) { logger.setLevel(OptionConverter.toLevel(priStr, Level.DEBUG)); } else { LogLog.debug("Desired Level sub-class: ["+className+']'); try { Class clazz = Loader.loadClass(className); Method toLevelMethod = clazz.getMethod("toLevel", ONE_STRING_PARAM); Level pri = (Level) toLevelMethod.invoke(null, new Object[] {priStr}); logger.setLevel(pri); } catch (Exception oops) { LogLog.error("Could not create level ["+priStr+ "]. Reported error follows.", oops); return; } } } LogLog.debug(catName + " level set to " + logger.getLevel()); } protected void setParameter(Element elem, PropertySetter propSetter) { setParameter(elem, propSetter, props); } /** Configure log4j using a configuration element as defined in the log4j.dtd. */ static public void configure (Element element) { DOMConfigurator configurator = new DOMConfigurator(); configurator.doConfigure(element, LogManager.getLoggerRepository()); } /** Like {@link #configureAndWatch(String, long)} except that the default delay as defined by {@link FileWatchdog#DEFAULT_DELAY} is used. @param configFilename A log4j configuration file in XML format. */ static public void configureAndWatch(String configFilename) { configureAndWatch(configFilename, FileWatchdog.DEFAULT_DELAY); } /** Read the configuration file configFilename if it exists. Moreover, a thread will be created that will periodically check if configFilename has been created or modified. The period is determined by the delay argument. If a change or file creation is detected, then configFilename is read to configure log4j. @param configFilename A log4j configuration file in XML format. @param delay The delay in milliseconds to wait between each check. */ static public void configureAndWatch(String configFilename, long delay) { XMLWatchdog xdog = new XMLWatchdog(configFilename); xdog.setDelay(delay); xdog.start(); } private interface ParseAction { Document parse(final DocumentBuilder parser) throws SAXException, IOException; } public void doConfigure(final String filename, LoggerRepository repository) { ParseAction action = new ParseAction() { public Document parse(final DocumentBuilder parser) throws SAXException, IOException { return parser.parse(new File(filename)); } public String toString() { return "file [" + filename + "]"; } }; doConfigure(action, repository); } public void doConfigure(final URL url, LoggerRepository repository) { ParseAction action = new ParseAction() { public Document parse(final DocumentBuilder parser) throws SAXException, IOException { InputStream stream = url.openStream(); try { InputSource src = new InputSource(stream); src.setSystemId(url.toString()); return parser.parse(src); } finally { stream.close(); } } public String toString() { return "url [" + url.toString() + "]"; } }; doConfigure(action, repository); } /** Configure log4j by reading in a log4j.dtd compliant XML configuration file. */ public void doConfigure(final InputStream inputStream, LoggerRepository repository) throws FactoryConfigurationError { ParseAction action = new ParseAction() { public Document parse(final DocumentBuilder parser) throws SAXException, IOException { InputSource inputSource = new InputSource(inputStream); inputSource.setSystemId("dummy://log4j.dtd"); return parser.parse(inputSource); } public String toString() { return "input stream [" + inputStream.toString() + "]"; } }; doConfigure(action, repository); } /** Configure log4j by reading in a log4j.dtd compliant XML configuration file. */ public void doConfigure(final Reader reader, LoggerRepository repository) throws FactoryConfigurationError { ParseAction action = new ParseAction() { public Document parse(final DocumentBuilder parser) throws SAXException, IOException { InputSource inputSource = new InputSource(reader); inputSource.setSystemId("dummy://log4j.dtd"); return parser.parse(inputSource); } public String toString() { return "reader [" + reader.toString() + "]"; } }; doConfigure(action, repository); } /** Configure log4j by reading in a log4j.dtd compliant XML configuration file. */ protected void doConfigure(final InputSource inputSource, LoggerRepository repository) throws FactoryConfigurationError { if (inputSource.getSystemId() == null) { inputSource.setSystemId("dummy://log4j.dtd"); } ParseAction action = new ParseAction() { public Document parse(final DocumentBuilder parser) throws SAXException, IOException { return parser.parse(inputSource); } public String toString() { return "input source [" + inputSource.toString() + "]"; } }; doConfigure(action, repository); } private final void doConfigure(final ParseAction action, final LoggerRepository repository) throws FactoryConfigurationError { DocumentBuilderFactory dbf = null; this.repository = repository; try { LogLog.debug("System property is :"+ OptionConverter.getSystemProperty(dbfKey, null)); dbf = DocumentBuilderFactory.newInstance(); LogLog.debug("Standard DocumentBuilderFactory search succeded."); LogLog.debug("DocumentBuilderFactory is: "+dbf.getClass().getName()); } catch(FactoryConfigurationError fce) { Exception e = fce.getException(); LogLog.debug("Could not instantiate a DocumentBuilderFactory.", e); throw fce; } try { dbf.setValidating(true); DocumentBuilder docBuilder = dbf.newDocumentBuilder(); docBuilder.setErrorHandler(new SAXErrorHandler()); docBuilder.setEntityResolver(new Log4jEntityResolver()); Document doc = action.parse(docBuilder); parse(doc.getDocumentElement()); } catch (Exception e) { // I know this is miserable... LogLog.error("Could not parse "+ action.toString() + ".", e); } } /** Configure by taking in an DOM element. */ public void doConfigure(Element element, LoggerRepository repository) { this.repository = repository; parse(element); } /** A static version of {@link #doConfigure(String, LoggerRepository)}. */ static public void configure(String filename) throws FactoryConfigurationError { new DOMConfigurator().doConfigure(filename, LogManager.getLoggerRepository()); } /** A static version of {@link #doConfigure(URL, LoggerRepository)}. */ static public void configure(URL url) throws FactoryConfigurationError { new DOMConfigurator().doConfigure(url, LogManager.getLoggerRepository()); } /** Used internally to configure the log4j framework by parsing a DOM tree of XML elements based on log4j.dtd. */ protected void parse(Element element) { String rootElementName = element.getTagName(); if (!rootElementName.equals(CONFIGURATION_TAG)) { if(rootElementName.equals(OLD_CONFIGURATION_TAG)) { LogLog.warn("The <"+OLD_CONFIGURATION_TAG+ "> element has been deprecated."); LogLog.warn("Use the <"+CONFIGURATION_TAG+"> element instead."); } else { LogLog.error("DOM element is - not a <"+CONFIGURATION_TAG+"> element."); return; } } String debugAttrib = subst(element.getAttribute(INTERNAL_DEBUG_ATTR)); LogLog.debug("debug attribute= \"" + debugAttrib +"\"."); // if the log4j.dtd is not specified in the XML file, then the // "debug" attribute is returned as the empty string. if(!debugAttrib.equals("") && !debugAttrib.equals("null")) { LogLog.setInternalDebugging(OptionConverter.toBoolean(debugAttrib, true)); } else { LogLog.debug("Ignoring " + INTERNAL_DEBUG_ATTR + " attribute."); } // // reset repository before configuration if reset="true" // on configuration element. // String resetAttrib = subst(element.getAttribute(RESET_ATTR)); LogLog.debug("reset attribute= \"" + resetAttrib +"\"."); if(!("".equals(resetAttrib)) && OptionConverter.toBoolean(resetAttrib, false)) { repository.resetConfiguration(); } String confDebug = subst(element.getAttribute(CONFIG_DEBUG_ATTR)); if(!confDebug.equals("") && !confDebug.equals("null")) { LogLog.warn("The \""+CONFIG_DEBUG_ATTR+"\" attribute is deprecated."); LogLog.warn("Use the \""+INTERNAL_DEBUG_ATTR+"\" attribute instead."); LogLog.setInternalDebugging(OptionConverter.toBoolean(confDebug, true)); } String thresholdStr = subst(element.getAttribute(THRESHOLD_ATTR)); LogLog.debug("Threshold =\"" + thresholdStr +"\"."); if(!"".equals(thresholdStr) && !"null".equals(thresholdStr)) { repository.setThreshold(thresholdStr); } //Hashtable appenderBag = new Hashtable(11); /* Building Appender objects, placing them in a local namespace for future reference */ // First configure each category factory under the root element. // Category factories need to be configured before any of // categories they support. // String tagName = null; Element currentElement = null; Node currentNode = null; NodeList children = element.getChildNodes(); final int length = children.getLength(); for (int loop = 0; loop < length; loop++) { currentNode = children.item(loop); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { currentElement = (Element) currentNode; tagName = currentElement.getTagName(); if (tagName.equals(CATEGORY_FACTORY_TAG) || tagName.equals(LOGGER_FACTORY_TAG)) { parseCategoryFactory(currentElement); } } } for (int loop = 0; loop < length; loop++) { currentNode = children.item(loop); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { currentElement = (Element) currentNode; tagName = currentElement.getTagName(); if (tagName.equals(CATEGORY) || tagName.equals(LOGGER)) { parseCategory(currentElement); } else if (tagName.equals(ROOT_TAG)) { parseRoot(currentElement); } else if(tagName.equals(RENDERER_TAG)) { parseRenderer(currentElement); } else if (!(tagName.equals(APPENDER_TAG) || tagName.equals(CATEGORY_FACTORY_TAG) || tagName.equals(LOGGER_FACTORY_TAG))) { quietParseUnrecognizedElement(repository, currentElement, props); } } } } protected String subst(final String value) { return subst(value, props); } /** * Substitutes property value for any references in expression. * * @param value value from configuration file, may contain * literal text, property references or both * @param props properties. * @return evaluated expression, may still contain expressions * if unable to expand. * @since 1.2.15 */ public static String subst(final String value, final Properties props) { try { return OptionConverter.substVars(value, props); } catch (IllegalArgumentException e) { LogLog.warn("Could not perform variable substitution.", e); return value; } } /** * Sets a parameter based from configuration file content. * * @param elem param element, may not be null. * @param propSetter property setter, may not be null. * @param props properties * @since 1.2.15 */ public static void setParameter(final Element elem, final PropertySetter propSetter, final Properties props) { String name = subst(elem.getAttribute("name"), props); String value = (elem.getAttribute("value")); value = subst(OptionConverter.convertSpecialChars(value), props); propSetter.setProperty(name, value); } /** * Creates an OptionHandler and processes any nested param elements * but does not call activateOptions. If the class also supports * UnrecognizedElementParser, the parseUnrecognizedElement method * will be call for any child elements other than param. * * @param element element, may not be null. * @param props properties * @param expectedClass interface or class expected to be implemented * by created class * @return created class or null. * @throws Exception thrown if the contain object should be abandoned. * @since 1.2.15 */ public static OptionHandler parseElement(final Element element, final Properties props, final Class expectedClass) throws Exception { String clazz = subst(element.getAttribute("class"), props); Object instance = OptionConverter.instantiateByClassName(clazz, expectedClass, null); if (instance instanceof OptionHandler) { OptionHandler optionHandler = (OptionHandler) instance; PropertySetter propSetter = new PropertySetter(optionHandler); NodeList children = element.getChildNodes(); final int length = children.getLength(); for (int loop = 0; loop < length; loop++) { Node currentNode = children.item(loop); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { Element currentElement = (Element) currentNode; String tagName = currentElement.getTagName(); if (tagName.equals("param")) { setParameter(currentElement, propSetter, props); } else { parseUnrecognizedElement(instance, currentElement, props); } } } return optionHandler; } return null; } private static class XMLWatchdog extends FileWatchdog { XMLWatchdog(String filename) { super(filename); } /** Call {@link DOMConfigurator#configure(String)} with the filename to reconfigure log4j. */ public void doOnChange() { new DOMConfigurator().doConfigure(filename, LogManager.getLoggerRepository()); } } /** * An {@link EntityResolver} specifically designed to return * log4j.dtd which is embedded within the log4j jar * file. * * @author Paul Austin * */ private static final class Log4jEntityResolver implements EntityResolver { public InputSource resolveEntity (String publicId, String systemId) { if (systemId.endsWith("log4j.dtd")) { InputStream in = Log4jEntityResolver.class.getResourceAsStream("log4j.dtd"); if (in == null) { LogLog.warn("Could not find [log4j.dtd] using [" + Log4jEntityResolver.class.getClassLoader() + "] class loader, parsed without DTD."); in = new ByteArrayInputStream(new byte[0]); } return new InputSource(in); } else { return null; } } } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/extras/SoundAppender.java000066400000000000000000000060111252742764200302010ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.extras; import java.applet.Applet; import java.applet.AudioClip; import java.net.MalformedURLException; import java.net.URL; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.helpers.LogLog; /** * This class is equivalent to org.apache.log4j.varia.SoundAppender * except for a package change to aid in use with OSGi. * * Plays a sound clip created using Applet.newAudioClip when an event is received. * * If the audio format is not supported, a message stating the SoundAppender could * not be initialized is logged. * * Use a filter in combination with this appender to control when the appender is * triggered. * * For example, in the appender definition, include a LevelMatchFilter configured * to accept WARN or greater, followed by a DenyAllFilter. * * @author Scott Deboy * */ public final class SoundAppender extends AppenderSkeleton { private AudioClip clip; private String audioURL; public SoundAppender() { } /** * Attempt to initialize the appender by creating a reference to an AudioClip. * * Will log a message if format is not supported, file not found, etc. * */ public void activateOptions() { /* * AudioSystem.getAudioInputStream requires jdk 1.3, * so we use applet.newaudioclip instead * */ try { clip = Applet.newAudioClip(new URL(audioURL)); } catch (MalformedURLException mue) { LogLog.error("unable to initialize SoundAppender", mue);} if (clip == null) { LogLog.error("Unable to initialize SoundAppender"); } } /** * Accessor * * @return audio file */ public String getAudioURL() { return audioURL; } /** * Mutator - common format for a file-based url: * file:///c:/path/someaudioclip.wav * * @param audioURL */ public void setAudioURL(String audioURL) { this.audioURL = audioURL; } /** * Play the sound if an event is being processed */ protected void append(LoggingEvent event) { if (clip != null) { clip.play(); } } public void close() { //nothing to do } /** * Gets whether appender requires a layout. * @return false */ public boolean requiresLayout() { return false; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/extras/UtilLoggingLevel.java000066400000000000000000000144171252742764200306570ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.extras; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Level; /** * This class is identical to org.apache.log4j.helpers.UtilLoggingLevel * except for a package change to aid in use with OSGi. * * An extension of the Level class that provides support for java.util.logging * Levels. * * @author Scott Deboy (sdeboy@apache.org) */ public class UtilLoggingLevel extends Level { /** * Serialization version id. */ private static final long serialVersionUID = 909301162611820211L; /** * Numerical value for SEVERE. */ public static final int SEVERE_INT = 17000; /** * Numerical value for WARNING. */ public static final int WARNING_INT = 16000; /** * Numerical value for INFO. */ public static final int INFO_INT = 15000; /** * Numerical value for CONFIG. */ public static final int CONFIG_INT = 14000; /** * Numerical value for FINE. */ public static final int FINE_INT = 13000; /** * Numerical value for FINER. */ public static final int FINER_INT = 12000; /** * Numerical value for FINEST. */ public static final int FINEST_INT = 11000; /** * Numerical value for UNKNOWN. */ public static final int UNKNOWN_INT = 10000; /** * SEVERE. */ public static final UtilLoggingLevel SEVERE = new UtilLoggingLevel(SEVERE_INT, "SEVERE", 0); /** * WARNING. */ public static final UtilLoggingLevel WARNING = new UtilLoggingLevel(WARNING_INT, "WARNING", 4); /** * INFO. */ public static final UtilLoggingLevel INFO = new UtilLoggingLevel(INFO_INT, "INFO", 5); /** * CONFIG. */ public static final UtilLoggingLevel CONFIG = new UtilLoggingLevel(CONFIG_INT, "CONFIG", 6); /** * FINE. */ public static final UtilLoggingLevel FINE = new UtilLoggingLevel(FINE_INT, "FINE", 7); /** * FINER. */ public static final UtilLoggingLevel FINER = new UtilLoggingLevel(FINER_INT, "FINER", 8); /** * FINEST. */ public static final UtilLoggingLevel FINEST = new UtilLoggingLevel(FINEST_INT, "FINEST", 9); /** * Create new instance. * @param level numeric value for level. * @param levelStr symbolic name for level. * @param syslogEquivalent Equivalent syslog severity. */ protected UtilLoggingLevel(final int level, final String levelStr, final int syslogEquivalent) { super(level, levelStr, syslogEquivalent); } /** * Convert an integer passed as argument to a level. If the * conversion fails, then this method returns the specified default. * @param val numeric value. * @param defaultLevel level to be returned if no level matches * numeric value. * @return matching level or default level. */ public static UtilLoggingLevel toLevel(final int val, final UtilLoggingLevel defaultLevel) { switch (val) { case SEVERE_INT: return SEVERE; case WARNING_INT: return WARNING; case INFO_INT: return INFO; case CONFIG_INT: return CONFIG; case FINE_INT: return FINE; case FINER_INT: return FINER; case FINEST_INT: return FINEST; default: return defaultLevel; } } /** * Gets level matching numeric value. * @param val numeric value. * @return matching level or UtilLoggerLevel.FINEST if no match. */ public static Level toLevel(final int val) { return toLevel(val, FINEST); } /** * Gets list of supported levels. * @return list of supported levels. */ public static List getAllPossibleLevels() { ArrayList list = new ArrayList(); list.add(FINE); list.add(FINER); list.add(FINEST); list.add(INFO); list.add(CONFIG); list.add(WARNING); list.add(SEVERE); return list; } /** * Get level with specified symbolic name. * @param s symbolic name. * @return matching level or Level.DEBUG if no match. */ public static Level toLevel(final String s) { return toLevel(s, Level.DEBUG); } /** * Get level with specified symbolic name. * @param sArg symbolic name. * @param defaultLevel level to return if no match. * @return matching level or defaultLevel if no match. */ public static Level toLevel(final String sArg, final Level defaultLevel) { if (sArg == null) { return defaultLevel; } String s = sArg.toUpperCase(); if (s.equals("SEVERE")) { return SEVERE; } //if(s.equals("FINE")) return Level.FINE; if (s.equals("WARNING")) { return WARNING; } if (s.equals("INFO")) { return INFO; } if (s.equals("CONFI")) { return CONFIG; } if (s.equals("FINE")) { return FINE; } if (s.equals("FINER")) { return FINER; } if (s.equals("FINEST")) { return FINEST; } return defaultLevel; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/extras/XSLTLayout.java000066400000000000000000000433331252742764200274320ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.extras; import org.apache.log4j.Layout; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.helpers.MDCKeySetExtractor; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.LocationInfo; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.Templates; import javax.xml.transform.Transformer; import javax.xml.transform.sax.TransformerHandler; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.stream.StreamSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.dom.DOMSource; import javax.xml.parsers.DocumentBuilderFactory; import java.io.InputStream; import java.io.ByteArrayOutputStream; import java.io.ByteArrayInputStream; import java.util.Set; import java.util.Properties; import java.util.Arrays; import java.util.TimeZone; import java.nio.charset.Charset; import java.nio.ByteBuffer; import org.apache.log4j.pattern.CachedDateFormat; import java.text.SimpleDateFormat; import org.w3c.dom.Document; import org.xml.sax.helpers.AttributesImpl; /** * This class is identical to org.apache.log4j.xml.XSLTLayout * except for a change in package to aid in use with OSGi. * * * XSLTLayout transforms each event as a document using * a specified or default XSLT transform. The default * XSLT transform produces a result similar to XMLLayout. * * When used with a FileAppender or similar, the transformation of * an event will be appended to the results for previous * transforms. If each transform results in an XML element, then * resulting file will only be an XML entity * since an XML document requires one and only one top-level element. * To process the entity, reference it in a XML document like so: * *
 *  <!DOCTYPE log4j:eventSet [<!ENTITY data SYSTEM "data.xml">]>
 *
 *  <log4j:eventSet xmlns:log4j="http://jakarta.apache.org/log4j/">
 *    &data
 *  </log4j:eventSet>
 *
 * 
* * The layout will detect the encoding and media-type specified in * the transform. If no encoding is specified in the transform, * an xsl:output element specifying the US-ASCII encoding will be inserted * before processing the transform. If an encoding is specified in the transform, * the same encoding should be explicitly specified for the appender. * * Extracting MDC values can be expensive when used with log4j releases * prior to 1.2.15. Output of MDC values is enabled by default * but be suppressed by setting properties to false. * * Extracting location info can be expensive regardless of log4j version. * Output of location info is disabled by default but can be enabled * by setting locationInfo to true. * * Embedded transforms in XML configuration should not * depend on namespace prefixes defined earlier in the document * as namespace aware parsing in not generally performed when * using DOMConfigurator. The transform will serialize * and reparse to get the namespace aware document needed. * */ public final class XSLTLayout extends Layout implements org.apache.log4j.xml.UnrecognizedElementHandler { /** * Namespace for XSLT. */ private static final String XSLT_NS = "http://www.w3.org/1999/XSL/Transform"; /** * Namespace for log4j events. */ private static final String LOG4J_NS = "http://jakarta.apache.org/log4j/"; /** * Whether location information should be written. */ private boolean locationInfo = false; /** * media-type (mime type) extracted from XSLT transform. */ private String mediaType = "text/plain"; /** * Encoding extracted from XSLT transform. */ private Charset encoding; /** * Transformer factory. */ private SAXTransformerFactory transformerFactory; /** * XSLT templates. */ private Templates templates; /** * Output stream. */ private final ByteArrayOutputStream outputStream; /** * Whether throwable information should be ignored. */ private boolean ignoresThrowable = false; /** * Whether properties should be extracted. */ private boolean properties = true; /** * Whether activateOptions has been called. */ private boolean activated = false; /** * DateFormat for UTC time. */ private final CachedDateFormat utcDateFormat; /** * Default constructor. * */ public XSLTLayout() { outputStream = new ByteArrayOutputStream(); transformerFactory = (SAXTransformerFactory) TransformerFactory.newInstance(); SimpleDateFormat zdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); zdf.setTimeZone(TimeZone.getTimeZone("UTC")); utcDateFormat = new CachedDateFormat(zdf, 1000); } /** * {@inheritDoc} */ public synchronized String getContentType() { return mediaType; } /** * The LocationInfo option takes a boolean value. By default, it is * set to false which means there will be no location information output by * this layout. If the the option is set to true, then the file name and line * number of the statement at the origin of the log statement will be output. * *

* If you are embedding this layout within an {@link * org.apache.log4j.net.SMTPAppender} then make sure to set the * LocationInfo option of that appender as well. * * @param flag new value. */ public synchronized void setLocationInfo(final boolean flag) { locationInfo = flag; } /** * Gets whether location info should be output. * @return if location is output. */ public synchronized boolean getLocationInfo() { return locationInfo; } /** * Sets whether MDC key-value pairs should be output, default false. * @param flag new value. */ public synchronized void setProperties(final boolean flag) { properties = flag; } /** * Gets whether MDC key-value pairs should be output. * @return true if MDC key-value pairs are output. */ public synchronized boolean getProperties() { return properties; } /** {@inheritDoc} */ public synchronized void activateOptions() { if (templates == null) { try { InputStream is = XSLTLayout.class.getResourceAsStream("default.xslt"); StreamSource ss = new StreamSource(is); templates = transformerFactory.newTemplates(ss); encoding = Charset.forName("US-ASCII"); mediaType = "text/plain"; } catch (Exception ex) { LogLog.error("Error loading default.xslt", ex); } } activated = true; } /** * Gets whether throwables should not be output. * @return true if throwables should not be output. */ public synchronized boolean ignoresThrowable() { return ignoresThrowable; } /** * Sets whether throwables should not be output. * @param ignoresThrowable if true, throwables should not be output. */ public synchronized void setIgnoresThrowable(boolean ignoresThrowable) { this.ignoresThrowable = ignoresThrowable; } /** * {@inheritDoc} */ public synchronized String format(final LoggingEvent event) { if (!activated) { activateOptions(); } if (templates != null && encoding != null) { outputStream.reset(); try { TransformerHandler transformer = transformerFactory.newTransformerHandler(templates); transformer.setResult(new StreamResult(outputStream)); transformer.startDocument(); // // event element // AttributesImpl attrs = new AttributesImpl(); attrs.addAttribute(null, "logger", "logger", "CDATA", event.getLoggerName()); attrs.addAttribute(null, "timestamp", "timestamp", "CDATA", Long.toString(event.timeStamp)); attrs.addAttribute(null, "level", "level", "CDATA", event.getLevel().toString()); attrs.addAttribute(null, "thread", "thread", "CDATA", event.getThreadName()); StringBuffer buf = new StringBuffer(); utcDateFormat.format(event.timeStamp, buf); attrs.addAttribute(null, "time", "time", "CDATA", buf.toString()); transformer.startElement(LOG4J_NS, "event", "event", attrs); attrs.clear(); // // message element // transformer.startElement(LOG4J_NS, "message", "message", attrs); String msg = event.getRenderedMessage(); if (msg != null && msg.length() > 0) { transformer.characters(msg.toCharArray(), 0, msg.length()); } transformer.endElement(LOG4J_NS, "message", "message"); // // NDC element // String ndc = event.getNDC(); if (ndc != null) { transformer.startElement(LOG4J_NS, "NDC", "NDC", attrs); char[] ndcChars = ndc.toCharArray(); transformer.characters(ndcChars, 0, ndcChars.length); transformer.endElement(LOG4J_NS, "NDC", "NDC"); } // // throwable element unless suppressed // if (!ignoresThrowable) { String[] s = event.getThrowableStrRep(); if (s != null) { transformer.startElement(LOG4J_NS, "throwable", "throwable", attrs); char[] nl = new char[] { '\n' }; for (int i = 0; i < s.length; i++) { char[] line = s[i].toCharArray(); transformer.characters(line, 0, line.length); transformer.characters(nl, 0, nl.length); } transformer.endElement(LOG4J_NS, "throwable", "throwable"); } } // // location info unless suppressed // // if (locationInfo) { LocationInfo locationInfo = event.getLocationInformation(); attrs.addAttribute(null, "class", "class", "CDATA", locationInfo.getClassName()); attrs.addAttribute(null, "method", "method", "CDATA", locationInfo.getMethodName()); attrs.addAttribute(null, "file", "file", "CDATA", locationInfo.getFileName()); attrs.addAttribute(null, "line", "line", "CDATA", locationInfo.getLineNumber()); transformer.startElement(LOG4J_NS, "locationInfo", "locationInfo", attrs); transformer.endElement(LOG4J_NS, "locationInfo", "locationInfo"); } if (properties) { // // write MDC contents out as properties element // Set mdcKeySet = MDCKeySetExtractor.INSTANCE.getPropertyKeySet(event); if ((mdcKeySet != null) && (mdcKeySet.size() > 0)) { attrs.clear(); transformer.startElement(LOG4J_NS, "properties", "properties", attrs); Object[] keys = mdcKeySet.toArray(); Arrays.sort(keys); for (int i = 0; i < keys.length; i++) { String key = keys[i].toString(); Object val = event.getMDC(key); attrs.clear(); attrs.addAttribute(null, "name", "name", "CDATA", key); attrs.addAttribute(null, "value", "value", "CDATA", val.toString()); transformer.startElement(LOG4J_NS, "data", "data", attrs); transformer.endElement(LOG4J_NS, "data", "data"); } } } transformer.endElement(LOG4J_NS, "event", "event"); transformer.endDocument(); String body = encoding.decode( ByteBuffer.wrap(outputStream.toByteArray())).toString(); outputStream.reset(); // // must remove XML declaration since it may // result in erroneous encoding info // if written by FileAppender in a different encoding if (body.startsWith(""); if (endDecl != -1) { for(endDecl += 2; endDecl < body.length() && (body.charAt(endDecl) == '\n' || body.charAt(endDecl) == '\r'); endDecl++); return body.substring(endDecl); } } return body; } catch (Exception ex) { LogLog.error("Error during transformation", ex); return ex.toString(); } } return "No valid transform or encoding specified."; } /** * Sets XSLT transform. * @param xsltdoc DOM document containing XSLT transform source, * may be modified. * @throws TransformerConfigurationException if transformer can not be * created. */ public void setTransform(final Document xsltdoc) throws TransformerConfigurationException { // // scan transform source for xsl:output elements // and extract encoding, media (mime) type and output method // String encodingName = null; mediaType = null; String method = null; NodeList nodes = xsltdoc.getElementsByTagNameNS( XSLT_NS, "output"); for(int i = 0; i < nodes.getLength(); i++) { Element outputElement = (Element) nodes.item(i); if (method == null || method.length() == 0) { method = outputElement.getAttributeNS(null, "method"); } if (encodingName == null || encodingName.length() == 0) { encodingName = outputElement.getAttributeNS(null, "encoding"); } if (mediaType == null || mediaType.length() == 0) { mediaType = outputElement.getAttributeNS(null, "media-type"); } } if (mediaType == null || mediaType.length() == 0) { if ("html".equals(method)) { mediaType = "text/html"; } else if ("xml".equals(method)) { mediaType = "text/xml"; } else { mediaType = "text/plain"; } } // // if encoding was not specified, // add xsl:output encoding=US-ASCII to XSLT source // if (encodingName == null || encodingName.length() == 0) { Element transformElement = xsltdoc.getDocumentElement(); Element outputElement = xsltdoc. createElementNS(XSLT_NS, "output"); outputElement.setAttributeNS(null, "encoding", "US-ASCII"); transformElement.insertBefore(outputElement, transformElement.getFirstChild()); encoding = Charset.forName("US-ASCII"); } else { encoding = Charset.forName(encodingName); } DOMSource transformSource = new DOMSource(xsltdoc); templates = transformerFactory.newTemplates(transformSource); } /** * {@inheritDoc} */ public boolean parseUnrecognizedElement(final Element element, final Properties props) throws Exception { if (XSLT_NS.equals(element.getNamespaceURI()) || element.getNodeName().indexOf("transform") != -1 || element.getNodeName().indexOf("stylesheet") != -1) { // // DOMConfigurator typically not namespace aware // serialize tree and reparse. ByteArrayOutputStream os = new ByteArrayOutputStream(); DOMSource source = new DOMSource(element); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(source, new StreamResult(os)); ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray()); DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); Document xsltdoc = domFactory.newDocumentBuilder().parse(is); setTransform(xsltdoc); return true; } return false; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/filter/000077500000000000000000000000001252742764200245505ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/filter/AndFilter.java000066400000000000000000000112561252742764200272700ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.filter; import org.apache.log4j.spi.Filter; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.OptionHandler; import org.apache.log4j.xml.UnrecognizedElementHandler; import org.w3c.dom.Element; import java.util.Properties; /** * A filter that 'and's the results of any number of contained filters together. * * For the filter to process events, all contained filters must return Filter.ACCEPT. * * If the contained filters do not return Filter.ACCEPT, Filter.NEUTRAL is returned. * * If acceptOnMatch is set to true, Filter.ACCEPT is returned. * If acceptOnMatch is set to false, Filter.DENY is returned. * * Here is an example config that will accept only events that contain BOTH * a DEBUG level AND 'test' in the message: * * * * * * * * * * * * * * * * * * To accept all events EXCEPT those events that contain a * DEBUG level and 'test' in the message: * change the AndFilter's acceptOnMatch param to false and remove the DenyAllFilter * * NOTE: If you are defining a filter that is only relying on logging event content * (no external or filter-managed state), you could opt instead * to use an ExpressionFilter with one of the following expressions: * * LEVEL == DEBUG && MSG ~= 'test' * or * ! ( LEVEL == DEBUG && MSG ~= 'test' ) * * XML configuration of this filter requires use of either log4j 1.2.15 or later or * org.apache.log4j.rolling.DOMConfigurator. * * @author Scott Deboy sdeboy@apache.org */ public class AndFilter extends Filter implements UnrecognizedElementHandler { Filter headFilter = null; Filter tailFilter = null; boolean acceptOnMatch = true; public void activateOptions() { } public void addFilter(final Filter filter) { if (headFilter == null) { headFilter = filter; tailFilter = filter; } else { tailFilter.next = filter; } } public void setAcceptOnMatch(final boolean acceptOnMatch) { this.acceptOnMatch = acceptOnMatch; } /** * If this event does not already contain location information, * evaluate the event against the expression. * * If the expression evaluates to true, generate a LocationInfo instance * by creating an exception and set this LocationInfo on the event. * * Returns {@link Filter#NEUTRAL} */ public int decide(final LoggingEvent event) { boolean accepted = true; Filter f = headFilter; while (f != null) { accepted = accepted && (Filter.ACCEPT == f.decide(event)); f = f.next; } if (accepted) { if(acceptOnMatch) { return Filter.ACCEPT; } return Filter.DENY; } return Filter.NEUTRAL; } /** * {@inheritDoc} */ public boolean parseUnrecognizedElement(final Element element, final Properties props) throws Exception { final String nodeName = element.getNodeName(); if ("filter".equals(nodeName)) { OptionHandler filter = org.apache.log4j.extras.DOMConfigurator.parseElement( element, props, Filter.class); if (filter instanceof Filter) { filter.activateOptions(); this.addFilter((Filter) filter); } return true; } return false; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/filter/DenyAllFilter.java000066400000000000000000000040131252742764200301070ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.filter; import org.apache.log4j.spi.Filter; import org.apache.log4j.spi.LoggingEvent; /** This filter drops all logging events.

You can add this filter to the end of a filter chain to switch from the default "accept all unless instructed otherwise" filtering behaviour to a "deny all unless instructed otherwise" behaviour. @author Ceki Gülcü @since 0.9.0 */ public class DenyAllFilter extends Filter { /** Returns null as there are no options. @deprecated We now use JavaBeans introspection to configure components. Options strings are no longer needed. */ public String[] getOptionStrings() { return null; } /** No options to set. @deprecated Use the setter method for the option directly instead of the generic setOption method. */ public void setOption(String key, String value) { } /** Always returns the integer constant {@link Filter#DENY} regardless of the {@link LoggingEvent} parameter. @param event The LoggingEvent to filter. @return Always returns {@link Filter#DENY}. */ public int decide(LoggingEvent event) { return Filter.DENY; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/filter/ExpressionFilter.java000066400000000000000000000117001252742764200307170ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.filter; import org.apache.log4j.rule.ExpressionRule; import org.apache.log4j.rule.Rule; import org.apache.log4j.spi.Filter; import org.apache.log4j.spi.LoggingEvent; /** * A filter supporting complex expressions - supports both infix and postfix * expressions (infix expressions must first be converted to postfix prior * to processing). *

*

See org.apache.log4j.chainsaw.LoggingEventFieldResolver.java * for the correct names for logging event fields * used when building expressions. *

*

See org.apache.log4j.chainsaw.rule package * for a list of available * rules which can be applied using the expression syntax. *

*

See org.apache.log4j.chainsaw.RuleFactory for the symbols * used to activate the corresponding rules. *

* NOTE: Grouping using parentheses is supported - * all tokens must be separated by spaces, and * operands which contain spaces are not yet supported. *

* Example: *

* In order to build a filter that displays all messages with * infomsg-45 or infomsg-44 in the message, * as well as all messages with a level of WARN or higher, * build an expression using * the LikeRule (supports java.util.regex based regular expressions) and the InequalityRule. * ( MSG LIKE infomsg-4[4,5] ) && ( LEVEL >= WARN ) *

* Three options are required: * Expression - the expression to match * ConvertInFixToPostFix - convert from infix to posfix (default true) * AcceptOnMatch - true or false (default true) *

* Meaning of AcceptToMatch: * If there is a match between the value of the * Expression option and the {@link LoggingEvent} and AcceptOnMatch is true, * the {@link #decide} method returns {@link Filter#ACCEPT}. *

* If there is a match between the value of the * Expression option and the {@link LoggingEvent} and AcceptOnMatch is false, * {@link Filter#DENY} is returned. *

* If there is no match, {@link Filter#NEUTRAL} is returned. * * @author Scott Deboy sdeboy@apache.org */ public class ExpressionFilter extends Filter { /** * accept on match. */ boolean acceptOnMatch = true; /** * Convert in-fix to post-fix. */ boolean convertInFixToPostFix = true; /** * Expression. */ String expression; /** * Evaluated rule. */ Rule expressionRule; /** * {@inheritDoc} */ public void activateOptions() { expressionRule = ExpressionRule.getRule(expression, !convertInFixToPostFix); } /** * Set exp. * @param exp exp. */ public void setExpression(final String exp) { this.expression = exp; } /** * Get expression. * @return expression. */ public String getExpression() { return expression; } /** * Set convert in-fix to post-fix. * @param newValue new value. */ public void setConvertInFixToPostFix(final boolean newValue) { this.convertInFixToPostFix = newValue; } /** * Get in-fix to post-fix conversion setting. * @return true if in-fix expressions are converted to post-fix. */ public boolean getConvertInFixToPostFix() { return convertInFixToPostFix; } /** * Set whether filter should accept events if they match the expression. * @param newValue if true, accept on match. */ public void setAcceptOnMatch(final boolean newValue) { this.acceptOnMatch = newValue; } /** * Gets whether filter accepts matching or non-matching events. * @return if true, accept matching events. */ public boolean getAcceptOnMatch() { return acceptOnMatch; } /** * Determines if event matches the filter. * @param event logging event; * @return {@link Filter#NEUTRAL} is there is no string match. */ public int decide(final LoggingEvent event) { if (expressionRule.evaluate(event, null)) { if (acceptOnMatch) { return Filter.ACCEPT; } else { return Filter.DENY; } } return Filter.NEUTRAL; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/filter/LevelMatchFilter.java000066400000000000000000000061041252742764200306060ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.filter; import org.apache.log4j.Level; import org.apache.log4j.helpers.OptionConverter; import org.apache.log4j.spi.Filter; import org.apache.log4j.spi.LoggingEvent; /** This is a very simple filter based on level matching.

The filter admits two options LevelToMatch and AcceptOnMatch. If there is an exact match between the value of the LevelToMatch option and the level of the {@link org.apache.log4j.spi.LoggingEvent}, then the {@link #decide} method returns {@link org.apache.log4j.spi.Filter#ACCEPT} in case the AcceptOnMatch option value is set to true, if it is false then {@link org.apache.log4j.spi.Filter#DENY} is returned. If there is no match, {@link org.apache.log4j.spi.Filter#NEUTRAL} is returned. @author Ceki Gülcü @since 1.2 */ public class LevelMatchFilter extends Filter { /** Do we return ACCEPT when a match occurs. Default is true. */ boolean acceptOnMatch = true; /** */ Level levelToMatch; public void setLevelToMatch(String level) { levelToMatch = OptionConverter.toLevel(level, null); } public String getLevelToMatch() { return (levelToMatch == null) ? null : levelToMatch.toString(); } public void setAcceptOnMatch(boolean acceptOnMatch) { this.acceptOnMatch = acceptOnMatch; } public boolean getAcceptOnMatch() { return acceptOnMatch; } /** Return the decision of this filter. Returns {@link Filter#NEUTRAL} if the LevelToMatch option is not set or if there is not match. Otherwise, if there is a match, then the returned decision is {@link Filter#ACCEPT} if the AcceptOnMatch property is set to true. The returned decision is {@link Filter#DENY} if the AcceptOnMatch property is set to false. */ public int decide(LoggingEvent event) { if (this.levelToMatch == null) { return Filter.NEUTRAL; } boolean matchOccured = false; if (this.levelToMatch.equals(event.getLevel())) { matchOccured = true; } if (matchOccured) { if (this.acceptOnMatch) { return Filter.ACCEPT; } else { return Filter.DENY; } } else { return Filter.NEUTRAL; } } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/filter/LevelRangeFilter.java000066400000000000000000000103051252742764200306040ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.filter; import org.apache.log4j.Level; import org.apache.log4j.spi.Filter; import org.apache.log4j.spi.LoggingEvent; /** This is a very simple filter based on level matching, which can be used to reject messages with priorities outside a certain range.

The filter admits three options LevelMin, LevelMax and AcceptOnMatch.

If the level of the {@link org.apache.log4j.spi.LoggingEvent} is not between Min and Max (inclusive), then {@link org.apache.log4j.spi.Filter#DENY} is returned.

If the Logging event level is within the specified range, then if AcceptOnMatch is true, {@link org.apache.log4j.spi.Filter#ACCEPT} is returned, and if AcceptOnMatch is false, {@link org.apache.log4j.spi.Filter#NEUTRAL} is returned.

If LevelMin is not defined, then there is no minimum acceptable level (ie a level is never rejected for being too "low"/unimportant). If LevelMax is not defined, then there is no maximum acceptable level (ie a level is never rejected for beeing too "high"/important).

Refer to the {@link org.apache.log4j.AppenderSkeleton#setThreshold setThreshold} method available to all appenders extending {@link org.apache.log4j.AppenderSkeleton} for a more convenient way to filter out events by level. @author Simon Kitching @author based on code by Ceki Gülcü */ public class LevelRangeFilter extends Filter { /** Do we return ACCEPT when a match occurs. Default is false, so that later filters get run by default */ boolean acceptOnMatch = false; Level levelMin; Level levelMax; /** Return the decision of this filter. */ public int decide(LoggingEvent event) { if(this.levelMin != null && event.getLevel().isGreaterOrEqual(levelMin) == false) { // level of event is less than minimum return Filter.DENY; } if(this.levelMax != null && event.getLevel().toInt() > levelMax.toInt()) { // level of event is greater than maximum // Alas, there is no Level.isGreater method. and using // a combo of isGreaterOrEqual && !Equal seems worse than // checking the int values of the level objects.. return Filter.DENY; } if (acceptOnMatch) { // this filter set up to bypass later filters and always return // accept if level in range return Filter.ACCEPT; } else { // event is ok for this filter; allow later filters to have a look.. return Filter.NEUTRAL; } } /** Get the value of the LevelMax option. */ public Level getLevelMax() { return levelMax; } /** Get the value of the LevelMin option. */ public Level getLevelMin() { return levelMin; } /** Get the value of the AcceptOnMatch option. */ public boolean getAcceptOnMatch() { return acceptOnMatch; } /** Set the LevelMax option. */ public void setLevelMax(Level levelMax) { this.levelMax = levelMax; } /** Set the LevelMin option. */ public void setLevelMin(Level levelMin) { this.levelMin = levelMin; } /** Set the AcceptOnMatch option. */ public void setAcceptOnMatch(boolean acceptOnMatch) { this.acceptOnMatch = acceptOnMatch; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/filter/LocationInfoFilter.java000066400000000000000000000061621252742764200311520ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.filter; import org.apache.log4j.rule.ExpressionRule; import org.apache.log4j.rule.Rule; import org.apache.log4j.spi.Filter; import org.apache.log4j.spi.LoggingEvent; /** * Location information is usually specified at the appender level - * all events associated * with an appender either create and parse stack traces or they do not. * This is an expensive operation and in some cases not needed * for all events associated with an appender. * * This filter creates event-level location information only * if the provided expression evaluates to true. * * For information on expression syntax, * see org.apache.log4j.rule.ExpressionRule * * @author Scott Deboy sdeboy@apache.org */ public class LocationInfoFilter extends Filter { /** * Convert to in-fix to post-fix. */ boolean convertInFixToPostFix = true; /** * Expression. */ String expression; /** * Compiled expression. */ Rule expressionRule; /** * {@inheritDoc} */ public void activateOptions() { expressionRule = ExpressionRule.getRule(expression, !convertInFixToPostFix); } /** * Set expression. * @param exp expression. */ public void setExpression(final String exp) { this.expression = exp; } /** * Get expression. * @return expression. */ public String getExpression() { return expression; } /** * Set whether in-fix expressions should be converted to post-fix. * @param newValue if true, convert/ */ public void setConvertInFixToPostFix(final boolean newValue) { this.convertInFixToPostFix = newValue; } /** * Set whether in-fix expressions should be converted to post-fix. * @return if true, expressions are converted. */ public boolean getConvertInFixToPostFix() { return convertInFixToPostFix; } /** * If this event does not already contain location information, * evaluate the event against the expression. * * If the expression evaluates to true, * force generation of location information by * calling getLocationInfo. * * @param event event * @return Filter.NEUTRAL. */ public int decide(final LoggingEvent event) { if (expressionRule.evaluate(event, null)) { event.getLocationInformation(); } return Filter.NEUTRAL; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/filter/LoggerMatchFilter.java000066400000000000000000000061171252742764200307620ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.filter; import org.apache.log4j.spi.Filter; import org.apache.log4j.spi.LoggingEvent; /** This is a very simple filter based on logger name matching.

The filter admits two options LoggerToMatch and AcceptOnMatch. If there is an exact match between the value of the LoggerToMatch option and the logger of the {@link org.apache.log4j.spi.LoggingEvent}, then the {@link #decide} method returns {@link org.apache.log4j.spi.Filter#ACCEPT} in case the AcceptOnMatch option value is set to true, if it is false then {@link org.apache.log4j.spi.Filter#DENY} is returned. If there is no match, {@link org.apache.log4j.spi.Filter#NEUTRAL} is returned. A loggerToMatch of "root" matches both the root logger and a logger named "root". */ public class LoggerMatchFilter extends Filter { /** Do we return ACCEPT when a match occurs. Default is true. */ private boolean acceptOnMatch = true; /** * Logger name, may be null or empty in which case it matches root. */ private String loggerToMatch = "root"; /** * Sets logger name. * @param logger logger name. */ public void setLoggerToMatch(final String logger) { if (logger == null) { loggerToMatch = "root"; } else { loggerToMatch = logger; } } /** * Gets logger name. * @return logger name. */ public String getLoggerToMatch() { return loggerToMatch; } /** * Sets whether a match should result in acceptance. * @param acceptOnMatch if true, accept if logger name matches, otherwise reject. */ public void setAcceptOnMatch(final boolean acceptOnMatch) { this.acceptOnMatch = acceptOnMatch; } /** * Gets whether a match should result in acceptance. * @return true if event is accepted if logger name matches. */ public boolean getAcceptOnMatch() { return acceptOnMatch; } /** * {@inheritDoc} */ public int decide(final LoggingEvent event) { boolean matchOccured = loggerToMatch.equals(event.getLoggerName()); if (matchOccured) { if (this.acceptOnMatch) { return Filter.ACCEPT; } else { return Filter.DENY; } } else { return Filter.NEUTRAL; } } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/filter/StringMatchFilter.java000066400000000000000000000046161252742764200310130ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.filter; import org.apache.log4j.spi.Filter; import org.apache.log4j.spi.LoggingEvent; /** This is a very simple filter based on string matching.

The filter admits two options StringToMatch and AcceptOnMatch. If there is a match between the value of the StringToMatch option and the message of the {@link LoggingEvent}, then the {@link #decide(LoggingEvent)} method returns {@link org.apache.log4j.spi.Filter#ACCEPT} if the AcceptOnMatch option value is true, if it is false then {@link org.apache.log4j.spi.Filter#DENY} is returned. If there is no match, {@link org.apache.log4j.spi.Filter#NEUTRAL} is returned. @author Ceki Gülcü @since 0.9.0 */ public class StringMatchFilter extends Filter { boolean acceptOnMatch = true; String stringToMatch; public void setStringToMatch(String s) { stringToMatch = s; } public String getStringToMatch() { return stringToMatch; } public void setAcceptOnMatch(boolean acceptOnMatch) { this.acceptOnMatch = acceptOnMatch; } public boolean getAcceptOnMatch() { return acceptOnMatch; } /** Returns {@link Filter#NEUTRAL} is there is no string match. */ public int decide(LoggingEvent event) { String msg = event.getRenderedMessage(); if(msg == null || stringToMatch == null) return Filter.NEUTRAL; if( msg.indexOf(stringToMatch) == -1 ) { return Filter.NEUTRAL; } else { // we've got a match if(acceptOnMatch) { return Filter.ACCEPT; } else { return Filter.DENY; } } } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/filter/TimeFilter.java000066400000000000000000000104111252742764200274540ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.filter; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.spi.Filter; import org.apache.log4j.spi.LoggingEvent; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.TimeZone; /** * Filters events that fall within a specified time period * in each day. * */ public final class TimeFilter extends Filter { private boolean acceptOnMatch; /** * Starting offset from midnight in milliseconds. */ private long start; /** * Ending offset from midnight in milliseconds. */ private long end; /** * Timezone. */ private Calendar calendar; /** * Length of hour in milliseconds. */ private static final long HOUR_MS = 3600000; /** * Length of minute in milliseconds. */ private static final long MINUTE_MS = 60000; /** * Length of second in milliseconds. */ private static final long SECOND_MS = 1000; /** * Constructor. */ public TimeFilter() { acceptOnMatch = true; start = 0; end = Long.MAX_VALUE; calendar = Calendar.getInstance(); } /** * Set start (inclusive) of time span. * @param s string representation of start time as HH:mm:ss. */ public void setStart(final String s) { SimpleDateFormat stf = new SimpleDateFormat("HH:mm:ss"); stf.setTimeZone(TimeZone.getTimeZone("UTC")); try { start = stf.parse(s).getTime(); } catch(ParseException ex) { LogLog.warn("Error parsing start value " + s, ex); } } /** * Set end (exclusive) of time span. * @param s string representation of end time as HH:mm:ss. */ public void setEnd(final String s) { SimpleDateFormat stf = new SimpleDateFormat("HH:mm:ss"); stf.setTimeZone(TimeZone.getTimeZone("UTC")); try { end = stf.parse(s).getTime(); } catch(ParseException ex) { LogLog.warn("Error parsing end value " + s, ex); } } /** * Set timezone. * @param s time zone. */ public void setTimeZone(final String s) { if (s == null) { calendar = Calendar.getInstance(); } else { calendar = Calendar.getInstance(TimeZone.getTimeZone(s)); } } /** * Sets whether an event within the timespan should be accepted or denied. * @param acceptOnMatch true if matching event should be accepted. */ public synchronized void setAcceptOnMatch(boolean acceptOnMatch) { this.acceptOnMatch = acceptOnMatch; } /** * Gets whether an event within the timespan should be accepted or denied. * @return true if matching event should be accepted. */ public synchronized boolean getAcceptOnMatch() { return acceptOnMatch; } /** {@inheritDoc} */ public int decide(final LoggingEvent event) { calendar.setTimeInMillis(event.timeStamp); // // get apparent number of milliseconds since midnight // (ignores extra or missing hour on daylight time changes). // long apparentOffset = calendar.get(Calendar.HOUR_OF_DAY) * HOUR_MS + calendar.get(Calendar.MINUTE) * MINUTE_MS + calendar.get(Calendar.SECOND) * SECOND_MS + calendar.get(Calendar.MILLISECOND); if (apparentOffset >= start && apparentOffset < end) { if (acceptOnMatch) { return Filter.ACCEPT; } else { return Filter.DENY; } } return Filter.NEUTRAL; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/pattern/000077500000000000000000000000001252742764200247405ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/pattern/ExtrasFormattingInfo.java000066400000000000000000000105141252742764200317210ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.pattern; /** * Modifies the output of a pattern converter for a specified minimum * and maximum width and alignment. * * * @author Jim Cakalic * @author Ceki Gülcü * @author Curt Arnold * */ public final class ExtrasFormattingInfo { /** * Array of spaces. */ private static final char[] SPACES = new char[] { ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' }; /** * Default instance. */ private static final ExtrasFormattingInfo DEFAULT = new ExtrasFormattingInfo(false, 0, Integer.MAX_VALUE); /** * Minimum length. */ private final int minLength; /** * Maximum length. */ private final int maxLength; /** * Alignment. */ private final boolean leftAlign; /** * Right truncation. * @since 1.2.17 */ private final boolean rightTruncate; /** * Creates new instance. * @param leftAlign left align if true. * @param minLength minimum length. * @param maxLength maximum length. * @deprecated since 1.2.17 */ public ExtrasFormattingInfo( final boolean leftAlign, final int minLength, final int maxLength) { this.leftAlign = leftAlign; this.minLength = minLength; this.maxLength = maxLength; this.rightTruncate = false; } /** * Creates new instance. * @param leftAlign left align if true. * @param rightTruncate right truncate if true. * @param minLength minimum length. * @param maxLength maximum length. * @since 1.2.17 */ public ExtrasFormattingInfo( final boolean leftAlign, final boolean rightTruncate, final int minLength, final int maxLength) { this.leftAlign = leftAlign; this.minLength = minLength; this.maxLength = maxLength; this.rightTruncate = rightTruncate; } /** * Gets default instance. * @return default instance. */ public static ExtrasFormattingInfo getDefault() { return DEFAULT; } /** * Determine if left aligned. * @return true if left aligned. */ public boolean isLeftAligned() { return leftAlign; } /** * Determine if right truncated. * @return true if right truncated. * @since 1.2.17 */ public boolean isRightTruncated() { return rightTruncate; } /** * Get minimum length. * @return minimum length. */ public int getMinLength() { return minLength; } /** * Get maximum length. * @return maximum length. */ public int getMaxLength() { return maxLength; } /** * Adjust the content of the buffer based on the specified lengths and alignment. * * @param fieldStart start of field in buffer. * @param buffer buffer to be modified. */ public void format(final int fieldStart, final StringBuffer buffer) { final int rawLength = buffer.length() - fieldStart; if (rawLength > maxLength) { if(rightTruncate) { buffer.setLength(fieldStart + maxLength); } else { buffer.delete(fieldStart, buffer.length() - maxLength); } } else if (rawLength < minLength) { if (leftAlign) { final int fieldEnd = buffer.length(); buffer.setLength(fieldStart + minLength); for (int i = fieldEnd; i < buffer.length(); i++) { buffer.setCharAt(i, ' '); } } else { int padLength = minLength - rawLength; for (; padLength > 8; padLength -= 8) { buffer.insert(fieldStart, SPACES); } buffer.insert(fieldStart, SPACES, 0, padLength); } } } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/pattern/ExtrasPatternParser.java000066400000000000000000000474361252742764200316020ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.pattern; import org.apache.log4j.helpers.Loader; import org.apache.log4j.helpers.LogLog; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; // Contributors: Nelson Minar <(nelson@monkey.org> // Igor E. Poteryaev // Reinhard Deschler /** * Most of the work of the {@link org.apache.log4j.EnhancedPatternLayout} class * is delegated to the ExtrasPatternParser class. *

It is this class that parses conversion patterns and creates * a chained list of {@link PatternConverter PatternConverters}. * * @author James P. Cakalic * @author Ceki Gülcü * @author Anders Kristensen * @author Paul Smith * @author Curt Arnold * */ public final class ExtrasPatternParser { /** * Escape character for format specifier. */ private static final char ESCAPE_CHAR = '%'; /** * Literal state. */ private static final int LITERAL_STATE = 0; /** * In converter name state. */ private static final int CONVERTER_STATE = 1; /** * Dot state. */ private static final int DOT_STATE = 3; /** * Min state. */ private static final int MIN_STATE = 4; /** * Max state. */ private static final int MAX_STATE = 5; /** * Standard format specifiers for EnhancedPatternLayout. */ private static final Map PATTERN_LAYOUT_RULES; /** * Standard format specifiers for rolling file appenders. */ private static final Map FILENAME_PATTERN_RULES; static { // We set the global rules in the static initializer of ExtrasPatternParser class Map rules = new HashMap(17); rules.put("c", LoggerPatternConverter.class); rules.put("logger", LoggerPatternConverter.class); rules.put("C", ClassNamePatternConverter.class); rules.put("class", ClassNamePatternConverter.class); rules.put("d", DatePatternConverter.class); rules.put("date", DatePatternConverter.class); rules.put("F", FileLocationPatternConverter.class); rules.put("file", FileLocationPatternConverter.class); rules.put("l", FullLocationPatternConverter.class); rules.put("L", LineLocationPatternConverter.class); rules.put("line", LineLocationPatternConverter.class); rules.put("m", MessagePatternConverter.class); rules.put("message", MessagePatternConverter.class); rules.put("n", LineSeparatorPatternConverter.class); rules.put("M", MethodLocationPatternConverter.class); rules.put("method", MethodLocationPatternConverter.class); rules.put("p", LevelPatternConverter.class); rules.put("level", LevelPatternConverter.class); rules.put("r", RelativeTimePatternConverter.class); rules.put("relative", RelativeTimePatternConverter.class); rules.put("t", ThreadPatternConverter.class); rules.put("thread", ThreadPatternConverter.class); rules.put("x", NDCPatternConverter.class); rules.put("ndc", NDCPatternConverter.class); rules.put("X", PropertiesPatternConverter.class); rules.put("properties", PropertiesPatternConverter.class); rules.put("sn", SequenceNumberPatternConverter.class); rules.put("sequenceNumber", SequenceNumberPatternConverter.class); rules.put("throwable", ThrowableInformationPatternConverter.class); PATTERN_LAYOUT_RULES = new ReadOnlyMap(rules); Map fnameRules = new HashMap(4); fnameRules.put("d", FileDatePatternConverter.class); fnameRules.put("date", FileDatePatternConverter.class); fnameRules.put("i", IntegerPatternConverter.class); fnameRules.put("index", IntegerPatternConverter.class); FILENAME_PATTERN_RULES = new ReadOnlyMap(fnameRules); } /** * Private constructor. */ private ExtrasPatternParser() { } /** * Get standard format specifiers for EnhancedPatternLayout. * @return read-only map of format converter classes keyed by format specifier strings. */ public static Map getPatternLayoutRules() { return PATTERN_LAYOUT_RULES; } /** * Get standard format specifiers for rolling file appender file specification. * @return read-only map of format converter classes keyed by format specifier strings. */ public static Map getFileNamePatternRules() { return FILENAME_PATTERN_RULES; } /** Extract the converter identifier found at position i. * * After this function returns, the variable i will point to the * first char after the end of the converter identifier. * * If i points to a char which is not a character acceptable at the * start of a unicode identifier, the value null is returned. * * @param lastChar last processed character. * @param pattern format string. * @param i current index into pattern format. * @param convBuf buffer to receive conversion specifier. * @param currentLiteral literal to be output in case format specifier in unrecognized. * @return position in pattern after converter. */ private static int extractConverter( char lastChar, final String pattern, int i, final StringBuffer convBuf, final StringBuffer currentLiteral) { convBuf.setLength(0); // When this method is called, lastChar points to the first character of the // conversion word. For example: // For "%hello" lastChar = 'h' // For "%-5hello" lastChar = 'h' //System.out.println("lastchar is "+lastChar); if (!Character.isUnicodeIdentifierStart(lastChar)) { return i; } convBuf.append(lastChar); while ( (i < pattern.length()) && Character.isUnicodeIdentifierPart(pattern.charAt(i))) { convBuf.append(pattern.charAt(i)); currentLiteral.append(pattern.charAt(i)); //System.out.println("conv buffer is now ["+convBuf+"]."); i++; } return i; } /** * Extract options. * @param pattern conversion pattern. * @param i start of options. * @param options array to receive extracted options * @return position in pattern after options. */ private static int extractOptions(String pattern, int i, List options) { while ((i < pattern.length()) && (pattern.charAt(i) == '{')) { int end = pattern.indexOf('}', i); if (end == -1) { break; } String r = pattern.substring(i + 1, end); options.add(r); i = end + 1; } return i; } /** * Parse a format specifier. * @param pattern pattern to parse. * @param patternConverters list to receive pattern converters. * @param formattingInfos list to receive field specifiers corresponding to pattern converters. * @param converterRegistry map of user-supported pattern converters keyed by format specifier, may be null. * @param rules map of stock pattern converters keyed by format specifier. */ public static void parse( final String pattern, final List patternConverters, final List formattingInfos, final Map converterRegistry, final Map rules) { if (pattern == null) { throw new NullPointerException("pattern"); } StringBuffer currentLiteral = new StringBuffer(32); int patternLength = pattern.length(); int state = LITERAL_STATE; char c; int i = 0; ExtrasFormattingInfo formattingInfo = ExtrasFormattingInfo.getDefault(); while (i < patternLength) { c = pattern.charAt(i++); switch (state) { case LITERAL_STATE: // In literal state, the last char is always a literal. if (i == patternLength) { currentLiteral.append(c); continue; } if (c == ESCAPE_CHAR) { // peek at the next char. switch (pattern.charAt(i)) { case ESCAPE_CHAR: currentLiteral.append(c); i++; // move pointer break; default: if (currentLiteral.length() != 0) { patternConverters.add( new LiteralPatternConverter(currentLiteral.toString())); formattingInfos.add(ExtrasFormattingInfo.getDefault()); } currentLiteral.setLength(0); currentLiteral.append(c); // append % state = CONVERTER_STATE; formattingInfo = ExtrasFormattingInfo.getDefault(); } } else { currentLiteral.append(c); } break; case CONVERTER_STATE: currentLiteral.append(c); switch (c) { case '-': formattingInfo = new ExtrasFormattingInfo( true, formattingInfo.isRightTruncated(), formattingInfo.getMinLength(), formattingInfo.getMaxLength()); break; case '!': formattingInfo = new ExtrasFormattingInfo( formattingInfo.isLeftAligned(), true, formattingInfo.getMinLength(), formattingInfo.getMaxLength()); break; case '.': state = DOT_STATE; break; default: if ((c >= '0') && (c <= '9')) { formattingInfo = new ExtrasFormattingInfo( formattingInfo.isLeftAligned(), formattingInfo.isRightTruncated(), c - '0', formattingInfo.getMaxLength()); state = MIN_STATE; } else { i = finalizeConverter( c, pattern, i, currentLiteral, formattingInfo, converterRegistry, rules, patternConverters, formattingInfos); // Next pattern is assumed to be a literal. state = LITERAL_STATE; formattingInfo = ExtrasFormattingInfo.getDefault(); currentLiteral.setLength(0); } } // switch break; case MIN_STATE: currentLiteral.append(c); if ((c >= '0') && (c <= '9')) { formattingInfo = new ExtrasFormattingInfo( formattingInfo.isLeftAligned(), formattingInfo.isRightTruncated(), (formattingInfo.getMinLength() * 10) + (c - '0'), formattingInfo.getMaxLength()); } else if (c == '.') { state = DOT_STATE; } else { i = finalizeConverter( c, pattern, i, currentLiteral, formattingInfo, converterRegistry, rules, patternConverters, formattingInfos); state = LITERAL_STATE; formattingInfo = ExtrasFormattingInfo.getDefault(); currentLiteral.setLength(0); } break; case DOT_STATE: currentLiteral.append(c); if ((c >= '0') && (c <= '9')) { formattingInfo = new ExtrasFormattingInfo( formattingInfo.isLeftAligned(), formattingInfo.isRightTruncated(), formattingInfo.getMinLength(), c - '0'); state = MAX_STATE; } else { LogLog.error( "Error occured in position " + i + ".\n Was expecting digit, instead got char \"" + c + "\"."); state = LITERAL_STATE; } break; case MAX_STATE: currentLiteral.append(c); if ((c >= '0') && (c <= '9')) { formattingInfo = new ExtrasFormattingInfo( formattingInfo.isLeftAligned(), formattingInfo.isRightTruncated(), formattingInfo.getMinLength(), (formattingInfo.getMaxLength() * 10) + (c - '0')); } else { i = finalizeConverter( c, pattern, i, currentLiteral, formattingInfo, converterRegistry, rules, patternConverters, formattingInfos); state = LITERAL_STATE; formattingInfo = ExtrasFormattingInfo.getDefault(); currentLiteral.setLength(0); } break; } // switch } // while if (currentLiteral.length() != 0) { patternConverters.add( new LiteralPatternConverter(currentLiteral.toString())); formattingInfos.add(ExtrasFormattingInfo.getDefault()); } } /** * Creates a new PatternConverter. * * * @param converterId converterId. * @param currentLiteral literal to be used if converter is unrecognized or following converter * if converterId contains extra characters. * @param converterRegistry map of user-supported pattern converters keyed by format specifier, may be null. * @param rules map of stock pattern converters keyed by format specifier. * @param options converter options. * @return converter or null. */ private static PatternConverter createConverter( final String converterId, final StringBuffer currentLiteral, final Map converterRegistry, final Map rules, final List options) { String converterName = converterId; Object converterObj = null; for (int i = converterId.length(); (i > 0) && (converterObj == null); i--) { converterName = converterName.substring(0, i); if (converterRegistry != null) { converterObj = converterRegistry.get(converterName); } if ((converterObj == null) && (rules != null)) { converterObj = rules.get(converterName); } } if (converterObj == null) { LogLog.error("Unrecognized format specifier [" + converterId + "]"); return null; } Class converterClass; if (converterObj instanceof Class) { converterClass = (Class) converterObj; } else { if (converterObj instanceof String) { try { converterClass = Loader.loadClass((String) converterObj); } catch (ClassNotFoundException ex) { LogLog.warn( "Class for conversion pattern %" + converterName + " not found", ex); return null; } } else { LogLog.warn( "Bad map entry for conversion pattern %" + converterName + "."); return null; } } try { Method factory = converterClass.getMethod( "newInstance", new Class[] { Class.forName("[Ljava.lang.String;") }); String[] optionsArray = new String[options.size()]; optionsArray = (String[]) options.toArray(optionsArray); Object newObj = factory.invoke(null, new Object[] { optionsArray }); if (newObj instanceof PatternConverter) { currentLiteral.delete( 0, currentLiteral.length() - (converterId.length() - converterName.length())); return (PatternConverter) newObj; } else { LogLog.warn( "Class " + converterClass.getName() + " does not extend PatternConverter."); } } catch (Exception ex) { LogLog.error("Error creating converter for " + converterId, ex); try { // // try default constructor PatternConverter pc = (PatternConverter) converterClass.newInstance(); currentLiteral.delete( 0, currentLiteral.length() - (converterId.length() - converterName.length())); return pc; } catch (Exception ex2) { LogLog.error("Error creating converter for " + converterId, ex2); } } return null; } /** * Processes a format specifier sequence. * * @param c initial character of format specifier. * @param pattern conversion pattern * @param i current position in conversion pattern. * @param currentLiteral current literal. * @param formattingInfo current field specifier. * @param converterRegistry map of user-provided pattern converters keyed by format specifier, may be null. * @param rules map of stock pattern converters keyed by format specifier. * @param patternConverters list to receive parsed pattern converter. * @param formattingInfos list to receive corresponding field specifier. * @return position after format specifier sequence. */ private static int finalizeConverter( char c, String pattern, int i, final StringBuffer currentLiteral, final ExtrasFormattingInfo formattingInfo, final Map converterRegistry, final Map rules, final List patternConverters, final List formattingInfos) { StringBuffer convBuf = new StringBuffer(); i = extractConverter(c, pattern, i, convBuf, currentLiteral); String converterId = convBuf.toString(); List options = new ArrayList(); i = extractOptions(pattern, i, options); PatternConverter pc = createConverter( converterId, currentLiteral, converterRegistry, rules, options); if (pc == null) { StringBuffer msg; if (converterId.length() == 0) { msg = new StringBuffer("Empty conversion specifier starting at position "); } else { msg = new StringBuffer("Unrecognized conversion specifier ["); msg.append(converterId); msg.append("] starting at position "); } msg.append(Integer.toString(i)); msg.append(" in conversion pattern."); LogLog.error(msg.toString()); patternConverters.add( new LiteralPatternConverter(currentLiteral.toString())); formattingInfos.add(ExtrasFormattingInfo.getDefault()); } else { patternConverters.add(pc); formattingInfos.add(formattingInfo); if (currentLiteral.length() > 0) { patternConverters.add( new LiteralPatternConverter(currentLiteral.toString())); formattingInfos.add(ExtrasFormattingInfo.getDefault()); } } currentLiteral.setLength(0); return i; } /** * The class wraps another Map but throws exceptions on any attempt to modify the map. */ private static class ReadOnlyMap implements Map { /** * Wrapped map. */ private final Map map; /** * Constructor * @param src source map. */ public ReadOnlyMap(Map src) { map = src; } /** * {@inheritDoc} */ public void clear() { throw new UnsupportedOperationException(); } /** * {@inheritDoc} */ public boolean containsKey(Object key) { return map.containsKey(key); } /** * {@inheritDoc} */ public boolean containsValue(Object value) { return map.containsValue(value); } /** * {@inheritDoc} */ public Set entrySet() { return map.entrySet(); } /** * {@inheritDoc} */ public Object get(Object key) { return map.get(key); } /** * {@inheritDoc} */ public boolean isEmpty() { return map.isEmpty(); } /** * {@inheritDoc} */ public Set keySet() { return map.keySet(); } /** * {@inheritDoc} */ public Object put(Object key, Object value) { throw new UnsupportedOperationException(); } /** * {@inheritDoc} */ public void putAll(Map t) { throw new UnsupportedOperationException(); } /** * {@inheritDoc} */ public Object remove(Object key) { throw new UnsupportedOperationException(); } /** * {@inheritDoc} */ public int size() { return map.size(); } /** * {@inheritDoc} */ public Collection values() { return map.values(); } } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/pattern/package.html000066400000000000000000000017151252742764200272250ustar00rootroot00000000000000

Provides classes implementing format specifiers in conversion patterns.


apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/000077500000000000000000000000001252742764200252525ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/db/000077500000000000000000000000001252742764200256375ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/db/ConnectionSource.java000066400000000000000000000045731252742764200317730ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.db; import org.apache.log4j.component.spi.Component; import org.apache.log4j.spi.OptionHandler; import java.sql.Connection; import java.sql.SQLException; /** * The ConnectionSource interface provides a pluggable means of * transparently obtaining JDBC {@link java.sql.Connection}s for log4j classes * that require the use of a {@link java.sql.Connection}. * * @author Ray DeCampo */ public interface ConnectionSource extends Component, OptionHandler { final int UNKNOWN_DIALECT = 0; final int POSTGRES_DIALECT = 1; final int MYSQL_DIALECT = 2; final int ORACLE_DIALECT = 3; final int MSSQL_DIALECT = 4; final int HSQL_DIALECT = 5; /** * Obtain a {@link java.sql.Connection} for use. The client is * responsible for closing the {@link java.sql.Connection} when it is no * longer required. * * @throws SQLException if a {@link java.sql.Connection} could not be * obtained */ Connection getConnection() throws SQLException; /** * Get the SQL dialect that should be used for this connection. Note that the * dialect is not needed if the JDBC driver supports the getGeneratedKeys * method. */ int getSQLDialectCode(); /** * If the connection supports the JDBC 3.0 getGeneratedKeys method, then * we do not need any specific dialect support. */ boolean supportsGetGeneratedKeys(); /** * If the connection does not support batch updates, we will avoid using them. */ public boolean supportsBatchUpdates(); } ConnectionSourceSkeleton.java000066400000000000000000000111141252742764200334060ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/db/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.db; import org.apache.log4j.component.spi.ComponentBase; import org.apache.log4j.receivers.db.dialect.Util; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.SQLException; /** * @author Ceki Gülcü */ public abstract class ConnectionSourceSkeleton extends ComponentBase implements ConnectionSource { private Boolean overriddenSupportsGetGeneratedKeys = null; private String user = null; private String password = null; // initially we have an unkonw dialect private int dialectCode = UNKNOWN_DIALECT; private boolean supportsGetGeneratedKeys = false; private boolean supportsBatchUpdates = false; /** * Learn relevant information about this connection source. * */ public void discoverConnnectionProperties() { Connection connection = null; try { connection = getConnection(); if (connection == null) { getLogger().warn("Could not get a conneciton"); return; } DatabaseMetaData meta = connection.getMetaData(); Util util = new Util(); util.setLoggerRepository(repository); if (overriddenSupportsGetGeneratedKeys != null) { supportsGetGeneratedKeys = overriddenSupportsGetGeneratedKeys .booleanValue(); } else { supportsGetGeneratedKeys = util.supportsGetGeneratedKeys(meta); } supportsBatchUpdates = util.supportsBatchUpdates(meta); dialectCode = Util.discoverSQLDialect(meta); } catch (SQLException se) { getLogger().warn("Could not discover the dialect to use.", se); } finally { DBHelper.closeConnection(connection); } } /** * Does this connection support the JDBC Connection.getGeneratedKeys method? */ public final boolean supportsGetGeneratedKeys() { return supportsGetGeneratedKeys; } public final int getSQLDialectCode() { return dialectCode; } /** * Get the password for this connection source. */ public final String getPassword() { return password; } /** * Sets the password. * @param password The password to set */ public final void setPassword(final String password) { this.password = password; } /** * Get the user for this connection source. */ public final String getUser() { return user; } /** * Sets the username. * @param username The username to set */ public final void setUser(final String username) { this.user = username; } /** * Returns the "overridden" value of "supportsGetGeneratedKeys" property of * the JDBC driver. In certain cases, getting (e.g. Oracle 10g) generated keys * does not work because it returns the ROWID, not the value of the sequence. * * @return A non null string, with "true" or "false" value, if overridden, * null if not overridden. */ public String getOverriddenSupportsGetGeneratedKeys() { return overriddenSupportsGetGeneratedKeys != null ? overriddenSupportsGetGeneratedKeys .toString() : null; } /** * Sets the "overridden" value of "supportsGetGeneratedKeys" property of the * JDBC driver. In certain cases, getting (e.g. Oracle 10g) generated keys * does not work because it returns the ROWID, not the value of the sequence. * * @param overriddenSupportsGetGeneratedKeys * A non null string, with "true" or "false" value, if overridden, * null if not overridden. */ public void setOverriddenSupportsGetGeneratedKeys( String overriddenSupportsGetGeneratedKeys) { this.overriddenSupportsGetGeneratedKeys = Boolean .valueOf(overriddenSupportsGetGeneratedKeys); } /** * Does this connection support batch updates? */ public final boolean supportsBatchUpdates() { return supportsBatchUpdates; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/db/CustomSQLDBReceiver.java000066400000000000000000000415461252742764200322410ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.db; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.component.plugins.Pauseable; import org.apache.log4j.component.plugins.Receiver; import org.apache.log4j.component.scheduler.Job; import org.apache.log4j.component.scheduler.Scheduler; import org.apache.log4j.component.spi.LoggerRepositoryEx; import org.apache.log4j.spi.LocationInfo; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.ThrowableInformation; import org.apache.log4j.xml.DOMConfigurator; import org.apache.log4j.xml.UnrecognizedElementHandler; import org.w3c.dom.Element; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Hashtable; import java.util.Properties; import java.util.StringTokenizer; /** * Converts log data stored in a database into LoggingEvents. *

* NOTE: This receiver cannot yet be created through Chainsaw's receiver panel. * It must be created through an XML configuration file. *

* This receiver supports database configuration via ConnectionSource, in the * org.apache.log4j.db package: DriverManagerConnectionSource, * DataSourceConnectionSource, JNDIConnectionSource *

* This database receiver differs from DBReceiver in that this receiver relies * on custom SQL to retrieve logging event data, where DBReceiver requires the * use of a log4j-defined schema. *

* A 'refreshMillis' int parameter controls SQL execution. If 'refreshMillis' is * zero (the default), the receiver will run only one time. If it is set to any * other numeric value, the SQL will be executed on a recurring basis every * 'refreshMillis' milliseconds. *

* The receiver closes the connection and acquires a new connection on each * execution of the SQL (use pooled connections if possible). *

* If the SQL will be executing on a recurring basis, specify the IDField param - * the column name holding the unique identifier (int) representing the logging * event. *

* As events are retrieved, the column represented by IDField is examined and * the largest value is held and used by the next execution of the SQL statement * to avoid retrieving previously processed events. *

* As an example, the IDField references a 'COUNTER' (int, auto-increment, * unique) column. The first execution of the SQL statement returns 500 rows, * with a final value in the COUNTER field of 500. *

* The SQL statement is manipulated prior to the next execution, adding ' WHERE * COUNTER > 500' to the statement to avoid retrieval of previously processed * events. *

* The select statement must provide ALL fields which define a LoggingEvent. *

* The SQL statement MUST include the columns: LOGGER, TIMESTAMP, LEVEL, THREAD, * MESSAGE, NDC, MDC, CLASS, METHOD, FILE, LINE, PROPERTIES, THROWABLE *

* Use ' AS ' in the SQL statement to alias the SQL's column names to match your * database schema. (see example below). *

* Include all fields in the SQL statement, even if you don't have data for the * field (specify an empty string as the value for columns which you don't have * data). *

* The TIMESTAMP column must be a datetime. *

* Both a PROPERTIES column and an MDC column are supported. These fields * represent Maps on the logging event, but require the use of string * concatenation database functions to hold the (possibly multiple) name/value * pairs in the column. *

* For example, to include both 'userid' and 'lastname' properties in the * logging event (from either the PROPERTIES or MDC columns), the name/value * pairs must be concatenated together by your database. *

* The resulting PROPERTIES or MDC column must have data in this format: {{name, * value, name2, value2}} *

* The resulting PROPERTIES column would contain this text: {{userid, someone, * lastname, mylastname}} *

* Here is an example of concatenating a PROPERTIES or MDC column using MySQL's * concat function, where the 'application' and 'hostname' parameters were fixed * text, but the 'log4jid' key's value is the value of the COUNTER column: *

* concat("{{application,databaselogs,hostname,mymachine,log4jid,", COUNTER, * "}}") as PROPERTIES *

* log4jid is a special property that is used by Chainsaw to represent an 'ID' * field. Specify this property to ensure you can map events in Chainsaw to * events in the database if you need to go back and view events at a later time * or save the events to XML for later analysis. *

* Here is a complete MySQL SQL statement which can be used to provide events to * Chainsaw (note how in the example below, there is no column in logtable representing the throwable, so an * empty string is passed in and an ALIAS is still defined): *

* select myloggercolumn as LOGGER, mytimestampcolumn as TIMESTAMP, mylevelcolumn as LEVEL, mythreadcolumn as * THREAD, mymessagecolumn as MESSAGE, myndccolumn as NDC, mymdccolumn as MDC, myclasscolumn as CLASS, mymethodcolumn as * METHOD, myfilecolumn as FILE, mylinecolumn as LINE, * concat("{{application,databaselogs,hostname,mymachine, log4jid,", * COUNTER,"}}") as PROPERTIES, "" as THROWABLE from logtable *

* @author Scott Deboy *

*/ public class CustomSQLDBReceiver extends Receiver implements Pauseable, UnrecognizedElementHandler { protected volatile Connection connection = null; protected String sqlStatement = ""; /** * By default we refresh data every 1000 milliseconds. * * @see #setRefreshMillis */ static int DEFAULT_REFRESH_MILLIS = 1000; int refreshMillis = DEFAULT_REFRESH_MILLIS; protected String idField = null; int lastID = -1; private static final String WHERE_CLAUSE = " WHERE "; private static final String AND_CLAUSE = " AND "; private boolean whereExists = false; private boolean paused = false; private ConnectionSource connectionSource; public static final String LOG4J_ID_KEY = "log4jid"; private CustomReceiverJob customReceiverJob; public void activateOptions() { if(connectionSource == null) { throw new IllegalStateException( "CustomSQLDBReceiver cannot function without a connection source"); } whereExists = (sqlStatement.toUpperCase().indexOf(WHERE_CLAUSE) > -1); customReceiverJob = new CustomReceiverJob(); if(this.repository == null) { throw new IllegalStateException( "CustomSQLDBReceiver cannot function without a reference to its owning repository"); } if (repository instanceof LoggerRepositoryEx) { Scheduler scheduler = ((LoggerRepositoryEx) repository).getScheduler(); scheduler.schedule( customReceiverJob, System.currentTimeMillis() + 500, refreshMillis); } } void closeConnection() { if (connection != null) { try { // LogLog.warn("closing the connection. ", new Exception("x")); connection.close(); } catch (SQLException sqle) { // nothing we can do here } } } public void setRefreshMillis(int refreshMillis) { this.refreshMillis = refreshMillis; } public int getRefreshMillis() { return refreshMillis; } /** * @return Returns the connectionSource. */ public ConnectionSource getConnectionSource() { return connectionSource; } /** * @param connectionSource * The connectionSource to set. */ public void setConnectionSource(ConnectionSource connectionSource) { this.connectionSource = connectionSource; } public void close() { try { if ((connection != null) && !connection.isClosed()) { connection.close(); } } catch (SQLException e) { e.printStackTrace(); } finally { connection = null; } } public void finalize() throws Throwable { super.finalize(); close(); } /* * (non-Javadoc) * * @see org.apache.log4j.plugins.Plugin#shutdown() */ public void shutdown() { getLogger().info("removing receiverJob from the Scheduler."); if(this.repository instanceof LoggerRepositoryEx) { Scheduler scheduler = ((LoggerRepositoryEx) repository).getScheduler(); scheduler.delete(customReceiverJob); } lastID = -1; } public void setSql(String s) { sqlStatement = s; } public String getSql() { return sqlStatement; } public void setIDField(String id) { idField = id; } public String getIDField() { return idField; } public synchronized void setPaused(boolean p) { paused = p; } public synchronized boolean isPaused() { return paused; } class CustomReceiverJob implements Job { public void execute() { int oldLastID = lastID; try { connection = connectionSource.getConnection(); Statement statement = connection.createStatement(); Logger eventLogger = null; long timeStamp = 0L; String level = null; String threadName = null; Object message = null; String ndc = null; Hashtable mdc = null; String[] throwable = null; String className = null; String methodName = null; String fileName = null; String lineNumber = null; Hashtable properties = null; String currentSQLStatement = sqlStatement; if (whereExists) { currentSQLStatement = sqlStatement + AND_CLAUSE + idField + " > " + lastID; } else { currentSQLStatement = sqlStatement + WHERE_CLAUSE + idField + " > " + lastID; } ResultSet rs = statement.executeQuery(currentSQLStatement); int i = 0; while (rs.next()) { // add a small break every 1000 received events if (++i == 1000) { synchronized (this) { try { // add a delay wait(300); } catch (InterruptedException ie) { } i = 0; } } eventLogger = Logger.getLogger(rs.getString("LOGGER")); timeStamp = rs.getTimestamp("TIMESTAMP").getTime(); level = rs.getString("LEVEL"); threadName = rs.getString("THREAD"); message = rs.getString("MESSAGE"); ndc = rs.getString("NDC"); String mdcString = rs.getString("MDC"); mdc = new Hashtable(); if (mdcString != null) { // support MDC being wrapped in {{name, value}} // or // just name, value if ((mdcString.indexOf("{{") > -1) && (mdcString.indexOf("}}") > -1)) { mdcString = mdcString .substring(mdcString.indexOf("{{") + 2, mdcString.indexOf("}}")); } StringTokenizer tok = new StringTokenizer(mdcString, ","); while (tok.countTokens() > 1) { mdc.put(tok.nextToken(), tok.nextToken()); } } throwable = new String[] { rs.getString("THROWABLE") }; className = rs.getString("CLASS"); methodName = rs.getString("METHOD"); fileName = rs.getString("FILE"); lineNumber = rs.getString("LINE"); // if properties are provided in the // SQL they can be used here (for example, to route // events to a unique tab in // Chainsaw if the machinename and/or appname // property // are set) String propertiesString = rs.getString("PROPERTIES"); properties = new Hashtable(); if (propertiesString != null) { // support properties being wrapped in {{name, // value}} or just name, value if ((propertiesString.indexOf("{{") > -1) && (propertiesString.indexOf("}}") > -1)) { propertiesString = propertiesString.substring( propertiesString.indexOf("{{") + 2, propertiesString.indexOf("}}")); } StringTokenizer tok2 = new StringTokenizer( propertiesString, ","); while (tok2.countTokens() > 1) { String tokenName = tok2.nextToken(); String value = tok2.nextToken(); if (tokenName.equals(LOG4J_ID_KEY)) { try { int thisInt = Integer.parseInt(value); value = String.valueOf(thisInt); if (thisInt > lastID) { lastID = thisInt; } } catch (Exception e) { } } properties.put(tokenName, value); } } Level levelImpl = Level.toLevel(level); LocationInfo locationInfo = new LocationInfo(fileName, className, methodName, lineNumber); ThrowableInformation throwableInfo = new ThrowableInformation( throwable); properties.putAll(mdc); LoggingEvent event = new LoggingEvent(eventLogger.getName(), eventLogger, timeStamp, levelImpl, message, threadName, throwableInfo, ndc, locationInfo, properties); doPost(event); } //log when rows are retrieved if (lastID != oldLastID) { getLogger().debug("lastID: " + lastID); oldLastID = lastID; } statement.close(); statement = null; } catch (SQLException sqle) { getLogger() .error("*************Problem receiving events", sqle); } finally { closeConnection(); } // if paused, loop prior to executing sql query synchronized (this) { while (isPaused()) { try { wait(1000); } catch (InterruptedException ie) { } } } } } /** * {@inheritDoc} */ public boolean parseUnrecognizedElement(Element element, Properties props) throws Exception { if ("connectionSource".equals(element.getNodeName())) { Object instance = DOMConfigurator.parseElement(element, props, ConnectionSource.class); if (instance instanceof ConnectionSource) { ConnectionSource source = (ConnectionSource) instance; source.activateOptions(); setConnectionSource(source); } return true; } return false; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/db/DBHelper.java000066400000000000000000000037121252742764200301320ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.db; import org.apache.log4j.spi.LoggingEvent; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.util.Set; /** * @author Ceki Gülcü * */ public class DBHelper { public final static short PROPERTIES_EXIST = 0x01; public final static short EXCEPTION_EXISTS = 0x02; public static short computeReferenceMask(LoggingEvent event) { short mask = 0; Set propertiesKeys = event.getPropertyKeySet(); if(propertiesKeys.size() > 0) { mask = PROPERTIES_EXIST; } String[] strRep = event.getThrowableStrRep(); if(strRep != null) { mask |= EXCEPTION_EXISTS; } return mask; } static public void closeConnection(Connection connection) { if(connection != null) { try { connection.close(); } catch(SQLException sqle) { // static utility classes should not log without an explicit repository // reference } } } public static void closeStatement(Statement statement) { if(statement != null) { try { statement.close(); } catch(SQLException sqle) { } } } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/db/DBReceiver.java000066400000000000000000000100621252742764200304530ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.db; import org.apache.log4j.component.plugins.Pauseable; import org.apache.log4j.component.plugins.Receiver; import org.apache.log4j.component.scheduler.Scheduler; import org.apache.log4j.component.spi.LoggerRepositoryEx; import org.apache.log4j.xml.DOMConfigurator; import org.apache.log4j.xml.UnrecognizedElementHandler; import org.w3c.dom.Element; import java.util.Properties; /** * * @author Scott Deboy * @author Ceki Gülcü * */ public class DBReceiver extends Receiver implements Pauseable, UnrecognizedElementHandler { /** * By default we refresh data every 1000 milliseconds. * @see #setRefreshMillis */ static int DEFAULT_REFRESH_MILLIS = 1000; ConnectionSource connectionSource; int refreshMillis = DEFAULT_REFRESH_MILLIS; DBReceiverJob receiverJob; boolean paused = false; public void activateOptions() { if(connectionSource == null) { throw new IllegalStateException( "DBAppender cannot function without a connection source"); } receiverJob = new DBReceiverJob(this); receiverJob.setLoggerRepository(repository); if(this.repository == null) { throw new IllegalStateException( "DBAppender cannot function without a reference to its owning repository"); } if (repository instanceof LoggerRepositoryEx) { Scheduler scheduler = ((LoggerRepositoryEx) repository).getScheduler(); scheduler.schedule( receiverJob, System.currentTimeMillis() + 500, refreshMillis); } } public void setRefreshMillis(int refreshMillis) { this.refreshMillis = refreshMillis; } public int getRefreshMillis() { return refreshMillis; } /** * @return Returns the connectionSource. */ public ConnectionSource getConnectionSource() { return connectionSource; } /** * @param connectionSource The connectionSource to set. */ public void setConnectionSource(ConnectionSource connectionSource) { this.connectionSource = connectionSource; } /* (non-Javadoc) * @see org.apache.log4j.plugins.Plugin#shutdown() */ public void shutdown() { getLogger().info("removing receiverJob from the Scheduler."); if(this.repository instanceof LoggerRepositoryEx) { Scheduler scheduler = ((LoggerRepositoryEx) repository).getScheduler(); scheduler.delete(receiverJob); } } /* (non-Javadoc) * @see org.apache.log4j.plugins.Pauseable#setPaused(boolean) */ public void setPaused(boolean paused) { this.paused = paused; } /* (non-Javadoc) * @see org.apache.log4j.plugins.Pauseable#isPaused() */ public boolean isPaused() { return paused; } /** * {@inheritDoc} */ public boolean parseUnrecognizedElement(Element element, Properties props) throws Exception { if ("connectionSource".equals(element.getNodeName())) { Object instance = DOMConfigurator.parseElement(element, props, ConnectionSource.class); if (instance instanceof ConnectionSource) { ConnectionSource source = (ConnectionSource) instance; source.activateOptions(); setConnectionSource(source); } return true; } return false; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/db/DBReceiverJob.java000066400000000000000000000147071252742764200311200ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.db; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.component.scheduler.Job; import org.apache.log4j.component.spi.ComponentBase; import org.apache.log4j.spi.LocationInfo; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.ThrowableInformation; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Hashtable; import java.util.Vector; /** * Actual retrieval of data is made by the instance of DBReceiverJob associated * with DBReceiver. * * @author Ceki Gülcü */ class DBReceiverJob extends ComponentBase implements Job { String sqlException = "SELECT trace_line FROM logging_event_exception where event_id=? ORDER by i ASC"; String sqlProperties = "SELECT mapped_key, mapped_value FROM logging_event_property WHERE event_id=?"; String sqlSelect = "SELECT " + "sequence_number, timestamp, rendered_message, logger_name, " + "level_string, ndc, thread_name, reference_flag, " + "caller_filename, caller_class, caller_method, caller_line, " + "event_id " + "FROM logging_event " + "WHERE event_id > ? ORDER BY event_id ASC"; long lastId = Short.MIN_VALUE; DBReceiver parentDBReceiver; DBReceiverJob(DBReceiver parent) { parentDBReceiver = parent; } public void execute() { Connection connection = null; try { connection = parentDBReceiver.connectionSource.getConnection(); PreparedStatement statement = connection.prepareStatement(sqlSelect); statement.setLong(1, lastId); ResultSet rs = statement.executeQuery(); //rs.beforeFirst(); while (rs.next()) { Logger logger = null; long timeStamp = 0L; String level = null; String threadName = null; Object message = null; String ndc = null; String className = null; String methodName = null; String fileName = null; String lineNumber = null; Hashtable properties = new Hashtable(); //event.setSequenceNumber(rs.getLong(1)); timeStamp = rs.getLong(2); message = rs.getString(3); logger = Logger.getLogger(rs.getString(4)); level = rs.getString(5); Level levelImpl = Level.toLevel(level.trim()); ndc = rs.getString(6); threadName = rs.getString(7); short mask = rs.getShort(8); fileName = rs.getString(9); className = rs.getString(10); methodName = rs.getString(11); lineNumber = rs.getString(12).trim(); LocationInfo locationInfo = null; if (fileName.equals(LocationInfo.NA)) { locationInfo = LocationInfo.NA_LOCATION_INFO; } else { locationInfo = new LocationInfo(fileName, className, methodName, lineNumber); } long id = rs.getLong(13); //LogLog.info("Received event with id=" + id); lastId = id; ThrowableInformation throwableInfo = null; if ((mask & DBHelper.EXCEPTION_EXISTS) != 0) { throwableInfo = getException(connection, id); } LoggingEvent event = new LoggingEvent(logger.getName(), logger, timeStamp, levelImpl, message, threadName, throwableInfo, ndc, locationInfo, properties); // Scott asked for this info to be event.setProperty("log4jid", Long.toString(id)); if ((mask & DBHelper.PROPERTIES_EXIST) != 0) { getProperties(connection, id, event); } if (!parentDBReceiver.isPaused()) { parentDBReceiver.doPost(event); } } // while statement.close(); statement = null; } catch (SQLException sqle) { getLogger().error("Problem receiving events", sqle); } finally { closeConnection(connection); } } void closeConnection(Connection connection) { if (connection != null) { try { //LogLog.warn("closing the connection. ", new Exception("x")); connection.close(); } catch (SQLException sqle) { // nothing we can do here } } } /** * Retrieve the event properties from the logging_event_property table. * * @param connection * @param id * @param event * @throws SQLException */ void getProperties(Connection connection, long id, LoggingEvent event) throws SQLException { PreparedStatement statement = connection.prepareStatement(sqlProperties); try { statement.setLong(1, id); ResultSet rs = statement.executeQuery(); while (rs.next()) { String key = rs.getString(1); String value = rs.getString(2); event.setProperty(key, value); } } finally { statement.close(); } } /** * Retrieve the exception string representation from the * logging_event_exception table. * * @param connection * @param id * @throws SQLException */ ThrowableInformation getException(Connection connection, long id) throws SQLException { PreparedStatement statement = null; try { statement = connection.prepareStatement(sqlException); statement.setLong(1, id); ResultSet rs = statement.executeQuery(); Vector v = new Vector(); while (rs.next()) { //int i = rs.getShort(1); v.add(rs.getString(1)); } int len = v.size(); String[] strRep = new String[len]; for (int i = 0; i < len; i++) { strRep[i] = (String) v.get(i); } // we've filled strRep, we now attach it to the event return new ThrowableInformation(strRep); } finally { if (statement != null) { statement.close(); } } } }DataSourceConnectionSource.java000066400000000000000000000064261252742764200336660ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/db/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.db; import org.apache.log4j.xml.DOMConfigurator; import org.apache.log4j.xml.UnrecognizedElementHandler; import org.w3c.dom.Element; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; /** * The DataSourceConnectionSource is an implementation of {@link ConnectionSource} * that obtains the Connection in the recommended JDBC manner based on * a {@link javax.sql.DataSource DataSource}. *

* * @author Ray DeCampo * @author Ceki Gülcü */ public class DataSourceConnectionSource extends ConnectionSourceSkeleton implements UnrecognizedElementHandler { private DataSource dataSource; public void activateOptions() { //LogLog.debug("**********DataSourceConnectionSource.activateOptions called"); if (dataSource == null) { getLogger().warn("WARNING: No data source specified"); } else { Connection connection = null; try { connection = getConnection(); } catch(SQLException se) { getLogger().warn("Could not get a connection to discover the dialect to use.", se); } if(connection != null) { discoverConnnectionProperties(); } if(!supportsGetGeneratedKeys() && getSQLDialectCode() == ConnectionSource.UNKNOWN_DIALECT) { getLogger().warn("Connection does not support GetGeneratedKey method and could not discover the dialect."); } } } /** * @see org.apache.log4j.receivers.db.ConnectionSource#getConnection() */ public Connection getConnection() throws SQLException { if (dataSource == null) { getLogger().error("WARNING: No data source specified"); return null; } if (getUser() == null) { return dataSource.getConnection(); } else { return dataSource.getConnection(getUser(), getPassword()); } } public DataSource getDataSource() { return dataSource; } public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } /** * {@inheritDoc} */ public boolean parseUnrecognizedElement(Element element, Properties props) throws Exception { if ("dataSource".equals(element.getNodeName())) { Object instance = DOMConfigurator.parseElement(element, props, DataSource.class); if (instance instanceof DataSource) { setDataSource((DataSource) instance); } return true; } return false; } } DriverManagerConnectionSource.java000066400000000000000000000110331252742764200343500ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/db/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.db; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /** * The DriverManagerConnectionSource is an implementation of {@link ConnectionSource} * that obtains the Connection in the traditional JDBC manner based on the * connection URL. *

* Note that this class will establish a new Connection for each call to * {@link #getConnection()}. It is recommended that you either use a JDBC * driver that natively supported Connection pooling or that you create * your own implementation of {@link ConnectionSource} that taps into whatever * pooling mechanism you are already using. (If you have access to a JNDI * implementation that supports {@link javax.sql.DataSource}s, e.g. within * a J2EE application server, see {@link JNDIConnectionSource}). See * below for a configuration example that uses the * commons-dbcp * package from Apache. *

* Sample configuration:
*

 *     <connectionSource class="org.apache.log4j.jdbc.DriverManagerConnectionSource">
 *        <param name="driver" value="com.mysql.jdbc.Driver" />
 *        <param name="url" value="jdbc:mysql://localhost:3306/mydb" />
 *        <param name="username" value="myUser" />
 *        <param name="password" value="myPassword" />
 *     </connectionSource>
 *  
*

* If you do not have another connection pooling mechanism * built into your application, you can use the * commons-dbcp * package from Apache:
*

 *     <connectionSource class="org.apache.log4j.jdbc.DriverManagerConnectionSource">
 *        <param name="driver" value="org.apache.commons.dbcp.PoolingDriver" />
 *        <param name="url" value="jdbc:apache:commons:dbcp:/myPoolingDriver" />
 *     </connectionSource>
 *  
* Then the configuration information for the commons-dbcp package goes into * the file myPoolingDriver.jocl and is placed in the classpath. See the * commons-dbcp * documentation for details. * * @author Ray DeCampo */ public class DriverManagerConnectionSource extends ConnectionSourceSkeleton { private String driverClass = null; private String url = null; public void activateOptions() { try { if (driverClass != null) { Class.forName(driverClass); discoverConnnectionProperties(); } else { getLogger().error( "WARNING: No JDBC driver specified for log4j DriverManagerConnectionSource."); } } catch (final ClassNotFoundException cnfe) { getLogger().error("Could not load JDBC driver class: " + driverClass, cnfe); } } /** * @see org.apache.log4j.receivers.db.ConnectionSource#getConnection() */ public Connection getConnection() throws SQLException { if (getUser() == null) { return DriverManager.getConnection(url); } else { return DriverManager.getConnection(url, getUser(), getPassword()); } } /** * Returns the url. * @return String */ public String getUrl() { return url; } /** * Sets the url. * @param url The url to set */ public void setUrl(String url) { this.url = url; } /** * Returns the name of the driver class. * @return String */ public String getDriverClass() { return driverClass; } /** * Sets the driver class. * @param driverClass The driver class to set */ public void setDriverClass(String driverClass) { this.driverClass = driverClass; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/db/JNDIConnectionSource.java000066400000000000000000000114511252742764200324310ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.db; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; // PortableRemoteObject was introduced in JDK 1.3. We won't use it. // import javax.rmi.PortableRemoteObject; /** * The JNDIConnectionSource is an implementation of * {@link ConnectionSource} that obtains a {@link javax.sql.DataSource} from a * JNDI provider and uses it to obtain a {@link java.sql.Connection}. It is * primarily designed to be used inside of J2EE application servers or * application server clients, assuming the application server supports remote * access of {@link javax.sql.DataSource}s. In this way one can take * advantage of connection pooling and whatever other goodies the application * server provides. *

* Sample configuration:
*

 *    <connectionSource class="org.apache.log4j.jdbc.JNDIConnectionSource">
 *        <param name="jndiLocation" value="jdbc/MySQLDS" />
 *    </connectionSource>
 *  
*

* Sample configuration (with username and password):
*

 *    <connectionSource class="org.apache.log4j.jdbc.JNDIConnectionSource">
 *        <param name="jndiLocation" value="jdbc/MySQLDS" />
 *        <param name="username" value="myUser" />
 *        <param name="password" value="myPassword" />
 *    </connectionSource>
 *  
*

* Note that this class will obtain an {@link javax.naming.InitialContext} * using the no-argument constructor. This will usually work when executing * within a J2EE environment. When outside the J2EE environment, make sure * that you provide a jndi.properties file as described by your JNDI * provider's documentation. * * @author Ray DeCampo */ public class JNDIConnectionSource extends ConnectionSourceSkeleton { private String jndiLocation = null; private DataSource dataSource = null; /** * @see org.apache.log4j.spi.OptionHandler#activateOptions() */ public void activateOptions() { if (jndiLocation == null) { getLogger().error("No JNDI location specified for JNDIConnectionSource."); } discoverConnnectionProperties(); } /** * @see org.apache.log4j.receivers.db.ConnectionSource#getConnection() */ public Connection getConnection() throws SQLException { Connection conn = null; try { if(dataSource == null) { dataSource = lookupDataSource(); } if (getUser() == null) { conn = dataSource.getConnection(); } else { conn = dataSource.getConnection(getUser(), getPassword()); } } catch (final NamingException ne) { getLogger().error("Error while getting data source", ne); throw new SQLException("NamingException while looking up DataSource: " + ne.getMessage()); } catch (final ClassCastException cce) { getLogger().error("ClassCastException while looking up DataSource.", cce); throw new SQLException("ClassCastException while looking up DataSource: " + cce.getMessage()); } return conn; } /** * Returns the jndiLocation. * @return String */ public String getJndiLocation() { return jndiLocation; } /** * Sets the jndiLocation. * @param jndiLocation The jndiLocation to set */ public void setJndiLocation(String jndiLocation) { this.jndiLocation = jndiLocation; } private DataSource lookupDataSource() throws NamingException, SQLException { DataSource ds; Context ctx = new InitialContext(); Object obj = ctx.lookup(jndiLocation); // PortableRemoteObject was introduced in JDK 1.3. We won't use it. //ds = (DataSource)PortableRemoteObject.narrow(obj, DataSource.class); ds = (DataSource) obj; if (ds == null) { throw new SQLException("Failed to obtain data source from JNDI location " + jndiLocation); } else { return ds; } } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/db/dialect/000077500000000000000000000000001252742764200272445ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/db/dialect/HSQLDBDialect.java000066400000000000000000000021771252742764200323610ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.db.dialect; /** * The HSQLDB dialect. * * @author Ceki Gülcü */ public class HSQLDBDialect implements SQLDialect { public static final String SELECT_CURRVAL = "CALL IDENTITY()"; public String getSelectInsertId() { return SELECT_CURRVAL; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/db/dialect/MsSQLDialect.java000066400000000000000000000023621252742764200323370ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.db.dialect; /** * The MS SQL Server dialect is untested. * * Note that the dialect is not needed if your JDBC driver supports * the getGeneratedKeys method introduced in JDBC 3.0 specification. * * @author James Stauffer */ public class MsSQLDialect implements SQLDialect { public static final String SELECT_CURRVAL = "SELECT @@identity id"; public String getSelectInsertId() { return SELECT_CURRVAL; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/db/dialect/MySQLDialect.java000066400000000000000000000021141252742764200323400ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.db.dialect; /** * * * @author Ceki * */ public class MySQLDialect implements SQLDialect { public static final String SELECT_LAST_INSERT_ID = "SELECT LAST_INSERT_ID()"; public String getSelectInsertId() { return SELECT_LAST_INSERT_ID; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/db/dialect/OracleDialect.java000066400000000000000000000022751252742764200326100ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.db.dialect; /** * The Oracle dialect. Tested successfully on Oracle9i Release 9.2.0.3.0 by * James Stauffer. * * @author Ceki Gülcü */ public class OracleDialect implements SQLDialect { public static final String SELECT_CURRVAL = "SELECT logging_event_id_seq.currval from dual"; public String getSelectInsertId() { return SELECT_CURRVAL; } } PostgreSQLDialect.java000066400000000000000000000023211252742764200333170ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/db/dialect/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.db.dialect; /** * * @author ceki * * To change the template for this generated type comment go to * Window>Preferences>Java>Code Generation>Code and Comments */ public class PostgreSQLDialect implements SQLDialect { public static final String SELECT_CURRVAL = "SELECT currval('logging_event_id_seq')"; public String getSelectInsertId() { return SELECT_CURRVAL; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/db/dialect/SQLDialect.java000066400000000000000000000016731252742764200320430ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.db.dialect; /** * @author ceki * */ public interface SQLDialect { public String getSelectInsertId(); } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/db/dialect/SybaseDialect.java000066400000000000000000000020751252742764200326270ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.log4j.receivers.db.dialect; /** * The Sybase dialect. * */ public class SybaseDialect implements SQLDialect { public static final String SELECT_CURRVAL = "select @@identity"; public String getSelectInsertId() { return SELECT_CURRVAL; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/db/dialect/Util.java000066400000000000000000000075421252742764200310340ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.db.dialect; import org.apache.log4j.component.spi.ComponentBase; import org.apache.log4j.receivers.db.ConnectionSource; import java.sql.DatabaseMetaData; import java.sql.SQLException; /** * * @author Ceki Gulcu * */ public class Util extends ComponentBase { private static final String POSTGRES_PART = "postgresql"; private static final String MYSQL_PART = "mysql"; private static final String ORACLE_PART = "oracle"; //private static final String MSSQL_PART = "mssqlserver4"; private static final String MSSQL_PART = "microsoft"; private static final String HSQL_PART = "hsql"; public static int discoverSQLDialect(DatabaseMetaData meta) { int dialectCode = 0; try { String dbName = meta.getDatabaseProductName().toLowerCase(); if (dbName.indexOf(POSTGRES_PART) != -1) { return ConnectionSource.POSTGRES_DIALECT; } else if (dbName.indexOf(MYSQL_PART) != -1) { return ConnectionSource.MYSQL_DIALECT; } else if (dbName.indexOf(ORACLE_PART) != -1) { return ConnectionSource.ORACLE_DIALECT; } else if (dbName.indexOf(MSSQL_PART) != -1) { return ConnectionSource.MSSQL_DIALECT; } else if (dbName.indexOf(HSQL_PART) != -1) { return ConnectionSource.HSQL_DIALECT; } else { return ConnectionSource.UNKNOWN_DIALECT; } } catch (SQLException sqle) { // we can't do much here } return dialectCode; } public static SQLDialect getDialectFromCode(int dialectCode) { SQLDialect sqlDialect = null; switch (dialectCode) { case ConnectionSource.POSTGRES_DIALECT: sqlDialect = new PostgreSQLDialect(); break; case ConnectionSource.MYSQL_DIALECT: sqlDialect = new MySQLDialect(); break; case ConnectionSource.ORACLE_DIALECT: sqlDialect = new OracleDialect(); break; case ConnectionSource.MSSQL_DIALECT: sqlDialect = new MsSQLDialect(); break; case ConnectionSource.HSQL_DIALECT: sqlDialect = new HSQLDBDialect(); break; } return sqlDialect; } /** * This method handles cases where the * {@link DatabaseMetaData#supportsGetGeneratedKeys} method is missing in the * JDBC driver implementation. */ public boolean supportsGetGeneratedKeys(DatabaseMetaData meta) { try { // // invoking JDK 1.4 method by reflection // return ((Boolean) DatabaseMetaData.class.getMethod("supportsGetGeneratedKeys", null).invoke(meta, null)).booleanValue(); } catch(Throwable e) { getLogger().info("Could not call supportsGetGeneratedKeys method. This may be recoverable"); return false; } } /** * This method handles cases where the * {@link DatabaseMetaData#supportsBatchUpdates} method is missing in the * JDBC driver implementation. */ public boolean supportsBatchUpdates(DatabaseMetaData meta) { try { return meta.supportsBatchUpdates(); } catch(Throwable e) { getLogger().info("Missing DatabaseMetaData.supportsBatchUpdates method."); return false; } } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/db/dialect/db2.sql000066400000000000000000000045271252742764200304440ustar00rootroot00000000000000# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. # # This SQL script creates the required tables by org.apache.log4j.db.DBAppender and # org.apache.log4j.db.DBReceiver. # # It is intended for IBM DB2 databases. # # WARNING WARNING WARNING WARNING # ================================= # This SQL script has not been tested on an actual DB2 # instance. It may contain errors or even invalid SQL # statements. DROP TABLE logging_event_property; DROP TABLE logging_event_exception; DROP TABLE logging_event; CREATE TABLE logging_event ( sequence_number BIGINT NOT NULL, timestamp BIGINT NOT NULL, rendered_message VARCHAR(4000) NOT NULL, logger_name VARCHAR(254) NOT NULL, level_string VARCHAR(254) NOT NULL, ndc VARCHAR(4000), thread_name VARCHAR(254), reference_flag SMALLINT, caller_filename VARCHAR(254) NOT NULL, caller_class VARCHAR(254) NOT NULL, caller_method VARCHAR(254) NOT NULL, caller_line CHAR(4) NOT NULL, event_id INTEGER GENERATED ALWAYS AS IDENTITY (START WITH 1) ); CREATE TABLE logging_event_property ( event_id INTEGER NOT NULL, mapped_key VARCHAR(254) NOT NULL, mapped_value VARCHAR(1024), PRIMARY KEY(event_id, mapped_key), FOREIGN KEY (event_id) REFERENCES logging_event(event_id) ); CREATE TABLE logging_event_exception ( event_id INTEGER NOT NULL, i SMALLINT NOT NULL, trace_line VARCHAR(254) NOT NULL, PRIMARY KEY(event_id, i), FOREIGN KEY (event_id) REFERENCES logging_event(event_id) ); apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/db/dialect/db2l.sql000066400000000000000000000042601252742764200306120ustar00rootroot00000000000000# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. # This SQL script creates the required tables by org.apache.log4j.db.DBAppender and # org.apache.log4j.db.DBReceiver. # # It is intended for PostgreSQL databases. DROP TABLE logging_event_property; DROP TABLE logging_event_exception; DROP TABLE logging_event; CREATE SEQUENCE logging_event_id_seq MINVALUE 1 START 1; CREATE TABLE logging_event ( sequence_number BIGINT NOT NULL, timestamp BIGINT NOT NULL, rendered_message TEXT NOT NULL, logger_name VARCHAR(254) NOT NULL, level_string VARCHAR(254) NOT NULL, ndc TEXT, thread_name VARCHAR(254), reference_flag SMALLINT, caller_filename VARCHAR(254) NOT NULL, caller_class VARCHAR(254) NOT NULL, caller_method VARCHAR(254) NOT NULL, caller_line CHAR(4) NOT NULL, event_id INT IDENTITY GENERATED ALWAYS PRIMARY KEY ); CREATE TABLE logging_event_property ( event_id INT NOT NULL, mapped_key VARCHAR(254) NOT NULL, mapped_value VARCHAR(1024), PRIMARY KEY(event_id, mapped_key), FOREIGN KEY (event_id) REFERENCES logging_event(event_id) ); CREATE TABLE logging_event_exception ( event_id INT NOT NULL, i SMALLINT NOT NULL, trace_line VARCHAR(254) NOT NULL, PRIMARY KEY(event_id, i), FOREIGN KEY (event_id) REFERENCES logging_event(event_id) ); apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/db/dialect/hsqldb.sql000066400000000000000000000041071252742764200312440ustar00rootroot00000000000000// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You 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. // This SQL script creates the required tables by // org.apache.log4j.db.DBAppender and org.apache.log4j.db.DBReceiver. // // It is intended for HSQLDB. // DROP TABLE logging_event_exception IF EXISTS; DROP TABLE logging_event_property IF EXISTS; DROP TABLE logging_event IF EXISTS; CREATE TABLE logging_event ( sequence_number BIGINT NOT NULL, timestamp BIGINT NOT NULL, rendered_message LONGVARCHAR NOT NULL, logger_name VARCHAR NOT NULL, level_string VARCHAR NOT NULL, ndc LONGVARCHAR, thread_name VARCHAR, reference_flag SMALLINT, caller_filename VARCHAR, caller_class VARCHAR, caller_method VARCHAR, caller_line CHAR(4), event_id INT NOT NULL IDENTITY ); CREATE TABLE logging_event_property ( event_id INT NOT NULL, mapped_key VARCHAR(254) NOT NULL, mapped_value LONGVARCHAR, PRIMARY KEY(event_id, mapped_key), FOREIGN KEY (event_id) REFERENCES logging_event(event_id) ); CREATE TABLE logging_event_exception ( event_id INT NOT NULL, i SMALLINT NOT NULL, trace_line VARCHAR NOT NULL, PRIMARY KEY(event_id, i), FOREIGN KEY (event_id) REFERENCES logging_event(event_id) ); apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/db/dialect/mssql.sql000066400000000000000000000043611252742764200311300ustar00rootroot00000000000000-- Licensed to the Apache Software Foundation (ASF) under one or more -- contributor license agreements. See the NOTICE file distributed with -- this work for additional information regarding copyright ownership. -- The ASF licenses this file to You 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. -- -- -- This SQL script creates the required tables by org.apache.log4j.db.DBAppender and -- org.apache.log4j.db.DBReceiver. -- -- It is intended for MS SQL Server databases. This has been tested with version 7.0. DROP TABLE logging_event_property DROP TABLE logging_event_exception DROP TABLE logging_event CREATE TABLE logging_event ( sequence_number DECIMAL(20) NOT NULL, timestamp DECIMAL(20) NOT NULL, rendered_message VARCHAR(4000) NOT NULL, logger_name VARCHAR(254) NOT NULL, level_string VARCHAR(254) NOT NULL, ndc VARCHAR(4000), thread_name VARCHAR(254), reference_flag SMALLINT, caller_filename VARCHAR(254) NOT NULL, caller_class VARCHAR(254) NOT NULL, caller_method VARCHAR(254) NOT NULL, caller_line CHAR(4) NOT NULL, event_id INT NOT NULL identity, PRIMARY KEY(event_id) ) CREATE TABLE logging_event_property ( event_id INT NOT NULL, mapped_key VARCHAR(254) NOT NULL, mapped_value VARCHAR(1024), PRIMARY KEY(event_id, mapped_key), FOREIGN KEY (event_id) REFERENCES logging_event(event_id) ) CREATE TABLE logging_event_exception ( event_id INT NOT NULL, i SMALLINT NOT NULL, trace_line VARCHAR(254) NOT NULL, PRIMARY KEY(event_id, i), FOREIGN KEY (event_id) REFERENCES logging_event(event_id) ) apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/db/dialect/mysql.sql000066400000000000000000000043641252742764200311410ustar00rootroot00000000000000# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. # # # # This SQL script creates the required tables by org.apache.log4j.db.DBAppender and # org.apache.log4j.db.DBReceiver. # # It is intended for MySQL databases. It has been tested on MySQL 4.1.1 with # INNODB tables. BEGIN; DROP TABLE IF EXISTS logging_event_property; DROP TABLE IF EXISTS logging_event_exception; DROP TABLE IF EXISTS logging_event; COMMIT; BEGIN; CREATE TABLE logging_event ( sequence_number BIGINT NOT NULL, timestamp BIGINT NOT NULL, rendered_message TEXT NOT NULL, logger_name VARCHAR(254) NOT NULL, level_string VARCHAR(254) NOT NULL, ndc TEXT, thread_name VARCHAR(254), reference_flag SMALLINT, caller_filename VARCHAR(254) NOT NULL, caller_class VARCHAR(254) NOT NULL, caller_method VARCHAR(254) NOT NULL, caller_line CHAR(4) NOT NULL, event_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ); COMMIT; BEGIN; CREATE TABLE logging_event_property ( event_id INT NOT NULL, mapped_key VARCHAR(254) NOT NULL, mapped_value TEXT, PRIMARY KEY(event_id, mapped_key), FOREIGN KEY (event_id) REFERENCES logging_event(event_id) ); COMMIT; BEGIN; CREATE TABLE logging_event_exception ( event_id INT NOT NULL, i SMALLINT NOT NULL, trace_line VARCHAR(254) NOT NULL, PRIMARY KEY(event_id, i), FOREIGN KEY (event_id) REFERENCES logging_event(event_id) ); COMMIT; apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/db/dialect/oracle.sql000066400000000000000000000053011252742764200312310ustar00rootroot00000000000000-- Licensed to the Apache Software Foundation (ASF) under one or more -- contributor license agreements. See the NOTICE file distributed with -- this work for additional information regarding copyright ownership. -- The ASF licenses this file to You 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. -- -- -- This SQL script creates the required tables by org.apache.log4j.db.DBAppender and -- org.apache.log4j.db.DBReceiver. -- -- It is intended for Oracle databases. -- Tested successfully on Oracle9i Release 9.2.0.3.0 by James Stauffer -- Tested successfully on Oracle9i Release by Elias Ross -- The following lines are useful in cleaning any previous tables --drop TRIGGER logging_event_id_seq_trig; --drop SEQUENCE logging_event_id_seq; --drop table logging_event_property; --drop table logging_event_exception; --drop table logging_event; CREATE SEQUENCE logging_event_id_seq MINVALUE 1 START WITH 1; CREATE TABLE logging_event ( sequence_number NUMBER(20) NOT NULL, timestamp NUMBER(20) NOT NULL, rendered_message VARCHAR2(4000) NOT NULL, logger_name VARCHAR2(254) NOT NULL, level_string VARCHAR2(254) NOT NULL, ndc VARCHAR2(4000), thread_name VARCHAR2(254), reference_flag NUMBER(5), caller_filename VARCHAR2(254) NOT NULL, caller_class VARCHAR2(254) NOT NULL, caller_method VARCHAR2(254) NOT NULL, caller_line CHAR(4) NOT NULL, event_id NUMBER(10) PRIMARY KEY ); CREATE OR REPLACE TRIGGER logging_event_id_seq_trig BEFORE INSERT ON logging_event FOR EACH ROW BEGIN SELECT logging_event_id_seq.nextval INTO :new.sequence_number FROM dual; END; CREATE TABLE logging_event_property ( event_id NUMBER(10) NOT NULL, mapped_key VARCHAR2(254) NOT NULL, mapped_value VARCHAR2(1024), PRIMARY KEY(event_id, mapped_key), FOREIGN KEY (event_id) REFERENCES logging_event(event_id) ); CREATE TABLE logging_event_exception ( event_id NUMBER(10) NOT NULL, i NUMBER(5) NOT NULL, trace_line VARCHAR2(254) NOT NULL, PRIMARY KEY(event_id, i), FOREIGN KEY (event_id) REFERENCES logging_event(event_id) ); apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/db/dialect/postgresql.sql000066400000000000000000000043451252742764200321760ustar00rootroot00000000000000# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. # ## This SQL script creates the required tables by org.apache.log4j.db.DBAppender and # org.apache.log4j.db.DBReceiver. # # It is intended for PostgreSQL databases. DROP TABLE logging_event_property; DROP TABLE logging_event_exception; DROP SEQUENCE logging_event_id_seq; DROP TABLE logging_event; CREATE SEQUENCE logging_event_id_seq MINVALUE 1 START 1; CREATE TABLE logging_event ( sequence_number BIGINT NOT NULL, timestamp BIGINT NOT NULL, rendered_message TEXT NOT NULL, logger_name VARCHAR(254) NOT NULL, level_string VARCHAR(254) NOT NULL, ndc TEXT, thread_name VARCHAR(254), reference_flag SMALLINT, caller_filename VARCHAR(254) NOT NULL, caller_class VARCHAR(254) NOT NULL, caller_method VARCHAR(254) NOT NULL, caller_line CHAR(4) NOT NULL, event_id INT DEFAULT nextval('logging_event_id_seq') PRIMARY KEY ); CREATE TABLE logging_event_property ( event_id INT NOT NULL, mapped_key VARCHAR(254) NOT NULL, mapped_value VARCHAR(1024), PRIMARY KEY(event_id, mapped_key), FOREIGN KEY (event_id) REFERENCES logging_event(event_id) ); CREATE TABLE logging_event_exception ( event_id INT NOT NULL, i SMALLINT NOT NULL, trace_line VARCHAR(254) NOT NULL, PRIMARY KEY(event_id, i), FOREIGN KEY (event_id) REFERENCES logging_event(event_id) ); apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/db/package.html000066400000000000000000000025651252742764200301300ustar00rootroot00000000000000

The org.apache.log4j.db package provides means to append logging events into various databases. The persisted data can be later read back using {@link org.apache.log4j.receivers.db.DBReceiver}.

Most popular database systems, such as PostgreSQL, MySQL, Oracle, DB2 and MsSQL are supported.

Just as importantly, the way for obtaining JDBC connections is pluggable. Connections can be obtained through the traditional way of DriverManager, or alternatively as a DataSource. A DataSource can be instantiated directly or it can obtained through JNDI.

apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/helpers/000077500000000000000000000000001252742764200267145ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/helpers/UtilLoggingLevel.java000066400000000000000000000143471252742764200330040ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.helpers; import org.apache.log4j.Level; import java.util.ArrayList; import java.util.List; /** * An extension of the Level class that provides support for java.util.logging * Levels. * * * @author Scott Deboy (sdeboy@apache.org) */ public class UtilLoggingLevel extends Level { /** * Serialization version id. */ private static final long serialVersionUID = 909301162611820211L; /** * Numerical value for SEVERE. */ public static final int SEVERE_INT = 22000; /** * Numerical value for WARNING. */ public static final int WARNING_INT = 21000; //INFO level defined in parent as 20000..no need to redefine here /** * Numerical value for CONFIG. */ public static final int CONFIG_INT = 14000; /** * Numerical value for FINE. */ public static final int FINE_INT = 13000; /** * Numerical value for FINER. */ public static final int FINER_INT = 12000; /** * Numerical value for FINEST. */ public static final int FINEST_INT = 11000; /** * Numerical value for UNKNOWN. */ public static final int UNKNOWN_INT = 10000; /** * SEVERE. */ public static final UtilLoggingLevel SEVERE = new UtilLoggingLevel(SEVERE_INT, "SEVERE", 0); /** * WARNING. */ public static final UtilLoggingLevel WARNING = new UtilLoggingLevel(WARNING_INT, "WARNING", 4); /** * INFO. */ //note: we've aligned the int values of the java.util.logging INFO level with log4j's level public static final UtilLoggingLevel INFO = new UtilLoggingLevel(INFO_INT, "INFO", 5); /** * CONFIG. */ public static final UtilLoggingLevel CONFIG = new UtilLoggingLevel(CONFIG_INT, "CONFIG", 6); /** * FINE. */ public static final UtilLoggingLevel FINE = new UtilLoggingLevel(FINE_INT, "FINE", 7); /** * FINER. */ public static final UtilLoggingLevel FINER = new UtilLoggingLevel(FINER_INT, "FINER", 8); /** * FINEST. */ public static final UtilLoggingLevel FINEST = new UtilLoggingLevel(FINEST_INT, "FINEST", 9); /** * Create new instance. * @param level numeric value for level. * @param levelStr symbolic name for level. * @param syslogEquivalent Equivalent syslog severity. */ protected UtilLoggingLevel(final int level, final String levelStr, final int syslogEquivalent) { super(level, levelStr, syslogEquivalent); } /** * Convert an integer passed as argument to a level. If the * conversion fails, then this method returns the specified default. * @param val numeric value. * @param defaultLevel level to be returned if no level matches * numeric value. * @return matching level or default level. */ public static UtilLoggingLevel toLevel(final int val, final UtilLoggingLevel defaultLevel) { switch (val) { case SEVERE_INT: return SEVERE; case WARNING_INT: return WARNING; case INFO_INT: return INFO; case CONFIG_INT: return CONFIG; case FINE_INT: return FINE; case FINER_INT: return FINER; case FINEST_INT: return FINEST; default: return defaultLevel; } } /** * Gets level matching numeric value. * @param val numeric value. * @return matching level or UtilLoggerLevel.FINEST if no match. */ public static Level toLevel(final int val) { return toLevel(val, FINEST); } /** * Gets list of supported levels. * @return list of supported levels. */ public static List getAllPossibleLevels() { ArrayList list = new ArrayList(); list.add(FINE); list.add(FINER); list.add(FINEST); list.add(INFO); list.add(CONFIG); list.add(WARNING); list.add(SEVERE); return list; } /** * Get level with specified symbolic name. * @param s symbolic name. * @return matching level or Level.DEBUG if no match. */ public static Level toLevel(final String s) { return toLevel(s, Level.DEBUG); } /** * Get level with specified symbolic name. * @param sArg symbolic name. * @param defaultLevel level to return if no match. * @return matching level or defaultLevel if no match. */ public static Level toLevel(final String sArg, final Level defaultLevel) { if (sArg == null) { return defaultLevel; } String s = sArg.toUpperCase(); if (s.equals("SEVERE")) { return SEVERE; } //if(s.equals("FINE")) return Level.FINE; if (s.equals("WARNING")) { return WARNING; } if (s.equals("INFO")) { return INFO; } if (s.equals("CONFI")) { return CONFIG; } if (s.equals("FINE")) { return FINE; } if (s.equals("FINER")) { return FINER; } if (s.equals("FINEST")) { return FINEST; } return defaultLevel; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/net/000077500000000000000000000000001252742764200260405ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/net/AddressBased.java000066400000000000000000000023631252742764200312330ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.net; /** * Net based entities that 'work with' an Address * should consider implementing this * interface so that they can be treated generically. * * @author Paul Smith (psmith@apache.org) * */ public interface AddressBased extends NetworkBased { /** * Returns a String representation of the Address this instance * encompasses. * @return String representation of the Address */ String getAddress(); } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/net/JMSReceiver.java000066400000000000000000000205771252742764200310340ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.net; import org.apache.log4j.component.plugins.Plugin; import org.apache.log4j.component.plugins.Receiver; import org.apache.log4j.spi.LoggingEvent; import javax.jms.*; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NameNotFoundException; import javax.naming.NamingException; import java.io.FileInputStream; import java.util.Properties; /** JMSReceiver receives a remote logging event on a configured JSM topic and "posts" it to a LoggerRepository as if the event was generated locally. This class is designed to receive events from the JMSAppender class (or classes that send compatible events).

Once the event has been "posted", it will be handled by the appenders currently configured in the LoggerRespository.

This implementation borrows heavily from the JMSSink implementation. @author Mark Womack @author Paul Smith @author Stephen Pain */ public class JMSReceiver extends Receiver implements MessageListener { private boolean active = false; protected String topicFactoryName; protected String topicName; protected String userId; protected String password; protected TopicConnection topicConnection; protected String jndiPath; private String remoteInfo; private String providerUrl; public JMSReceiver() { } public JMSReceiver(String _topicFactoryName, String _topicName, String _userId, String _password, String _jndiPath) { topicFactoryName = _topicFactoryName; topicName = _topicName; userId = _userId; password = _password; jndiPath = _jndiPath; } /** * Sets the path to a properties file containing * the initial context and jndi provider url */ public void setJndiPath(String _jndiPath) { jndiPath = _jndiPath; } /** * Gets the path to a properties file containing * the initial context and jndi provider url */ public String getJndiPath() { return jndiPath; } /** Sets the JMS topic factory name to use when creating the JMS connection. */ public void setTopicFactoryName(String _topicFactoryName) { topicFactoryName = _topicFactoryName; } /** Gets the curernt JMS topic factory name property. */ public String getTopicFactoryName() { return topicFactoryName; } /** * Sets the JMS topic name to use when creating the * JMS connection. */ public void setTopicName(String _topicName) { topicName = _topicName; } /** * Gets the curernt JMS topic name property. */ public String getTopicName() { return topicName; } /** Sets the user id to use when creating the JMS connection. */ public void setUserId(String _userId) { userId = _userId; } /** * Gets the current user id property. */ public String getUserId() { return userId; } /** * Sets the password to use when creating the * JMS connection. */ public void setPassword(String _password) { password = _password; } /** * Gets the curernt password property. */ public String getPassword() { return password; } /** * Returns true if the receiver is the same class and they are * configured for the same properties, and super class also considers * them to be equivalent. This is used by PluginRegistry when determining * if the a similarly configured receiver is being started. * * @param testPlugin The plugin to test equivalency against. * @return boolean True if the testPlugin is equivalent to this plugin. */ public boolean isEquivalent(Plugin testPlugin) { // only do full check if an instance of this class if (testPlugin instanceof JMSReceiver) { JMSReceiver receiver = (JMSReceiver)testPlugin; // check for same topic name and super class equivalency return ( topicFactoryName.equals(receiver.getTopicFactoryName()) && (jndiPath == null || jndiPath.equals(receiver.getJndiPath())) && super.isEquivalent(testPlugin) ); } return false; } /** Returns true if this receiver is active. */ public synchronized boolean isActive() { return active; } /** Sets the flag to indicate if receiver is active or not. */ protected synchronized void setActive(boolean _active) { active = _active; } /** Starts the JMSReceiver with the current options. */ public void activateOptions() { if (!isActive()) { try { remoteInfo = topicFactoryName + ":" + topicName; Context ctx = null; if (jndiPath == null || jndiPath.equals("")) { ctx = new InitialContext(); } else { FileInputStream is = new FileInputStream(jndiPath); Properties p = new Properties(); p.load(is); is.close(); ctx = new InitialContext(p); } // give some more flexibility about the choice of a tab name providerUrl = (String)ctx.getEnvironment().get(Context.PROVIDER_URL); TopicConnectionFactory topicConnectionFactory; topicConnectionFactory = (TopicConnectionFactory) lookup(ctx, topicFactoryName); if (userId != null && password != null) { topicConnection = topicConnectionFactory.createTopicConnection(userId, password); } else { topicConnection = topicConnectionFactory.createTopicConnection(); } TopicSession topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); Topic topic = (Topic)ctx.lookup(topicName); TopicSubscriber topicSubscriber = topicSession.createSubscriber(topic); topicSubscriber.setMessageListener(this); topicConnection.start(); setActive(true); } catch(Exception e) { setActive(false); if (topicConnection != null) { try { topicConnection.close(); } catch (Exception e2) { // do nothing } topicConnection = null; } getLogger().error("Could not start JMSReceiver.", e); } } } /** Called when the receiver should be stopped. */ public synchronized void shutdown() { if (isActive()) { // mark this as no longer running setActive(false); if (topicConnection != null) { try { topicConnection.close(); } catch (Exception e) { // do nothing } topicConnection = null; } } } public void onMessage(Message message) { try { if(message instanceof ObjectMessage) { // get the logging event and post it to the repository ObjectMessage objectMessage = (ObjectMessage) message; LoggingEvent event = (LoggingEvent) objectMessage.getObject(); // store the known remote info in an event property event.setProperty("log4j.remoteSourceInfo", remoteInfo); event.setProperty("log4j.jmsProviderUrl", providerUrl); doPost(event); } else { getLogger().warn("Received message is of type "+message.getJMSType() +", was expecting ObjectMessage."); } } catch(Exception e) { getLogger().error("Exception thrown while processing incoming message.", e); } } protected Object lookup(Context ctx, String name) throws NamingException { try { return ctx.lookup(name); } catch(NameNotFoundException e) { getLogger().error("Could not find name ["+name+"]."); throw e; } } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/net/JMSReceiverBeanInfo.java000066400000000000000000000034361252742764200324310ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.net; import java.beans.PropertyDescriptor; import java.beans.SimpleBeanInfo; /** * BeanInfo class for the JMSReceiver. * * @author Paul Smith * */ public class JMSReceiverBeanInfo extends SimpleBeanInfo { /* (non-Javadoc) * @see java.beans.BeanInfo#getPropertyDescriptors() */ public PropertyDescriptor[] getPropertyDescriptors() { try { return new PropertyDescriptor[] { new PropertyDescriptor("name", JMSReceiver.class), new PropertyDescriptor("topicFactoryName", JMSReceiver.class), new PropertyDescriptor("topicName", JMSReceiver.class), new PropertyDescriptor("threshold", JMSReceiver.class), new PropertyDescriptor("jndiPath", JMSReceiver.class), new PropertyDescriptor("userId", JMSReceiver.class), }; } catch (Exception e) { } return null; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/net/MulticastAppender.java000066400000000000000000000222001252742764200323230ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.net; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.component.helpers.Constants; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.net.ZeroConfSupport; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.xml.XMLLayout; import java.io.IOException; import java.net.DatagramPacket; import java.net.InetAddress; import java.net.MulticastSocket; import java.net.UnknownHostException; import java.util.HashMap; import java.util.Map; /** * Multicast-based Appender. Works in conjunction with the MulticastReceiver, which expects * a LoggingEvent encoded using XMLLayout. * * Sends log information as a multicast datagrams. * *

Messages are not sent as LoggingEvent objects but as text after * applying XMLLayout. * *

The port and remoteHost properties can be set in configuration properties. * By setting the remoteHost to a broadcast address any number of clients can * listen for log messages. * *

This was inspired and really extended/copied from {@link org.apache.log4j.net.SocketAppender}. Please * see the docs for the proper credit to the authors of that class. * * @author Kevin Brown * @author Scott Deboy * */ public class MulticastAppender extends AppenderSkeleton implements PortBased { /** The default port number for the multicast packets. (9991). */ static final int DEFAULT_PORT = 9991; /** * The MulticastDNS zone advertised by a MulticastAppender * the MulticastAppender also adds a 'multicastAddress' property with the multicast address value as a string */ public static final String ZONE = "_log4j_xml_mcast_appender.local."; /** We remember host name as String in addition to the resolved InetAddress so that it can be returned via getOption(). */ String hostname; String remoteHost; String application; int timeToLive; InetAddress address; int port = DEFAULT_PORT; MulticastSocket outSocket; private String encoding; private boolean locationInfo = false; private boolean advertiseViaMulticastDNS; private ZeroConfSupport zeroConf; public MulticastAppender() { super(false); } /** Open the multicast sender for the RemoteHost and Port. */ public void activateOptions() { try { hostname = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException uhe) { try { hostname = InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException uhe2) { hostname = "unknown"; } } //allow system property of application to be primary if (application == null) { application = System.getProperty(Constants.APPLICATION_KEY); } else { if (System.getProperty(Constants.APPLICATION_KEY) != null) { application = application + "-" + System.getProperty(Constants.APPLICATION_KEY); } } if(remoteHost != null) { address = getAddressByName(remoteHost); } else { String err = "The RemoteHost property is required for MulticastAppender named "+ name; LogLog.error(err); throw new IllegalStateException(err); } if (layout == null) { layout = new XMLLayout(); } if (advertiseViaMulticastDNS) { Map properties = new HashMap(); properties.put("multicastAddress", remoteHost); zeroConf = new ZeroConfSupport(ZONE, port, getName(), properties); zeroConf.advertise(); } connect(); super.activateOptions(); } /** Close this appender.

This will mark the appender as closed and call then {@link #cleanUp} method. */ public synchronized void close() { if (closed) { return; } this.closed = true; if (advertiseViaMulticastDNS) { zeroConf.unadvertise(); } cleanUp(); } /** Close the Socket and release the underlying connector thread if it has been created */ public void cleanUp() { if (outSocket != null) { try { outSocket.close(); } catch (Exception e) { LogLog.error("Could not close outSocket.", e); } outSocket = null; } } void connect() { if (this.address == null) { return; } try { // First, close the previous connection if any. cleanUp(); outSocket = new MulticastSocket(); outSocket.setTimeToLive(timeToLive); } catch (IOException e) { LogLog.error("Error in connect method of MulticastAppender named "+name, e); } } public void append(LoggingEvent event) { if (event == null) { return; } if(locationInfo) { event.getLocationInformation(); } if (outSocket != null) { event.setProperty(Constants.HOSTNAME_KEY, hostname); if (application != null) { event.setProperty(Constants.APPLICATION_KEY, application); } if(locationInfo) { event.getLocationInformation(); } try { StringBuffer buf = new StringBuffer(layout.format(event)); byte[] payload; if(encoding == null) { payload = buf.toString().getBytes(); } else { payload = buf.toString().getBytes(encoding); } DatagramPacket dp = new DatagramPacket(payload, payload.length, address, port); outSocket.send(dp); } catch (IOException e) { outSocket = null; LogLog.warn("Detected problem with Multicast connection: " + e); } } } InetAddress getAddressByName(String host) { try { return InetAddress.getByName(host); } catch (Exception e) { LogLog.error("Could not find address of [" + host + "].", e); return null; } } /** The RemoteHost option takes a string value which should be the host name or ipaddress to send the multicast packets. */ public void setRemoteHost(String host) { remoteHost = host; } /** Returns value of the RemoteHost option. */ public String getRemoteHost() { return remoteHost; } /** The LocationInfo option takes a boolean value. If true, the information sent to the remote host will include location information. By default no location information is sent to the server. */ public void setLocationInfo(boolean locationInfo) { this.locationInfo = locationInfo; } /** * Returns value of the LocationInfo option. */ public boolean getLocationInfo() { return locationInfo; } /** The Encoding option specifies how the bytes are encoded. If this option is not specified, the System encoding is used. */ public void setEncoding(String encoding) { this.encoding = encoding; } /** Returns value of the Encoding option. */ public String getEncoding() { return encoding; } /** The App option takes a string value which should be the name of the application getting logged. If property was already set (via system property), don't set here. */ public void setApplication(String app) { this.application = app; } /** Returns value of the App option. */ public String getApplication() { return application; } /** The Time to live option takes a positive integer representing the time to live value. */ public void setTimeToLive(int timeToLive) { this.timeToLive = timeToLive; } /** Returns value of the Time to Live option. */ public int getTimeToLive() { return timeToLive; } /** The Port option takes a positive integer representing the port where multicast packets will be sent. */ public void setPort(int port) { this.port = port; } /** Returns value of the Port option. */ public int getPort() { return port; } /* (non-Javadoc) * @see org.apache.log4j.net.NetworkBased#isActive() */ public boolean isActive() { // TODO handle active/inactive return true; } /** * Gets whether appender requires a layout. * @return false */ public boolean requiresLayout() { return true; } public boolean isAdvertiseViaMulticastDNS() { return advertiseViaMulticastDNS; } public void setAdvertiseViaMulticastDNS(boolean advertiseViaMulticastDNS) { this.advertiseViaMulticastDNS = advertiseViaMulticastDNS; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/net/MulticastReceiver.java000066400000000000000000000157361252742764200323510ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.net; import org.apache.log4j.component.plugins.Pauseable; import org.apache.log4j.component.plugins.Receiver; import org.apache.log4j.net.ZeroConfSupport; import org.apache.log4j.receivers.spi.Decoder; import org.apache.log4j.spi.LoggingEvent; import java.io.IOException; import java.net.*; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Multicast-based receiver. Accepts LoggingEvents encoded using * MulticastAppender and XMLLayout. The the XML data is converted * back to a LoggingEvent and is posted. * * @author Scott Deboy * */ public class MulticastReceiver extends Receiver implements PortBased, AddressBased, Pauseable { private static final int PACKET_LENGTH = 16384; private int port; private String address; private String encoding; private MulticastSocket socket = null; //default to log4j xml decoder private String decoder = "org.apache.log4j.xml.XMLDecoder"; private Decoder decoderImpl; private MulticastHandlerThread handlerThread; private MulticastReceiverThread receiverThread; private boolean paused; private boolean advertiseViaMulticastDNS; private ZeroConfSupport zeroConf; /** * The MulticastDNS zone advertised by a MulticastReceiver */ public static final String ZONE = "_log4j_xml_mcast_receiver.local."; public String getDecoder() { return decoder; } public void setDecoder(String decoder) { this.decoder = decoder; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public String getAddress() { return address; } /** The Encoding option specifies how the bytes are encoded. If this option is not specified, the system encoding will be used. */ public void setEncoding(String encoding) { this.encoding = encoding; } /** Returns value of the Encoding option. */ public String getEncoding() { return encoding; } public synchronized void shutdown() { active = false; if (advertiseViaMulticastDNS) { zeroConf.unadvertise(); } if (handlerThread != null) { handlerThread.interrupt(); } if (receiverThread != null) { receiverThread.interrupt(); } if (socket != null) { socket.close(); } } public void setAddress(String address) { this.address = address; } public boolean isPaused() { return paused; } public void setPaused(boolean b) { paused = b; } public void activateOptions() { InetAddress addr = null; try { Class c = Class.forName(decoder); Object o = c.newInstance(); if (o instanceof Decoder) { this.decoderImpl = (Decoder) o; } } catch (ClassNotFoundException cnfe) { getLogger().warn("Unable to find decoder", cnfe); } catch (IllegalAccessException iae) { getLogger().warn("Could not construct decoder", iae); } catch (InstantiationException ie) { getLogger().warn("Could not construct decoder", ie); } try { addr = InetAddress.getByName(address); } catch (UnknownHostException uhe) { uhe.printStackTrace(); } try { active = true; socket = new MulticastSocket(port); socket.joinGroup(addr); receiverThread = new MulticastReceiverThread(); receiverThread.start(); handlerThread = new MulticastHandlerThread(); handlerThread.start(); if (advertiseViaMulticastDNS) { zeroConf = new ZeroConfSupport(ZONE, port, getName()); zeroConf.advertise(); } } catch (IOException ioe) { ioe.printStackTrace(); } } public void setAdvertiseViaMulticastDNS(boolean advertiseViaMulticastDNS) { this.advertiseViaMulticastDNS = advertiseViaMulticastDNS; } public boolean isAdvertiseViaMulticastDNS() { return advertiseViaMulticastDNS; } class MulticastHandlerThread extends Thread { private List list = new ArrayList(); public MulticastHandlerThread() { setDaemon(true); } public void append(String data) { synchronized (list) { list.add(data); list.notify(); } } public void run() { ArrayList list2 = new ArrayList(); while (isAlive()) { synchronized (list) { try { while (list.size() == 0) { list.wait(); } if (list.size() > 0) { list2.addAll(list); list.clear(); } } catch (InterruptedException ie) { } } if (list2.size() > 0) { Iterator iter = list2.iterator(); while (iter.hasNext()) { String data = (String) iter.next(); List v = decoderImpl.decodeEvents(data.trim()); if (v != null) { Iterator eventIter = v.iterator(); while (eventIter.hasNext()) { if (!isPaused()) { doPost((LoggingEvent) eventIter.next()); } } } } list2.clear(); } else { try { synchronized (this) { wait(1000); } } catch (InterruptedException ie) { } } } } } class MulticastReceiverThread extends Thread { public MulticastReceiverThread() { setDaemon(true); } public void run() { active = true; byte[] b = new byte[PACKET_LENGTH]; DatagramPacket p = new DatagramPacket(b, b.length); while (active) { try { socket.receive(p); //this string constructor which accepts a charset throws an exception if it is //null if (encoding == null) { handlerThread.append( new String(p.getData(), 0, p.getLength())); } else { handlerThread.append( new String(p.getData(), 0, p.getLength(), encoding)); } } catch (SocketException se) { //disconnected } catch (IOException ioe) { ioe.printStackTrace(); } } getLogger().debug("{}'s thread is ending.", MulticastReceiver.this.getName()); } } } MulticastReceiverBeanInfo.java000066400000000000000000000035121252742764200336610ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/net/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.net; import java.beans.PropertyDescriptor; import java.beans.SimpleBeanInfo; /** * BeanInfo class for the meta-data of the MulticastReceiver. * * @author Paul Smith * */ public class MulticastReceiverBeanInfo extends SimpleBeanInfo { /* (non-Javadoc) * @see java.beans.BeanInfo#getPropertyDescriptors() */ public PropertyDescriptor[] getPropertyDescriptors() { try { return new PropertyDescriptor[] { new PropertyDescriptor("name", MulticastReceiver.class), new PropertyDescriptor("address", MulticastReceiver.class), new PropertyDescriptor("port", MulticastReceiver.class), new PropertyDescriptor("threshold", MulticastReceiver.class), new PropertyDescriptor("decoder", MulticastReceiver.class), new PropertyDescriptor("advertiseViaMulticastDNS", MulticastReceiver.class), }; } catch (Exception e) { } return null; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/net/NetworkBased.java000066400000000000000000000022221252742764200312710ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.net; /** * The parent of all the Network based interfaces. * * @author Paul Smith (psmith@apache.org) * */ public interface NetworkBased { /** * Get name. * @return name. */ String getName(); /** * Get if item is active. * @return if true, item is active. */ boolean isActive(); } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/net/PortBased.java000066400000000000000000000022661252742764200305740ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.net; /** * Net based entities that 'work with' a Port should consider implementing this * interface so that they can be treated generically. * * @author Paul Smith (psmith@apache.org) * */ public interface PortBased extends NetworkBased { /** * Returns the Port # that this net based thing is using. * @return int port number */ int getPort(); } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/net/SocketHubReceiver.java000066400000000000000000000260161252742764200322640ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.net; import org.apache.log4j.component.plugins.Plugin; import org.apache.log4j.component.plugins.Receiver; import org.apache.log4j.net.ZeroConfSupport; import org.apache.log4j.spi.LoggerRepository; import java.io.IOException; import java.net.Socket; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; /** SocketHubReceiver receives a remote logging event on a configured socket and "posts" it to a LoggerRepository as if the event was generated locally. This class is designed to receive events from the SocketHubAppender class (or classes that send compatible events).

Once the event has been "posted", it will be handled by the appenders currently configured in the LoggerRespository. @author Mark Womack @author Ceki Gülcü @author Paul Smith (psmith@apache.org) */ public class SocketHubReceiver extends Receiver implements SocketNodeEventListener, PortBased { /** * Default reconnection delay. */ static final int DEFAULT_RECONNECTION_DELAY = 30000; /** * Host. */ protected String host; /** * Port. */ protected int port; /** * Reconnection delay. */ protected int reconnectionDelay = DEFAULT_RECONNECTION_DELAY; /** * The MulticastDNS zone advertised by a SocketHubReceiver */ public static final String ZONE = "_log4j_obj_tcpconnect_receiver.local."; /** * Active. */ protected boolean active = false; /** * Connector. */ protected Connector connector; /** * Socket. */ protected SocketNode13 socketNode; /** * Listener list. */ private List listenerList = Collections.synchronizedList(new ArrayList()); private boolean advertiseViaMulticastDNS; private ZeroConfSupport zeroConf; /** * Create new instance. */ public SocketHubReceiver() { super(); } /** * Create new instance. * @param h host * @param p port */ public SocketHubReceiver(final String h, final int p) { super(); host = h; port = p; } /** * Create new instance. * @param h host * @param p port * @param repo logger repository */ public SocketHubReceiver(final String h, final int p, final LoggerRepository repo) { super(); host = h; port = p; repository = repo; } /** * Adds a SocketNodeEventListener to this receiver to be notified * of SocketNode events. * @param l listener */ public void addSocketNodeEventListener(final SocketNodeEventListener l) { listenerList.add(l); } /** * Removes a specific SocketNodeEventListener from this instance * so that it will no longer be notified of SocketNode events. * @param l listener */ public void removeSocketNodeEventListener( final SocketNodeEventListener l) { listenerList.remove(l); } /** Get the remote host to connect to for logging events. @return host */ public String getHost() { return host; } /** * Configures the Host property, this will require activateOptions * to be called for this to take effect. * @param remoteHost address of remote host. */ public void setHost(final String remoteHost) { this.host = remoteHost; } /** Set the remote host to connect to for logging events. Equivalent to setHost. @param remoteHost address of remote host. */ public void setPort(final String remoteHost) { host = remoteHost; } /** Get the remote port to connect to for logging events. @return port */ public int getPort() { return port; } /** Set the remote port to connect to for logging events. @param p port */ public void setPort(final int p) { this.port = p; } /** The ReconnectionDelay option takes a positive integer representing the number of milliseconds to wait between each failed connection attempt to the server. The default value of this option is 30000 which corresponds to 30 seconds.

Setting this option to zero turns off reconnection capability. @param delay milliseconds to wait or zero to not reconnect. */ public void setReconnectionDelay(final int delay) { int oldValue = this.reconnectionDelay; this.reconnectionDelay = delay; firePropertyChange("reconnectionDelay", oldValue, this.reconnectionDelay); } /** Returns value of the ReconnectionDelay option. @return value of reconnection delay option. */ public int getReconnectionDelay() { return reconnectionDelay; } /** * Returns true if the receiver is the same class and they are * configured for the same properties, and super class also considers * them to be equivalent. This is used by PluginRegistry when determining * if the a similarly configured receiver is being started. * * @param testPlugin The plugin to test equivalency against. * @return boolean True if the testPlugin is equivalent to this plugin. */ public boolean isEquivalent(final Plugin testPlugin) { if (testPlugin != null && testPlugin instanceof SocketHubReceiver) { SocketHubReceiver sReceiver = (SocketHubReceiver) testPlugin; return (port == sReceiver.getPort() && host.equals(sReceiver.getHost()) && reconnectionDelay == sReceiver.getReconnectionDelay() && super.isEquivalent(testPlugin)); } return false; } /** Sets the flag to indicate if receiver is active or not. @param b new value */ protected synchronized void setActive(final boolean b) { active = b; } /** Starts the SocketReceiver with the current options. */ public void activateOptions() { if (!isActive()) { setActive(true); if (advertiseViaMulticastDNS) { zeroConf = new ZeroConfSupport(ZONE, port, getName()); zeroConf.advertise(); } fireConnector(false); } } /** Called when the receiver should be stopped. Closes the socket */ public synchronized void shutdown() { // mark this as no longer running active = false; // close the socket try { if (socketNode != null) { socketNode.close(); socketNode = null; } } catch (Exception e) { getLogger().info("Excpetion closing socket", e); // ignore for now } // stop the connector if (connector != null) { connector.interrupted = true; connector = null; // allow gc } if (advertiseViaMulticastDNS) { zeroConf.unadvertise(); } } /** Listen for a socketClosedEvent from the SocketNode. Reopen the socket if this receiver is still active. @param e exception not used. */ public void socketClosedEvent(final Exception e) { // if it is a non-normal closed event // we clear the connector object here // so that it actually does reconnect if the // remote socket dies. if (e != null) { connector = null; fireConnector(true); } } /** * Fire connectors. * @param isReconnect true if reconnect. */ private synchronized void fireConnector(final boolean isReconnect) { if (active && connector == null) { getLogger().debug("Starting a new connector thread."); connector = new Connector(isReconnect); connector.setDaemon(true); connector.setPriority(Thread.MIN_PRIORITY); connector.start(); } } /** * Set socket. * @param newSocket new value for socket. */ private synchronized void setSocket(final Socket newSocket) { connector = null; socketNode = new SocketNode13(newSocket, this); socketNode.addSocketNodeEventListener(this); synchronized (listenerList) { for (Iterator iter = listenerList.iterator(); iter.hasNext();) { SocketNodeEventListener listener = (SocketNodeEventListener) iter.next(); socketNode.addSocketNodeEventListener(listener); } } new Thread(socketNode).start(); } public void setAdvertiseViaMulticastDNS(boolean advertiseViaMulticastDNS) { this.advertiseViaMulticastDNS = advertiseViaMulticastDNS; } public boolean isAdvertiseViaMulticastDNS() { return advertiseViaMulticastDNS; } /** The Connector will reconnect when the server becomes available again. It does this by attempting to open a new connection every reconnectionDelay milliseconds.

It stops trying whenever a connection is established. It will restart to try reconnect to the server when previpously open connection is droppped. @author Ceki Gülcü */ private final class Connector extends Thread { /** * Interruption status. */ boolean interrupted = false; /** * If true, then delay on next iteration. */ boolean doDelay; /** * Create new instance. * @param isReconnect true if reconnecting. */ public Connector(final boolean isReconnect) { super(); doDelay = isReconnect; } /** * Attempt to connect until interrupted. */ public void run() { while (!interrupted) { try { if (doDelay) { getLogger().debug("waiting for " + reconnectionDelay + " milliseconds before reconnecting."); sleep(reconnectionDelay); } doDelay = true; getLogger().debug("Attempting connection to " + host); Socket s = new Socket(host, port); setSocket(s); getLogger().debug( "Connection established. Exiting connector thread."); break; } catch (InterruptedException e) { getLogger().debug("Connector interrupted. Leaving loop."); return; } catch (java.net.ConnectException e) { getLogger().debug("Remote host {} refused connection.", host); } catch (IOException e) { getLogger().debug("Could not connect to {}. Exception is {}.", host, e); } } } } /** * This method does nothing. * @param remoteInfo remote info. */ public void socketOpened(final String remoteInfo) { // This method does nothing. } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/net/SocketNode13.java000066400000000000000000000210551252742764200311100ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.net; import org.apache.log4j.Logger; import org.apache.log4j.component.helpers.Constants; import org.apache.log4j.component.plugins.Pauseable; import org.apache.log4j.component.plugins.Receiver; import org.apache.log4j.component.spi.ComponentBase; import org.apache.log4j.spi.LoggerRepository; import org.apache.log4j.spi.LoggingEvent; import java.io.BufferedInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.net.Socket; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; // Contributors: Moses Hohman /** Read {@link LoggingEvent} objects sent from a remote client using Sockets (TCP). These logging events are logged according to local policy, as if they were generated locally.

For example, the socket node might decide to log events to a local file and also resent them to a second socket node. Implementation lifted from org.apache.log4j.net.SocketNode in log4j 1.3 and renamed to prevent collision with log4j 1.2 implementation. @author Ceki Gülcü @author Paul Smith (psmith@apache.org) */ public class SocketNode13 extends ComponentBase implements Runnable, Pauseable { /** * Paused state. */ private boolean paused; /** * Closed state. */ private boolean closed; /** * Socket. */ private Socket socket; /** * Receiver. */ private Receiver receiver; /** * List of listeners. */ private List listenerList = Collections.synchronizedList(new ArrayList()); /** Constructor for socket and logger repository. @param s socket @param hierarchy logger repository */ public SocketNode13(final Socket s, final LoggerRepository hierarchy) { super(); this.socket = s; this.repository = hierarchy; } /** Constructor for socket and receiver. @param s socket @param r receiver */ public SocketNode13(final Socket s, final Receiver r) { super(); this.socket = s; this.receiver = r; } /** * Set the event listener on this node. * * @deprecated Now supports mutliple listeners, this method * simply invokes the removeSocketNodeEventListener() to remove * the listener, and then readds it. * @param l listener */ public void setListener(final SocketNodeEventListener l) { removeSocketNodeEventListener(l); addSocketNodeEventListener(l); } /** * Adds the listener to the list of listeners to be notified of the * respective event. * @param listener the listener to add to the list */ public void addSocketNodeEventListener( final SocketNodeEventListener listener) { listenerList.add(listener); } /** * Removes the registered Listener from this instances list of * listeners. If the listener has not been registered, then invoking * this method has no effect. * * @param listener the SocketNodeEventListener to remove */ public void removeSocketNodeEventListener( final SocketNodeEventListener listener) { listenerList.remove(listener); } /** * Deserialize events from socket until interrupted. */ public void run() { LoggingEvent event; Logger remoteLogger; Exception listenerException = null; ObjectInputStream ois = null; try { ois = new ObjectInputStream( new BufferedInputStream(socket.getInputStream())); } catch (Exception e) { ois = null; listenerException = e; getLogger().error("Exception opening ObjectInputStream to " + socket, e); } if (ois != null) { String hostName = socket.getInetAddress().getHostName(); String remoteInfo = hostName + ":" + socket.getPort(); /** * notify the listener that the socket has been * opened and this SocketNode is ready and waiting */ fireSocketOpened(remoteInfo); try { while (!isClosed()) { // read an event from the wire event = (LoggingEvent) ois.readObject(); event.setProperty(Constants.HOSTNAME_KEY, hostName); // store the known remote info in an event property event.setProperty("log4j.remoteSourceInfo", remoteInfo); // if configured with a receiver, tell it to post the event if (!isPaused() && !isClosed()) { if ((receiver != null)) { receiver.doPost(event); // else post it via the hierarchy } else { // get a logger from the hierarchy. The name of the logger // is taken to be the name contained in the event. remoteLogger = repository.getLogger(event.getLoggerName()); //event.logger = remoteLogger; // apply the logger-level filter if (event .getLevel() .isGreaterOrEqual(remoteLogger.getEffectiveLevel())) { // finally log the event as if was generated locally remoteLogger.callAppenders(event); } } } else { //we simply discard this event. } } } catch (java.io.EOFException e) { getLogger().info("Caught java.io.EOFException closing connection."); listenerException = e; } catch (java.net.SocketException e) { getLogger().info("Caught java.net.SocketException closing connection."); listenerException = e; } catch (IOException e) { getLogger().info("Caught java.io.IOException: " + e); getLogger().info("Closing connection."); listenerException = e; } catch (Exception e) { getLogger().error("Unexpected exception. Closing connection.", e); listenerException = e; } } // close the socket try { if (ois != null) { ois.close(); } } catch (Exception e) { //getLogger().info("Could not close connection.", e); } // send event to listener, if configured if (listenerList.size() > 0 && !isClosed()) { fireSocketClosedEvent(listenerException); } } /** * Notifies all registered listeners regarding the closing of the Socket. * @param listenerException listener exception */ private void fireSocketClosedEvent(final Exception listenerException) { synchronized (listenerList) { for (Iterator iter = listenerList.iterator(); iter.hasNext();) { SocketNodeEventListener snel = (SocketNodeEventListener) iter.next(); if (snel != null) { snel.socketClosedEvent(listenerException); } } } } /** * Notifies all registered listeners regarding the opening of a Socket. * @param remoteInfo remote info */ private void fireSocketOpened(final String remoteInfo) { synchronized (listenerList) { for (Iterator iter = listenerList.iterator(); iter.hasNext();) { SocketNodeEventListener snel = (SocketNodeEventListener) iter.next(); if (snel != null) { snel.socketOpened(remoteInfo); } } } } /** * Sets if node is paused. * @param b new value */ public void setPaused(final boolean b) { this.paused = b; } /** * Get if node is paused. * @return true if pause. */ public boolean isPaused() { return this.paused; } /** * Close the node and underlying socket */ public void close() throws IOException { getLogger().debug("closing socket"); this.closed = true; socket.close(); fireSocketClosedEvent(null); } /** * Get if node is closed. * @return true if closed. */ public boolean isClosed() { return this.closed; } } SocketNodeEventListener.java000066400000000000000000000027501252742764200333760ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/net/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.net; import java.util.EventListener; /** Interface used to listen for {@link org.apache.log4j.net.SocketNode} related events. Clients register an instance of the interface and the instance is called back when the various events occur. @author Mark Womack @author Paul Smith (psmith@apache.org) */ public interface SocketNodeEventListener extends EventListener { /** * Called when the SocketNode is created and begins awaiting data. * @param remoteInfo remote info */ void socketOpened(String remoteInfo); /** Called when the socket the node was given has been closed. @param e exception */ void socketClosedEvent(Exception e); } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/net/SocketReceiver.java000066400000000000000000000277011252742764200316270ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.net; import org.apache.log4j.component.plugins.Pauseable; import org.apache.log4j.component.plugins.Plugin; import org.apache.log4j.component.plugins.Receiver; import org.apache.log4j.net.ZeroConfSupport; import org.apache.log4j.spi.LoggerRepository; import org.apache.log4j.spi.LoggingEvent; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.*; /** SocketReceiver receives a remote logging event on a configured socket and "posts" it to a LoggerRepository as if the event was generated locally. This class is designed to receive events from the SocketAppender class (or classes that send compatible events).

Once the event has been "posted", it will be handled by the appenders currently configured in the LoggerRespository. @author Mark Womack @author Scott Deboy (sdeboy@apache.org) @author Paul Smith (psmith@apache.org) */ public class SocketReceiver extends Receiver implements Runnable, PortBased, Pauseable { /** * socket map. */ private Map socketMap = new HashMap(); /** * Paused. */ private boolean paused; /** * Thread. */ private Thread rThread; /** * Port. */ protected int port; /** * Server socket. */ private ServerSocket serverSocket; /** * Socket list. */ private Vector socketList = new Vector(); /** * The MulticastDNS zone advertised by a SocketReceiver */ public static final String ZONE = "_log4j_obj_tcpaccept_receiver.local."; /** * Listener. */ private SocketNodeEventListener listener = null; /** * Listeners. */ private List listenerList = Collections.synchronizedList(new ArrayList()); private boolean advertiseViaMulticastDNS; private ZeroConfSupport zeroConf; /** * Create new instance. */ public SocketReceiver() { super(); } /** * Create new instance. * @param p port */ public SocketReceiver(final int p) { super(); port = p; } /** * Create new instance. * @param p port * @param repo logger repository */ public SocketReceiver(final int p, final LoggerRepository repo) { super(); this.port = p; repository = repo; } public int getPort() { return port; } public void setPort(final int p) { port = p; } /** * Returns true if the receiver is the same class and they are * configured for the same properties, and super class also considers * them to be equivalent. This is used by PluginRegistry when determining * if the a similarly configured receiver is being started. * * @param testPlugin The plugin to test equivalency against. * @return boolean True if the testPlugin is equivalent to this plugin. */ public boolean isEquivalent(final Plugin testPlugin) { if ((testPlugin != null) && testPlugin instanceof SocketReceiver) { SocketReceiver sReceiver = (SocketReceiver) testPlugin; return (port == sReceiver.getPort() && super.isEquivalent(testPlugin)); } return false; } /** Starts the SocketReceiver with the current options. */ public void activateOptions() { if (!isActive()) { // shutdown(); rThread = new Thread(this); rThread.setDaemon(true); rThread.start(); if (advertiseViaMulticastDNS) { zeroConf = new ZeroConfSupport(ZONE, port, getName()); zeroConf.advertise(); } active = true; } } /** * Called when the receiver should be stopped. Closes the * server socket and all of the open sockets. */ public synchronized void shutdown() { getLogger().debug(getName() + " received shutdown request"); // mark this as no longer running active = false; if (rThread != null) { rThread.interrupt(); rThread = null; } if (advertiseViaMulticastDNS) { zeroConf.unadvertise(); } doShutdown(); } /** * Does the actual shutting down by closing the server socket * and any connected sockets that have been created. */ private synchronized void doShutdown() { active = false; getLogger().debug(getName() + " doShutdown called"); // close the server socket closeServerSocket(); // close all of the accepted sockets closeAllAcceptedSockets(); } /** * Closes the server socket, if created. */ private void closeServerSocket() { getLogger().debug("{} closing server socket", getName()); try { if (serverSocket != null) { serverSocket.close(); } } catch (Exception e) { // ignore for now } serverSocket = null; } /** * Closes all the connected sockets in the List. */ private synchronized void closeAllAcceptedSockets() { for (int x = 0; x < socketList.size(); x++) { try { ((Socket) socketList.get(x)).close(); } catch (Exception e) { // ignore for now } } // clear member variables socketMap.clear(); socketList.clear(); } /** Sets the flag to indicate if receiver is active or not. @param b new value */ protected synchronized void setActive(final boolean b) { active = b; } public void setAdvertiseViaMulticastDNS(boolean advertiseViaMulticastDNS) { this.advertiseViaMulticastDNS = advertiseViaMulticastDNS; } public boolean isAdvertiseViaMulticastDNS() { return advertiseViaMulticastDNS; } /** Loop, accepting new socket connections. */ public void run() { /** * Ensure we start fresh. */ closeServerSocket(); closeAllAcceptedSockets(); // start the server socket try { serverSocket = new ServerSocket(port); } catch (Exception e) { getLogger().error( "error starting SocketReceiver (" + this.getName() + "), receiver did not start", e); active = false; return; } Socket socket = null; try { getLogger().debug("in run-about to enter while not interrupted loop"); active = true; while (!rThread.isInterrupted()) { // if we have a socket, start watching it if (socket != null) { getLogger().debug( "socket not null - creating and starting socketnode"); socketList.add(socket); SocketNode13 node = new SocketNode13(socket, this); synchronized (listenerList) { for (Iterator iter = listenerList.iterator(); iter.hasNext();) { SocketNodeEventListener l = (SocketNodeEventListener) iter.next(); node.addSocketNodeEventListener(l); } } socketMap.put(socket, node); new Thread(node).start(); socket = null; } getLogger().debug("waiting to accept socket"); // wait for a socket to open, then loop to start it socket = serverSocket.accept(); getLogger().debug("accepted socket"); } } catch (Exception e) { getLogger().warn( "exception while watching socket server in SocketReceiver (" + this.getName() + "), stopping"); } getLogger().debug("{} has exited the not interrupted loop", getName()); // socket not watched because we a no longer running // so close it now. if (socket != null) { try { socket.close(); } catch (IOException e1) { getLogger().warn("socket exception caught - socket closed"); } } getLogger().debug("{} is exiting main run loop", getName()); } /** * Returns a Vector of SocketDetail representing the IP/Domain name * of the currently connected sockets that this receiver has * been responsible for creating. * @return Vector of SocketDetails */ public Vector getConnectedSocketDetails() { Vector details = new Vector(socketList.size()); for (Enumeration enumeration = socketList.elements(); enumeration.hasMoreElements(); ) { Socket socket = (Socket) enumeration.nextElement(); details.add( new SocketDetail(socket, (SocketNode13) socketMap.get(socket))); } return details; } /** * Returns the currently configured SocketNodeEventListener that * will be automatically set for each SocketNode created. * @return SocketNodeEventListener currently configured * * @deprecated This receiver now supports multiple listeners */ public SocketNodeEventListener getListener() { return listener; } /** * Adds the listener to the list of listeners to be notified of the * respective event. * @param l the listener to add to the list */ public void addSocketNodeEventListener( final SocketNodeEventListener l) { listenerList.add(l); } /** * Removes the registered Listener from this instances list of * listeners. If the listener has not been registered, then invoking * this method has no effect. * * @param l the SocketNodeEventListener to remove */ public void removeSocketNodeEventListener( final SocketNodeEventListener l) { listenerList.remove(l); } /** * Sets the SocketNodeEventListener that will be used for each * created SocketNode. * @param l the listener to set on each creation of a SocketNode * @deprecated This receiver now supports multiple listeners and * so this method simply removes the listener (if there already) * and readds it to the list. * * The passed listener will also be returned via the getListener() * method still, but this is also deprecated */ public void setListener(final SocketNodeEventListener l) { removeSocketNodeEventListener(l); addSocketNodeEventListener(l); this.listener = l; } /** {@inheritDoc} */ public boolean isPaused() { return paused; } /** {@inheritDoc} */ public void setPaused(final boolean b) { paused = b; } /** * Socket detail. */ private static final class SocketDetail implements AddressBased, PortBased, Pauseable { /** * Address. */ private String address; /** * Port. */ private int port; /** * Socket node. */ private SocketNode13 socketNode; /** * Create new instance. * @param socket socket * @param node socket node */ private SocketDetail(final Socket socket, final SocketNode13 node) { super(); this.address = socket.getInetAddress().getHostName(); this.port = socket.getPort(); this.socketNode = node; } /** {@inheritDoc} */ public String getAddress() { return address; } /** {@inheritDoc} */ public int getPort() { return port; } /** {@inheritDoc} */ public String getName() { return "Socket"; } /** {@inheritDoc} */ public boolean isActive() { return true; } /** {@inheritDoc} */ public boolean isPaused() { return socketNode.isPaused(); } /** {@inheritDoc} */ public void setPaused(final boolean b) { socketNode.setPaused(b); } } /** {@inheritDoc} */ public void doPost(final LoggingEvent event) { if (!isPaused()) { super.doPost(event); } } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/net/UDPAppender.java000066400000000000000000000211341252742764200310130ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.net; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.component.helpers.Constants; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.net.ZeroConfSupport; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.xml.XMLLayout; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.UnknownHostException; /** * Sends log information as a UDP datagrams. * *

The UDPAppender is meant to be used as a diagnostic logging tool * so that logging can be monitored by a simple UDP client. * *

Messages are not sent as LoggingEvent objects but as text after * applying the designated Layout. * *

The port and remoteHost properties can be set in configuration properties. * By setting the remoteHost to a broadcast address any number of clients can * listen for log messages. * *

This was inspired and really extended/copied from {@link org.apache.log4j.net.SocketAppender}. * Please see the docs for the proper credit to the authors of that class. * * @author Kevin Brown * @author Scott Deboy */ public class UDPAppender extends AppenderSkeleton implements PortBased{ /** * The default port number for the UDP packets, 9991. */ public static final int DEFAULT_PORT = 9991; /** We remember host name as String in addition to the resolved InetAddress so that it can be returned via getOption(). */ String hostname; String remoteHost; String application; String encoding; InetAddress address; int port = DEFAULT_PORT; DatagramSocket outSocket; /** * The MulticastDNS zone advertised by a UDPAppender */ public static final String ZONE = "_log4j_xml_udp_appender.local."; // if there is something irrecoverably wrong with the settings, there is no // point in sending out packeets. boolean inError = false; private boolean advertiseViaMulticastDNS; private ZeroConfSupport zeroConf; public UDPAppender() { super(false); } /** Sends UDP packets to the address and port. */ public UDPAppender(final InetAddress address, final int port) { super(false); this.address = address; this.remoteHost = address.getHostName(); this.port = port; activateOptions(); } /** Sends UDP packets to the address and port. */ public UDPAppender(final String host, final int port) { super(false); this.port = port; this.address = getAddressByName(host); this.remoteHost = host; activateOptions(); } /** Open the UDP sender for the RemoteHost and Port. */ public void activateOptions() { try { hostname = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException uhe) { try { hostname = InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException uhe2) { hostname = "unknown"; } } //allow system property of application to be primary if (application == null) { application = System.getProperty(Constants.APPLICATION_KEY); } else { if (System.getProperty(Constants.APPLICATION_KEY) != null) { application = application + "-" + System.getProperty(Constants.APPLICATION_KEY); } } if(remoteHost != null) { address = getAddressByName(remoteHost); connect(address, port); } else { String err = "The RemoteHost property is required for SocketAppender named "+ name; LogLog.error(err); throw new IllegalStateException(err); } if (layout == null) { layout = new XMLLayout(); } if (advertiseViaMulticastDNS) { zeroConf = new ZeroConfSupport(ZONE, port, getName()); zeroConf.advertise(); } super.activateOptions(); } /** Close this appender.

This will mark the appender as closed and call then {@link #cleanUp} method. */ public synchronized void close() { if (closed) { return; } if (advertiseViaMulticastDNS) { zeroConf.unadvertise(); } this.closed = true; cleanUp(); } /** Close the UDP Socket and release the underlying connector thread if it has been created */ public void cleanUp() { if (outSocket != null) { try { outSocket.close(); } catch (Exception e) { LogLog.error("Could not close outSocket.", e); } outSocket = null; } } void connect(InetAddress address, int port) { if (this.address == null) { return; } try { // First, close the previous connection if any. cleanUp(); outSocket = new DatagramSocket(); outSocket.connect(address, port); } catch (IOException e) { LogLog.error( "Could not open UDP Socket for sending.", e); inError = true; } } public void append(LoggingEvent event) { if(inError) { return; } if (event == null) { return; } if (address == null) { return; } if (outSocket != null) { event.setProperty(Constants.HOSTNAME_KEY, hostname); if (application != null) { event.setProperty(Constants.APPLICATION_KEY, application); } try { StringBuffer buf = new StringBuffer(layout.format(event)); byte[] payload; if(encoding == null) { payload = buf.toString().getBytes(); } else { payload = buf.toString().getBytes(encoding); } DatagramPacket dp = new DatagramPacket(payload, payload.length, address, port); outSocket.send(dp); } catch (IOException e) { outSocket = null; LogLog.warn("Detected problem with UDP connection: " + e); } } } public boolean isActive() { return !inError; } InetAddress getAddressByName(String host) { try { return InetAddress.getByName(host); } catch (Exception e) { LogLog.error("Could not find address of [" + host + "].", e); return null; } } /** The UDPAppender uses layouts. Hence, this method returns true. */ public boolean requiresLayout() { return true; } /** The RemoteHost option takes a string value which should be the host name or ipaddress to send the UDP packets. */ public void setRemoteHost(String host) { remoteHost = host; } /** Returns value of the RemoteHost option. */ public String getRemoteHost() { return remoteHost; } /** The App option takes a string value which should be the name of the application getting logged. If property was already set (via system property), don't set here. */ public void setApplication(String app) { this.application = app; } /** Returns value of the App option. */ public String getApplication() { return application; } /** The Encoding option specifies how the bytes are encoded. If this option is not specified, the System encoding is used. */ public void setEncoding(String encoding) { this.encoding = encoding; } /** Returns value of the Encoding option. */ public String getEncoding() { return encoding; } /** The Port option takes a positive integer representing the port where UDP packets will be sent. */ public void setPort(int port) { this.port = port; } /** Returns value of the Port option. */ public int getPort() { return port; } public void setAdvertiseViaMulticastDNS(boolean advertiseViaMulticastDNS) { this.advertiseViaMulticastDNS = advertiseViaMulticastDNS; } public boolean isAdvertiseViaMulticastDNS() { return advertiseViaMulticastDNS; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/net/UDPReceiver.java000066400000000000000000000164571252742764200310350ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.net; import org.apache.log4j.component.plugins.Pauseable; import org.apache.log4j.component.plugins.Receiver; import org.apache.log4j.net.ZeroConfSupport; import org.apache.log4j.receivers.spi.Decoder; import org.apache.log4j.spi.LoggingEvent; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Receive LoggingEvents encoded with an XMLLayout, convert the XML data to a * LoggingEvent and post the LoggingEvent. * * @author Scott Deboy * */ public class UDPReceiver extends Receiver implements PortBased, Pauseable { private static final int PACKET_LENGTH = 16384; private UDPReceiverThread receiverThread; private String encoding; //default to log4j xml decoder private String decoder = "org.apache.log4j.xml.XMLDecoder"; private Decoder decoderImpl; protected boolean paused; private transient boolean closed = false; private int port; private DatagramSocket socket; UDPHandlerThread handlerThread; private boolean advertiseViaMulticastDNS; private ZeroConfSupport zeroConf; /** * The MulticastDNS zone advertised by a UDPReceiver */ public static final String ZONE = "_log4j_xml_udp_receiver.local."; public int getPort() { return port; } public void setPort(int port) { this.port = port; } /** * The Encoding option specifies how the bytes are encoded. If this * option is not specified, the system encoding will be used. * */ public void setEncoding(String encoding) { this.encoding = encoding; } /** * Returns value of the Encoding option. */ public String getEncoding() { return encoding; } public String getDecoder() { return decoder; } public void setDecoder(String decoder) { this.decoder = decoder; } public boolean isPaused() { return paused; } public void setPaused(boolean b) { paused = b; } public void setAdvertiseViaMulticastDNS(boolean advertiseViaMulticastDNS) { this.advertiseViaMulticastDNS = advertiseViaMulticastDNS; } public boolean isAdvertiseViaMulticastDNS() { return advertiseViaMulticastDNS; } public synchronized void shutdown() { if(closed == true) { return; } closed = true; active = false; // Closing the datagram socket will unblock the UDPReceiverThread if it is // was waiting to receive data from the socket. if (socket != null) { socket.close(); } if (advertiseViaMulticastDNS) { zeroConf.unadvertise(); } try { if(handlerThread != null) { handlerThread.close(); handlerThread.join(); } if(receiverThread != null) { receiverThread.join(); } } catch(InterruptedException ie) { } } /** Returns true if this receiver is active. */ // public synchronized boolean isActive() { // return isActive; //} public void activateOptions() { try { Class c = Class.forName(decoder); Object o = c.newInstance(); if (o instanceof Decoder) { this.decoderImpl = (Decoder) o; } } catch (ClassNotFoundException cnfe) { getLogger().warn("Unable to find decoder", cnfe); } catch (IllegalAccessException iae) { getLogger().warn("Could not construct decoder", iae); } catch (InstantiationException ie) { getLogger().warn("Could not construct decoder", ie); } try { socket = new DatagramSocket(port); receiverThread = new UDPReceiverThread(); receiverThread.start(); handlerThread = new UDPHandlerThread(); handlerThread.start(); if (advertiseViaMulticastDNS) { zeroConf = new ZeroConfSupport(ZONE, port, getName()); zeroConf.advertise(); } active = true; } catch (IOException ioe) { ioe.printStackTrace(); } } class UDPHandlerThread extends Thread { private List list = new ArrayList(); public UDPHandlerThread() { setDaemon(true); } public void append(String data) { synchronized (list) { list.add(data); list.notify(); } } /** * Allow the UDPHandlerThread to wakeup and exit gracefully. */ void close() { synchronized(list) { list.notify(); } } public void run() { ArrayList list2 = new ArrayList(); while (!UDPReceiver.this.closed) { synchronized (list) { try { while (!UDPReceiver.this.closed && list.size() == 0) { list.wait(300); } if (list.size() > 0) { list2.addAll(list); list.clear(); } } catch (InterruptedException ie) { } } if (list2.size() > 0) { Iterator iter = list2.iterator(); while (iter.hasNext()) { String data = (String) iter.next(); List v = decoderImpl.decodeEvents(data); if (v != null) { Iterator eventIter = v.iterator(); while (eventIter.hasNext()) { if (!isPaused()) { doPost((LoggingEvent) eventIter.next()); } } } } list2.clear(); } else { try { synchronized (this) { wait(1000); } } catch (InterruptedException ie) { } } } // while getLogger().debug(UDPReceiver.this.getName()+ "'s handler thread is exiting"); } // run } // UDPHandlerThread class UDPReceiverThread extends Thread { public UDPReceiverThread() { setDaemon(true); } public void run() { byte[] b = new byte[PACKET_LENGTH]; DatagramPacket p = new DatagramPacket(b, b.length); while (!UDPReceiver.this.closed) { try { socket.receive(p); //this string constructor which accepts a charset throws an exception if it is //null if (encoding == null) { handlerThread.append( new String(p.getData(), 0, p.getLength())); } else { handlerThread.append( new String(p.getData(), 0, p.getLength(), encoding)); } } catch (SocketException se) { //disconnected } catch (IOException ioe) { ioe.printStackTrace(); } } //LogLog.debug(UDPReceiver.this.getName() + "'s thread is ending."); } } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/net/XMLSocketNode.java000066400000000000000000000151511252742764200313250ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.net; import org.apache.log4j.Logger; import org.apache.log4j.component.helpers.Constants; import org.apache.log4j.component.plugins.Receiver; import org.apache.log4j.component.spi.ComponentBase; import org.apache.log4j.receivers.spi.Decoder; import org.apache.log4j.spi.LoggerRepository; import org.apache.log4j.spi.LoggingEvent; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.util.Iterator; import java.util.List; /** Read {@link LoggingEvent} objects sent from a remote client using XML over Sockets (TCP). These logging events are logged according to local policy, as if they were generated locally.

For example, the socket node might decide to log events to a local file and also resent them to a second socket node. @author Scott Deboy ; @since 0.8.4 */ public class XMLSocketNode extends ComponentBase implements Runnable { Socket socket; Receiver receiver; Decoder decoder; SocketNodeEventListener listener; /** Constructor for socket and logger repository. */ public XMLSocketNode( String decoder, Socket socket, LoggerRepository hierarchy) { this.repository = hierarchy; try { Class c = Class.forName(decoder); Object o = c.newInstance(); if (o instanceof Decoder) { this.decoder = (Decoder) o; } } catch (ClassNotFoundException cnfe) { getLogger().warn("Unable to find decoder", cnfe); } catch (IllegalAccessException iae) { getLogger().warn("Unable to construct decoder", iae); } catch (InstantiationException ie) { getLogger().warn("Unable to construct decoder", ie); } this.socket = socket; } /** Constructor for socket and reciever. */ public XMLSocketNode(String decoder, Socket socket, Receiver receiver) { try { Class c = Class.forName(decoder); Object o = c.newInstance(); if (o instanceof Decoder) { this.decoder = (Decoder) o; } } catch (ClassNotFoundException cnfe) { getLogger().warn("Unable to find decoder", cnfe); } catch (IllegalAccessException iae) { getLogger().warn("Unable to construct decoder", iae); } catch (InstantiationException ie) { getLogger().warn("Unable to construct decoder", ie); } this.socket = socket; this.receiver = receiver; } /** Set the event listener on this node. */ public void setListener(SocketNodeEventListener _listener) { listener = _listener; } public void run() { Logger remoteLogger; Exception listenerException = null; InputStream is = null; if ((this.receiver == null) || (this.decoder == null)) { is = null; listenerException = new Exception( "No receiver or decoder provided. Cannot process xml socket events"); getLogger().error( "Exception constructing XML Socket Receiver", listenerException); } try { is = socket.getInputStream(); } catch (Exception e) { is = null; listenerException = e; getLogger().error("Exception opening ObjectInputStream to " + socket, e); } if (is != null) { String hostName = socket.getInetAddress().getHostName(); String remoteInfo = hostName + ":" + socket.getPort(); try { //read data from the socket //it's up to the individual decoder to handle incomplete event data while (true) { byte[] b = new byte[1024]; int length = is.read(b); if (length == -1) { getLogger().info( "no bytes read from stream - closing connection."); break; } List v = decoder.decodeEvents(new String(b, 0, length)); if (v != null) { Iterator iter = v.iterator(); while (iter.hasNext()) { LoggingEvent e = (LoggingEvent) iter.next(); e.setProperty(Constants.HOSTNAME_KEY, hostName); // store the known remote info in an event property e.setProperty("log4j.remoteSourceInfo", remoteInfo); // if configured with a receiver, tell it to post the event if (receiver != null) { receiver.doPost(e); // else post it via the hierarchy } else { // get a logger from the hierarchy. The name of the logger // is taken to be the name contained in the event. remoteLogger = repository.getLogger(e.getLoggerName()); //event.logger = remoteLogger; // apply the logger-level filter if ( e.getLevel().isGreaterOrEqual( remoteLogger.getEffectiveLevel())) { // finally log the event as if was generated locally remoteLogger.callAppenders(e); } } } } } } catch (java.io.EOFException e) { getLogger().info("Caught java.io.EOFException closing connection."); listenerException = e; } catch (java.net.SocketException e) { getLogger().info( "Caught java.net.SocketException closing connection."); listenerException = e; } catch (IOException e) { getLogger().info("Caught java.io.IOException: " + e); getLogger().info("Closing connection."); listenerException = e; } catch (Exception e) { getLogger().error("Unexpected exception. Closing connection.", e); listenerException = e; } } // close the socket try { if (is != null) { is.close(); } } catch (Exception e) { //logger.info("Could not close connection.", e); } // send event to listener, if configured if (listener != null) { listener.socketClosedEvent(listenerException); } } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/net/XMLSocketReceiver.java000066400000000000000000000213771252742764200322130ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.net; import org.apache.log4j.component.plugins.Pauseable; import org.apache.log4j.component.plugins.Plugin; import org.apache.log4j.component.plugins.Receiver; import org.apache.log4j.net.ZeroConfSupport; import org.apache.log4j.spi.LoggerRepository; import org.apache.log4j.spi.LoggingEvent; import java.net.ServerSocket; import java.net.Socket; import java.util.List; import java.util.Vector; /** XMLSocketReceiver receives a remote logging event via XML on a configured socket and "posts" it to a LoggerRepository as if the event were generated locally. This class is designed to receive events from the XMLSocketAppender class (or classes that send compatible events).

This receiver supports log files created using log4j's XMLLayout, as well as java.util.logging XMLFormatter (via the org.apache.log4j.spi.Decoder interface).

By default, log4j's XMLLayout is supported (no need to specify a decoder in that case).

To configure this receiver to support java.util.logging's XMLFormatter, specify a 'decoder' param of org.apache.log4j.xml.UtilLoggingXMLDecoder.

Once the event has been "posted", it will be handled by the appenders currently configured in the LoggerRespository. @author Mark Womack @author Scott Deboy */ public class XMLSocketReceiver extends Receiver implements Runnable, PortBased, Pauseable { private boolean paused; //default to log4j xml decoder protected String decoder = "org.apache.log4j.xml.XMLDecoder"; private ServerSocket serverSocket; private List socketList = new Vector(); private Thread rThread; public static final int DEFAULT_PORT = 4448; protected int port = DEFAULT_PORT; private boolean advertiseViaMulticastDNS; private ZeroConfSupport zeroConf; /** * The MulticastDNS zone advertised by an XMLSocketReceiver */ public static final String ZONE = "_log4j_xml_tcpaccept_receiver.local."; /* * Log4j doesn't provide an XMLSocketAppender, but the MulticastDNS zone that should be advertised by one is: * _log4j_xml_tcpconnect_appender.local. */ public XMLSocketReceiver() { } public XMLSocketReceiver(int _port) { port = _port; } public XMLSocketReceiver(int _port, LoggerRepository _repository) { port = _port; repository = _repository; } /** Get the port to receive logging events on. */ public int getPort() { return port; } /** Set the port to receive logging events on. */ public void setPort(int _port) { port = _port; } public String getDecoder() { return decoder; } /** *Specify the class name implementing org.apache.log4j.spi.Decoder that can process the file. */ public void setDecoder(String _decoder) { decoder = _decoder; } public boolean isPaused() { return paused; } public void setPaused(boolean b) { paused = b; } /** * Returns true if the receiver is the same class and they are * configured for the same properties, and super class also considers * them to be equivalent. This is used by PluginRegistry when determining * if the a similarly configured receiver is being started. * * @param testPlugin The plugin to test equivalency against. * @return boolean True if the testPlugin is equivalent to this plugin. */ public boolean isEquivalent(Plugin testPlugin) { if ((testPlugin != null) && testPlugin instanceof XMLSocketReceiver) { XMLSocketReceiver sReceiver = (XMLSocketReceiver) testPlugin; return (port == sReceiver.getPort() && super.isEquivalent(testPlugin)); } return false; } public int hashCode() { int result = 37 * (repository != null? repository.hashCode():0); result = result * 37 + port; return (result * 37 + (getName() != null? getName().hashCode():0)); } /** Sets the flag to indicate if receiver is active or not. @param b new value */ protected synchronized void setActive(final boolean b) { active = b; } /** Starts the SocketReceiver with the current options. */ public void activateOptions() { if (!isActive()) { rThread = new Thread(this); rThread.setDaemon(true); rThread.start(); if (advertiseViaMulticastDNS) { zeroConf = new ZeroConfSupport(ZONE, port, getName()); zeroConf.advertise(); } active = true; } } public void setAdvertiseViaMulticastDNS(boolean advertiseViaMulticastDNS) { this.advertiseViaMulticastDNS = advertiseViaMulticastDNS; } public boolean isAdvertiseViaMulticastDNS() { return advertiseViaMulticastDNS; } /** Called when the receiver should be stopped. Closes the server socket and all of the open sockets. */ public synchronized void shutdown() { // mark this as no longer running active = false; if (rThread != null) { rThread.interrupt(); rThread = null; } doShutdown(); } /** * Does the actual shutting down by closing the server socket * and any connected sockets that have been created. */ private synchronized void doShutdown() { active = false; getLogger().debug("{} doShutdown called", getName()); // close the server socket closeServerSocket(); // close all of the accepted sockets closeAllAcceptedSockets(); if (advertiseViaMulticastDNS) { zeroConf.unadvertise(); } } /** * Closes the server socket, if created. */ private void closeServerSocket() { getLogger().debug("{} closing server socket", getName()); try { if (serverSocket != null) { serverSocket.close(); } } catch (Exception e) { // ignore for now } serverSocket = null; } /** * Closes all the connected sockets in the List. */ private synchronized void closeAllAcceptedSockets() { for (int x = 0; x < socketList.size(); x++) { try { ((Socket) socketList.get(x)).close(); } catch (Exception e) { // ignore for now } } // clear member variables socketList.clear(); } /** Loop, accepting new socket connections. */ public void run() { /** * Ensure we start fresh. */ getLogger().debug("performing socket cleanup prior to entering loop for {}", name); closeServerSocket(); closeAllAcceptedSockets(); getLogger().debug("socket cleanup complete for {}", name); active = true; // start the server socket try { serverSocket = new ServerSocket(port); } catch (Exception e) { getLogger().error( "error starting SocketReceiver (" + this.getName() + "), receiver did not start", e); active = false; doShutdown(); return; } Socket socket = null; try { getLogger().debug("in run-about to enter while isactiveloop"); active = true; while (!rThread.isInterrupted()) { // if we have a socket, start watching it if (socket != null) { getLogger().debug("socket not null - creating and starting socketnode"); socketList.add(socket); XMLSocketNode node = new XMLSocketNode(decoder, socket, this); node.setLoggerRepository(this.repository); new Thread(node).start(); socket = null; } getLogger().debug("waiting to accept socket"); // wait for a socket to open, then loop to start it socket = serverSocket.accept(); getLogger().debug("accepted socket"); } // socket not watched because we a no longer running // so close it now. if (socket != null) { socket.close(); } } catch (Exception e) { getLogger().warn( "socket server disconnected, stopping"); } } /* (non-Javadoc) * @see org.apache.log4j.plugins.Receiver#doPost(org.apache.log4j.spi.LoggingEvent) */ public void doPost(LoggingEvent event) { if(!isPaused()){ super.doPost(event); } } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/rewrite/000077500000000000000000000000001252742764200267335ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/rewrite/MapRewritePolicy.java000066400000000000000000000063431252742764200330430ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.rewrite; import org.apache.log4j.Logger; import org.apache.log4j.spi.LoggingEvent; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * This policy rewrites events where the message of the * original event implementes java.util.Map. * All other events are passed through unmodified. * If the map contains a "message" entry, the value will be * used as the message for the rewritten event. The rewritten * event will have a property set that is the combination of the * original property set and the other members of the message map. * If both the original property set and the message map * contain the same entry, the value from the message map * will overwrite the original property set. * * The combination of the RewriteAppender and this policy * performs the same actions as the MapFilter from log4j 1.3. */ public class MapRewritePolicy implements RewritePolicy { /** * {@inheritDoc} */ public LoggingEvent rewrite(final LoggingEvent source) { Object msg = source.getMessage(); if (msg instanceof Map) { Map props = new HashMap(source.getProperties()); Map eventProps = (Map) msg; // // if the map sent in the logging request // has "message" entry, use that as the message body // otherwise, use the entire map. // Object newMsg = eventProps.get("message"); if (newMsg == null) { newMsg = msg; } for(Iterator iter = eventProps.entrySet().iterator(); iter.hasNext(); ) { Map.Entry entry = (Map.Entry) iter.next(); if (!("message".equals(entry.getKey()))) { props.put(entry.getKey(), entry.getValue()); } } return new LoggingEvent( source.getFQNOfLoggerClass(), source.getLogger() != null ? source.getLogger(): Logger.getLogger(source.getLoggerName()), source.getTimeStamp(), source.getLevel(), newMsg, source.getThreadName(), source.getThrowableInformation(), source.getNDC(), source.getLocationInformation(), props); } else { return source; } } } PropertyRewritePolicy.java000066400000000000000000000061301252742764200340650ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/rewrite/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.rewrite; import org.apache.log4j.Logger; import org.apache.log4j.spi.LoggingEvent; import java.util.*; /** * This policy rewrites events by adding * a user-specified list of properties to the event. * Existing properties are not modified. * * The combination of the RewriteAppender and this policy * performs the same actions as the PropertyFilter from log4j 1.3. */ public class PropertyRewritePolicy implements RewritePolicy { private Map properties = Collections.EMPTY_MAP; public PropertyRewritePolicy() { } /** * Set a string representing the property name/value pairs. * * Form: propname1=propvalue1,propname2=propvalue2 * * @param props */ public void setProperties(String props) { Map hashTable = new HashMap(); StringTokenizer pairs = new StringTokenizer(props, ","); while (pairs.hasMoreTokens()) { StringTokenizer entry = new StringTokenizer(pairs.nextToken(), "="); hashTable.put(entry.nextElement().toString().trim(), entry.nextElement().toString().trim()); } synchronized(this) { properties = hashTable; } } /** * {@inheritDoc} */ public LoggingEvent rewrite(final LoggingEvent source) { if (!properties.isEmpty()) { Map rewriteProps = new HashMap(source.getProperties()); for(Iterator iter = properties.entrySet().iterator(); iter.hasNext(); ) { Map.Entry entry = (Map.Entry) iter.next(); if (!rewriteProps.containsKey(entry.getKey())) { rewriteProps.put(entry.getKey(), entry.getValue()); } } return new LoggingEvent( source.getFQNOfLoggerClass(), source.getLogger() != null ? source.getLogger(): Logger.getLogger(source.getLoggerName()), source.getTimeStamp(), source.getLevel(), source.getMessage(), source.getThreadName(), source.getThrowableInformation(), source.getNDC(), source.getLocationInformation(), rewriteProps); } return source; } } ReflectionRewritePolicy.java000066400000000000000000000072771252742764200343500ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/rewrite/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.rewrite; import org.apache.log4j.Logger; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.spi.LoggingEvent; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.util.HashMap; import java.util.Map; /** * This policy rewrites events by evaluating any * JavaBean properties on the message object and adding them * to the event properties. If the message object has a * message property, the value of that property will be * used as the message for the rewritten event and will * not be added to the event properties. Values from the * JavaBean properties will replace any existing property * with the same name. * * The combination of the RewriteAppender and this policy * performs the same actions as the ReflectionFilter from log4j 1.3. */ public class ReflectionRewritePolicy implements RewritePolicy { /** * {@inheritDoc} */ public LoggingEvent rewrite(final LoggingEvent source) { Object msg = source.getMessage(); if (!(msg instanceof String)) { Object newMsg = msg; Map rewriteProps = new HashMap(source.getProperties()); try { PropertyDescriptor[] props = Introspector.getBeanInfo( msg.getClass(), Object.class).getPropertyDescriptors(); if (props.length > 0) { for (int i=0;iAsyncAppender by interrupting the dispatcher * thread which will process all pending events before exiting. */ public void close() { closed = true; // // close all attached appenders. // synchronized (appenders) { Enumeration iter = appenders.getAllAppenders(); if (iter != null) { while (iter.hasMoreElements()) { Object next = iter.nextElement(); if (next instanceof Appender) { ((Appender) next).close(); } } } } } /** * Determines if specified appender is attached. * @param appender appender. * @return true if attached. */ public boolean isAttached(final Appender appender) { synchronized (appenders) { return appenders.isAttached(appender); } } /** * {@inheritDoc} */ public boolean requiresLayout() { return false; } /** * Removes and closes all attached appenders. */ public void removeAllAppenders() { synchronized (appenders) { appenders.removeAllAppenders(); } } /** * Removes an appender. * @param appender appender to remove. */ public void removeAppender(final Appender appender) { synchronized (appenders) { appenders.removeAppender(appender); } } /** * Remove appender by name. * @param name name. */ public void removeAppender(final String name) { synchronized (appenders) { appenders.removeAppender(name); } } public void setRewritePolicy(final RewritePolicy rewritePolicy) { policy = rewritePolicy; } /** * {@inheritDoc} */ public boolean parseUnrecognizedElement(final Element element, final Properties props) throws Exception { final String nodeName = element.getNodeName(); if ("rewritePolicy".equals(nodeName)) { Object rewritePolicy = org.apache.log4j.xml.DOMConfigurator.parseElement( element, props, RewritePolicy.class); if (rewritePolicy != null) { if (rewritePolicy instanceof OptionHandler) { ((OptionHandler) rewritePolicy).activateOptions(); } this.setRewritePolicy((RewritePolicy) rewritePolicy); } return true; } return false; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/rewrite/RewritePolicy.java000066400000000000000000000026661252742764200324110ustar00rootroot00000000000000package org.apache.log4j.receivers.rewrite; import org.apache.log4j.spi.LoggingEvent; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ /** * This interface is implemented to provide a rewrite * strategy for RewriteAppender. RewriteAppender will * call the rewrite method with a source logging event. * The strategy may return that event, create a new event * or return null to suppress the logging request. */ public interface RewritePolicy { /** * Rewrite a logging event. * @param source a logging event that may be returned or * used to create a new logging event. * @return a logging event or null to suppress processing. */ LoggingEvent rewrite(final LoggingEvent source); } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/spi/000077500000000000000000000000001252742764200260455ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/spi/Decoder.java000066400000000000000000000036111252742764200302560ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.spi; import org.apache.log4j.spi.LoggingEvent; import java.io.IOException; import java.net.URL; import java.util.Map; import java.util.Vector; /** * Allow LoggingEvents to be reconstructed from a different format * (usually XML). * * @author Scott Deboy (sdeboy@apache.org) */ public interface Decoder { /** * Decode events from document. * @param document document to decode. * @return list of LoggingEvent instances. */ Vector decodeEvents(String document); /** * Decode event from string. * @param event string representation of event * @return event */ LoggingEvent decode(String event); /** * Decode event from document retreived from URL. * @param url url of document * @return list of LoggingEvent instances. * @throws IOException if IO error resolving document. */ Vector decode(URL url) throws IOException; /** * Sets additional properties. * @param additionalProperties map of additional properties. */ void setAdditionalProperties(Map additionalProperties); } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/varia/000077500000000000000000000000001252742764200263545ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/varia/ListModelAppender.java000066400000000000000000000037151252742764200326000ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.varia; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.spi.LoggingEvent; import javax.swing.*; /** * A very basic appender that takes the events and stores them in to a * ListModel for late retrieval. * * * @author Paul Smith (psmith@apache.org) * */ public final class ListModelAppender extends AppenderSkeleton { /** * Default list model. */ private final DefaultListModel model = new DefaultListModel(); /** * Constructs a ListModelAppender. */ public ListModelAppender() { super(true); } /** * Returns a reference to the ListModel that contains all the LoggingEvents * that have been appended to this class. * * @return the list model */ public ListModel getModel() { return model; } /** {@inheritDoc} */ protected void append(final LoggingEvent event) { model.addElement(event); } /** {@inheritDoc} */ public void close() { clearModel(); } /** * Removes all the Events from the model. */ public void clearModel() { model.clear(); } /** {@inheritDoc} */ public boolean requiresLayout() { return false; } } LogFilePatternReceiver.java000066400000000000000000001053761252742764200335200ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/varia/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.varia; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.component.helpers.Constants; import org.apache.log4j.component.plugins.Receiver; import org.apache.log4j.rule.ExpressionRule; import org.apache.log4j.rule.Rule; import org.apache.log4j.spi.LocationInfo; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.ThrowableInformation; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.MatchResult; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /** * LogFilePatternReceiver can parse and tail log files, converting entries into * LoggingEvents. If the file doesn't exist when the receiver is initialized, the * receiver will look for the file once every 10 seconds. *

* This receiver relies on java.util.regex features to perform the parsing of text in the * log file, however the only regular expression field explicitly supported is * a glob-style wildcard used to ignore fields in the log file if needed. All other * fields are parsed by using the supplied keywords. *

* Features:
* - specify the URL of the log file to be processed
* - specify the timestamp format in the file (if one exists, using patterns from {@link java.text.SimpleDateFormat})
* - specify the pattern (logFormat) used in the log file using keywords, a wildcard character (*) and fixed text
* - 'tail' the file (allows the contents of the file to be continually read and new events processed)
* - supports the parsing of multi-line messages and exceptions * - 'hostname' property set to URL host (or 'file' if not available) * - 'application' property set to URL path (or value of fileURL if not available) *

* Keywords:
* TIMESTAMP
* LOGGER
* LEVEL
* THREAD
* CLASS
* FILE
* LINE
* METHOD
* RELATIVETIME
* MESSAGE
* NDC
* PROP(key)
*

* Use a * to ignore portions of the log format that should be ignored *

* Example:
* If your file's patternlayout is this:
* %d %-5p [%t] %C{2} (%F:%L) - %m%n *

* specify this as the log format:
* TIMESTAMP LEVEL [THREAD] CLASS (FILE:LINE) - MESSAGE *

* To define a PROPERTY field, use PROP(key) *

* Example:
* If you used the RELATIVETIME pattern layout character in the file, * you can use PROP(RELATIVETIME) in the logFormat definition to assign * the RELATIVETIME field as a property on the event. *

* If your file's patternlayout is this:
* %r [%t] %-5p %c %x - %m%n *

* specify this as the log format:
* PROP(RELATIVETIME) [THREAD] LEVEL LOGGER * - MESSAGE *

* Note the * - it can be used to ignore a single word or sequence of words in the log file * (in order for the wildcard to ignore a sequence of words, the text being ignored must be * followed by some delimiter, like '-' or '[') - ndc is being ignored in the following example. *

* Assign a filterExpression in order to only process events which match a filter. * If a filterExpression is not assigned, all events are processed. *

* Limitations:
* - no support for the single-line version of throwable supported by patternlayout
* (this version of throwable will be included as the last line of the message)
* - the relativetime patternLayout character must be set as a property: PROP(RELATIVETIME)
* - messages should appear as the last field of the logFormat because the variability in message content
* - exceptions are converted if the exception stack trace (other than the first line of the exception)
* is stored in the log file with a tab followed by the word 'at' as the first characters in the line
* - tailing may fail if the file rolls over. *

* Example receiver configuration settings (add these as params, specifying a LogFilePatternReceiver 'plugin'):
* param: "timestampFormat" value="yyyy-MM-d HH:mm:ss,SSS"
* param: "logFormat" value="PROP(RELATIVETIME) [THREAD] LEVEL LOGGER * - MESSAGE"
* param: "fileURL" value="file:///c:/events.log"
* param: "tailing" value="true" *

* This configuration will be able to process these sample events:
* 710 [ Thread-0] DEBUG first.logger first - something here something else
* 880 [ Thread-2] DEBUG first.logger third - something here something else
* 880 [ Thread-0] INFO first.logger first - infomsg-0
* java.lang.Exception: someexception-first
* at Generator2.run(Generator2.java:102)
* *@author Scott Deboy */ public class LogFilePatternReceiver extends Receiver { private final List keywords = new ArrayList(); private static final String PROP_START = "PROP("; private static final String PROP_END = ")"; private static final String LOGGER = "LOGGER"; private static final String MESSAGE = "MESSAGE"; private static final String TIMESTAMP = "TIMESTAMP"; private static final String NDC = "NDC"; private static final String LEVEL = "LEVEL"; private static final String THREAD = "THREAD"; private static final String CLASS = "CLASS"; private static final String FILE = "FILE"; private static final String LINE = "LINE"; private static final String METHOD = "METHOD"; private static final String DEFAULT_HOST = "file"; //all lines other than first line of exception begin with tab followed by 'at' followed by text private static final String EXCEPTION_PATTERN = "^\\s+at.*"; private static final String REGEXP_DEFAULT_WILDCARD = ".*?"; private static final String REGEXP_GREEDY_WILDCARD = ".*"; private static final String PATTERN_WILDCARD = "*"; private static final String NOSPACE_GROUP = "(\\S*\\s*?)"; private static final String DEFAULT_GROUP = "(" + REGEXP_DEFAULT_WILDCARD + ")"; private static final String GREEDY_GROUP = "(" + REGEXP_GREEDY_WILDCARD + ")"; private static final String MULTIPLE_SPACES_REGEXP = "[ ]+"; private final String newLine = System.getProperty("line.separator"); private final String[] emptyException = new String[] { "" }; private SimpleDateFormat dateFormat; private String timestampFormat = "yyyy-MM-d HH:mm:ss,SSS"; private String logFormat; private String customLevelDefinitions; private String fileURL; private String host; private String path; private boolean tailing; private String filterExpression; private long waitMillis = 2000; //default 2 seconds private static final String VALID_DATEFORMAT_CHARS = "GyMwWDdFEaHkKhmsSzZ"; private static final String VALID_DATEFORMAT_CHAR_PATTERN = "[" + VALID_DATEFORMAT_CHARS + "]"; private Rule expressionRule; private Map currentMap; private List additionalLines; private List matchingKeywords; private String regexp; private Reader reader; private Pattern regexpPattern; private Pattern exceptionPattern; private String timestampPatternText; private boolean useCurrentThread; public static final int MISSING_FILE_RETRY_MILLIS = 10000; private boolean appendNonMatches; private final Map customLevelDefinitionMap = new HashMap(); public LogFilePatternReceiver() { keywords.add(TIMESTAMP); keywords.add(LOGGER); keywords.add(LEVEL); keywords.add(THREAD); keywords.add(CLASS); keywords.add(FILE); keywords.add(LINE); keywords.add(METHOD); keywords.add(MESSAGE); keywords.add(NDC); try { exceptionPattern = Pattern.compile(EXCEPTION_PATTERN); } catch (PatternSyntaxException pse) { //shouldn't happen } } /** * Accessor * * @return file URL */ public String getFileURL() { return fileURL; } /** * Mutator * * @param fileURL */ public void setFileURL(String fileURL) { this.fileURL = fileURL; } /** * If the log file contains non-log4j level strings, they can be mapped to log4j levels using the format (android example): * V=TRACE,D=DEBUG,I=INFO,W=WARN,E=ERROR,F=FATAL,S=OFF * * @param customLevelDefinitions the level definition string */ public void setCustomLevelDefinitions(String customLevelDefinitions) { this.customLevelDefinitions = customLevelDefinitions; } public String getCustomLevelDefinitions() { return customLevelDefinitions; } /** * Accessor * @return append non matches */ public boolean isAppendNonMatches() { return appendNonMatches; } /** * Mutator * @param appendNonMatches */ public void setAppendNonMatches(boolean appendNonMatches) { this.appendNonMatches = appendNonMatches; } /** * Accessor * * @return filter expression */ public String getFilterExpression() { return filterExpression; } /** * Mutator * * @param filterExpression */ public void setFilterExpression(String filterExpression) { this.filterExpression = filterExpression; } /** * Accessor * * @return tailing */ public boolean isTailing() { return tailing; } /** * Mutator * * @param tailing */ public void setTailing(boolean tailing) { this.tailing = tailing; } /** * When true, this property uses the current Thread to perform the import, * otherwise when false (the default), a new Thread is created and started to manage * the import. * @return true, if the current thread is used */ public final boolean isUseCurrentThread() { return useCurrentThread; } /** * Sets whether the current Thread or a new Thread is created to perform the import, * the default being false (new Thread created). * * @param useCurrentThread */ public final void setUseCurrentThread(boolean useCurrentThread) { this.useCurrentThread = useCurrentThread; } /** * Accessor * * @return log format */ public String getLogFormat() { return logFormat; } /** * Mutator * * @param logFormat * the format */ public void setLogFormat(String logFormat) { this.logFormat = logFormat; } /** * Mutator. Specify a pattern from {@link java.text.SimpleDateFormat} * * @param timestampFormat */ public void setTimestampFormat(String timestampFormat) { this.timestampFormat = timestampFormat; } /** * Accessor * * @return timestamp format */ public String getTimestampFormat() { return timestampFormat; } /** * Accessor * @return millis between retrieves of content */ public long getWaitMillis() { return waitMillis; } /** * Mutator * @param waitMillis */ public void setWaitMillis(long waitMillis) { this.waitMillis = waitMillis; } /** * Walk the additionalLines list, looking for the EXCEPTION_PATTERN. *

* Return the index of the first matched line * (the match may be the 1st line of an exception) *

* Assumptions:
* - the additionalLines list may contain both message and exception lines
* - message lines are added to the additionalLines list and then * exception lines (all message lines occur in the list prior to all * exception lines) * * @return -1 if no exception line exists, line number otherwise */ private int getExceptionLine() { for (int i = 0; i < additionalLines.size(); i++) { Matcher exceptionMatcher = exceptionPattern.matcher((String)additionalLines.get(i)); if (exceptionMatcher.matches()) { return i; } } return -1; } /** * Combine all message lines occuring in the additionalLines list, adding * a newline character between each line *

* the event will already have a message - combine this message * with the message lines in the additionalLines list * (all entries prior to the exceptionLine index) * * @param firstMessageLine primary message line * @param exceptionLine index of first exception line * @return message */ private String buildMessage(String firstMessageLine, int exceptionLine) { if (additionalLines.size() == 0) { return firstMessageLine; } StringBuffer message = new StringBuffer(); if (firstMessageLine != null) { message.append(firstMessageLine); } int linesToProcess = (exceptionLine == -1?additionalLines.size(): exceptionLine); for (int i = 0; i < linesToProcess; i++) { message.append(newLine); message.append(additionalLines.get(i)); } return message.toString(); } /** * Combine all exception lines occuring in the additionalLines list into a * String array *

* (all entries equal to or greater than the exceptionLine index) * * @param exceptionLine index of first exception line * @return exception */ private String[] buildException(int exceptionLine) { if (exceptionLine == -1) { return emptyException; } String[] exception = new String[additionalLines.size() - exceptionLine - 1]; for (int i = 0; i < exception.length; i++) { exception[i] = (String) additionalLines.get(i + exceptionLine); } return exception; } /** * Construct a logging event from currentMap and additionalLines * (additionalLines contains multiple message lines and any exception lines) *

* CurrentMap and additionalLines are cleared in the process * * @return event */ private LoggingEvent buildEvent() { if (currentMap.size() == 0) { if (additionalLines.size() > 0) { for (Iterator iter = additionalLines.iterator();iter.hasNext();) { getLogger().info("found non-matching line: " + iter.next()); } } additionalLines.clear(); return null; } //the current map contains fields - build an event int exceptionLine = getExceptionLine(); String[] exception = buildException(exceptionLine); //messages are listed before exceptions in additionallines if (additionalLines.size() > 0 && exception.length > 0) { currentMap.put(MESSAGE, buildMessage((String) currentMap.get(MESSAGE), exceptionLine)); } LoggingEvent event = convertToEvent(currentMap, exception); currentMap.clear(); additionalLines.clear(); return event; } /** * Read, parse and optionally tail the log file, converting entries into logging events. * * A runtimeException is thrown if the logFormat pattern is malformed. * * @param bufferedReader * @throws IOException */ protected void process(BufferedReader bufferedReader) throws IOException { Matcher eventMatcher; Matcher exceptionMatcher; String line; while ((line = bufferedReader.readLine()) != null) { //skip empty line entries eventMatcher = regexpPattern.matcher(line); if (line.trim().equals("")) {continue;} exceptionMatcher = exceptionPattern.matcher(line); if (eventMatcher.matches()) { //build an event from the previous match (held in current map) LoggingEvent event = buildEvent(); if (event != null) { if (passesExpression(event)) { doPost(event); } } currentMap.putAll(processEvent(eventMatcher.toMatchResult())); } else if (exceptionMatcher.matches()) { //an exception line additionalLines.add(line); } else { //neither...either post an event with the line or append as additional lines //if this was a logging event with multiple lines, each line will show up as its own event instead of being //appended as multiple lines on the same event.. //choice is to have each non-matching line show up as its own line, or append them all to a previous event if (appendNonMatches) { //hold on to the previous time, so we can do our best to preserve time-based ordering if the event is a non-match String lastTime = (String)currentMap.get(TIMESTAMP); //build an event from the previous match (held in current map) if (currentMap.size() > 0) { LoggingEvent event = buildEvent(); if (event != null) { if (passesExpression(event)) { doPost(event); } } } if (lastTime != null) { currentMap.put(TIMESTAMP, lastTime); } currentMap.put(MESSAGE, line); } else { additionalLines.add(line); } } } //process last event if one exists LoggingEvent event = buildEvent(); if (event != null) { if (passesExpression(event)) { doPost(event); } } } protected void createPattern() { regexpPattern = Pattern.compile(regexp); } /** * Helper method that supports the evaluation of the expression * * @param event * @return true if expression isn't set, or the result of the evaluation otherwise */ private boolean passesExpression(LoggingEvent event) { if (event != null) { if (expressionRule != null) { return (expressionRule.evaluate(event, null)); } } return true; } /** * Convert the match into a map. *

* Relies on the fact that the matchingKeywords list is in the same * order as the groups in the regular expression * * @param result * @return map */ private Map processEvent(MatchResult result) { Map map = new HashMap(); //group zero is the entire match - process all other groups for (int i = 1; i < result.groupCount() + 1; i++) { Object key = matchingKeywords.get(i - 1); Object value = result.group(i); map.put(key, value); } return map; } /** * Helper method that will convert timestamp format to a pattern * * * @return string */ private String convertTimestamp() { //some locales (for example, French) generate timestamp text with characters not included in \w - // now using \S (all non-whitespace characters) instead of /w String result = timestampFormat.replaceAll(VALID_DATEFORMAT_CHAR_PATTERN + "+", "\\\\S+"); //make sure dots in timestamp are escaped result = result.replaceAll(Pattern.quote("."), "\\\\."); return result; } protected void setHost(String host) { this.host = host; } protected void setPath(String path) { this.path = path; } public String getPath() { return path; } /** * Build the regular expression needed to parse log entries * */ protected void initialize() { if (host == null && path == null) { try { URL url = new URL(fileURL); host = url.getHost(); path = url.getPath(); } catch (MalformedURLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } if (host == null || host.trim().equals("")) { host = DEFAULT_HOST; } if (path == null || path.trim().equals("")) { path = fileURL; } currentMap = new HashMap(); additionalLines = new ArrayList(); matchingKeywords = new ArrayList(); if (timestampFormat != null) { dateFormat = new SimpleDateFormat(quoteTimeStampChars(timestampFormat)); timestampPatternText = convertTimestamp(); } //if custom level definitions exist, parse them updateCustomLevelDefinitionMap(); try { if (filterExpression != null) { expressionRule = ExpressionRule.getRule(filterExpression); } } catch (Exception e) { getLogger().warn("Invalid filter expression: " + filterExpression, e); } List buildingKeywords = new ArrayList(); String newPattern = logFormat; int index = 0; String current = newPattern; //build a list of property names and temporarily replace the property with an empty string, //we'll rebuild the pattern later List propertyNames = new ArrayList(); while (index > -1) { if (current.indexOf(PROP_START) > -1 && current.indexOf(PROP_END) > -1) { index = current.indexOf(PROP_START); String longPropertyName = current.substring(current.indexOf(PROP_START), current.indexOf(PROP_END) + 1); String shortProp = getShortPropertyName(longPropertyName); buildingKeywords.add(shortProp); propertyNames.add(longPropertyName); current = current.substring(longPropertyName.length() + 1 + index); newPattern = singleReplace(newPattern, longPropertyName, new Integer(buildingKeywords.size() -1).toString()); } else { //no properties index = -1; } } /* * we're using a treemap, so the index will be used as the key to ensure * keywords are ordered correctly * * examine pattern, adding keywords to an index-based map patterns can * contain only one of these per entry...properties are the only 'keyword' * that can occur multiple times in an entry */ Iterator iter = keywords.iterator(); while (iter.hasNext()) { String keyword = (String) iter.next(); int index2 = newPattern.indexOf(keyword); if (index2 > -1) { buildingKeywords.add(keyword); newPattern = singleReplace(newPattern, keyword, new Integer(buildingKeywords.size() -1).toString()); } } String buildingInt = ""; for (int i=0;i 0 && !lastCharIsDateFormat) { result.append("'"); } lastCharIsDateFormat = thisCharIsDateFormat; result.append(thisVal); } //append an end single-quote if we ended with non-dateformat char if (!lastCharIsDateFormat) { result.append("'"); } return result.toString(); } private String singleReplace(String inputString, String oldString, String newString) { int propLength = oldString.length(); int startPos = inputString.indexOf(oldString); if (startPos == -1) { getLogger().info("string: " + oldString + " not found in input: " + inputString + " - returning input"); return inputString; } if (startPos == 0) { inputString = inputString.substring(propLength); inputString = newString + inputString; } else { inputString = inputString.substring(0, startPos) + newString + inputString.substring(startPos + propLength); } return inputString; } private String getShortPropertyName(String longPropertyName) { String currentProp = longPropertyName.substring(longPropertyName.indexOf(PROP_START)); String prop = currentProp.substring(0, currentProp.indexOf(PROP_END) + 1); String shortProp = prop.substring(PROP_START.length(), prop.length() - 1); return shortProp; } /** * Some perl5 characters may occur in the log file format. * Escape these characters to prevent parsing errors. * * @param input * @return string */ private String replaceMetaChars(String input) { //escape backslash first since that character is used to escape the remaining meta chars input = input.replaceAll("\\\\", "\\\\\\"); //don't escape star - it's used as the wildcard input = input.replaceAll(Pattern.quote("]"), "\\\\]"); input = input.replaceAll(Pattern.quote("["), "\\\\["); input = input.replaceAll(Pattern.quote("^"), "\\\\^"); input = input.replaceAll(Pattern.quote("$"), "\\\\$"); input = input.replaceAll(Pattern.quote("."), "\\\\."); input = input.replaceAll(Pattern.quote("|"), "\\\\|"); input = input.replaceAll(Pattern.quote("?"), "\\\\?"); input = input.replaceAll(Pattern.quote("+"), "\\\\+"); input = input.replaceAll(Pattern.quote("("), "\\\\("); input = input.replaceAll(Pattern.quote(")"), "\\\\)"); input = input.replaceAll(Pattern.quote("-"), "\\\\-"); input = input.replaceAll(Pattern.quote("{"), "\\\\{"); input = input.replaceAll(Pattern.quote("}"), "\\\\}"); input = input.replaceAll(Pattern.quote("#"), "\\\\#"); return input; } /** * Convert a keyword-to-values map to a LoggingEvent * * @param fieldMap * @param exception * * @return logging event */ private LoggingEvent convertToEvent(Map fieldMap, String[] exception) { if (fieldMap == null) { return null; } //a logger must exist at a minimum for the event to be processed if (!fieldMap.containsKey(LOGGER)) { fieldMap.put(LOGGER, "Unknown"); } if (exception == null) { exception = emptyException; } Logger logger = null; long timeStamp = 0L; String level = null; String threadName = null; Object message = null; String ndc = null; String className = null; String methodName = null; String eventFileName = null; String lineNumber = null; Hashtable properties = new Hashtable(); logger = Logger.getLogger((String) fieldMap.remove(LOGGER)); if ((dateFormat != null) && fieldMap.containsKey(TIMESTAMP)) { try { timeStamp = dateFormat.parse((String) fieldMap.remove(TIMESTAMP)) .getTime(); } catch (Exception e) { e.printStackTrace(); } } //use current time if timestamp not parseable if (timeStamp == 0L) { timeStamp = System.currentTimeMillis(); } message = fieldMap.remove(MESSAGE); if (message == null) { message = ""; } level = (String) fieldMap.remove(LEVEL); Level levelImpl; if (level == null) { levelImpl = Level.DEBUG; } else { //first try to resolve against custom level definition map, then fall back to regular levels levelImpl = (Level) customLevelDefinitionMap.get(level); if (levelImpl == null) { levelImpl = Level.toLevel(level.trim()); if (!level.equals(levelImpl.toString())) { //check custom level map if (levelImpl == null) { levelImpl = Level.DEBUG; getLogger().debug("found unexpected level: " + level + ", logger: " + logger.getName() + ", msg: " + message); //make sure the text that couldn't match a level is added to the message message = level + " " + message; } } } } threadName = (String) fieldMap.remove(THREAD); ndc = (String) fieldMap.remove(NDC); className = (String) fieldMap.remove(CLASS); methodName = (String) fieldMap.remove(METHOD); eventFileName = (String) fieldMap.remove(FILE); lineNumber = (String) fieldMap.remove(LINE); properties.put(Constants.HOSTNAME_KEY, host); properties.put(Constants.APPLICATION_KEY, path); properties.put(Constants.RECEIVER_NAME_KEY, getName()); //all remaining entries in fieldmap are properties properties.putAll(fieldMap); LocationInfo info = null; if ((eventFileName != null) || (className != null) || (methodName != null) || (lineNumber != null)) { info = new LocationInfo(eventFileName, className, methodName, lineNumber); } else { info = LocationInfo.NA_LOCATION_INFO; } LoggingEvent event = new LoggingEvent(null, logger, timeStamp, levelImpl, message, threadName, new ThrowableInformation(exception), ndc, info, properties); return event; } // public static void main(String[] args) { // org.apache.log4j.Logger rootLogger = org.apache.log4j.Logger.getRootLogger(); // org.apache.log4j.ConsoleAppender appender = new org.apache.log4j.ConsoleAppender(new org.apache.log4j.SimpleLayout()); // appender.setName("console"); // rootLogger.addAppender(appender); // LogFilePatternReceiver test = new LogFilePatternReceiver(); // org.apache.log4j.spi.LoggerRepository repo = new org.apache.log4j.LoggerRepositoryExImpl(org.apache.log4j.LogManager.getLoggerRepository()); // test.setLoggerRepository(repo); // test.setLogFormat("PROP(RELATIVETIME) [THREAD] LEVEL LOGGER * - MESSAGE"); // test.setTailing(false); // test.setAppendNonMatches(true); // test.setTimestampFormat("yyyy-MM-d HH:mm:ss,SSS"); // test.setFileURL("file:///C:/log/test.log"); // test.initialize(); // test.activateOptions(); // } /** * Close the reader. */ public void shutdown() { getLogger().info(getPath() + " shutdown"); active = false; try { if (reader != null) { reader.close(); reader = null; } } catch (IOException ioe) { ioe.printStackTrace(); } } /** * Read and process the log file. */ public void activateOptions() { getLogger().info("activateOptions"); active = true; Runnable runnable = new Runnable() { public void run() { initialize(); while (reader == null) { getLogger().info("attempting to load file: " + getFileURL()); try { reader = new InputStreamReader(new URL(getFileURL()).openStream()); } catch (FileNotFoundException fnfe) { getLogger().info("file not available - will try again"); synchronized (this) { try { wait(MISSING_FILE_RETRY_MILLIS); } catch (InterruptedException ie) {} } } catch (IOException ioe) { getLogger().warn("unable to load file", ioe); return; } } try { BufferedReader bufferedReader = new BufferedReader(reader); createPattern(); do { process(bufferedReader); try { synchronized (this) { wait(waitMillis); } } catch (InterruptedException ie) {} if (tailing) { getLogger().debug("tailing file"); } } while (tailing); } catch (IOException ioe) { //io exception - probably shut down getLogger().info("stream closed"); } getLogger().debug("processing " + path + " complete"); shutdown(); } }; if(useCurrentThread) { runnable.run(); }else { new Thread(runnable, "LogFilePatternReceiver-"+getName()).start(); } } } LogFilePatternReceiverBeanInfo.java000066400000000000000000000041161252742764200351100ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/varia/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.varia; import java.beans.PropertyDescriptor; import java.beans.SimpleBeanInfo; /** * BeanInfo class for the meta-data of the LogFilePatternReceiver. * */ public class LogFilePatternReceiverBeanInfo extends SimpleBeanInfo { /* (non-Javadoc) * @see java.beans.BeanInfo#getPropertyDescriptors() */ public PropertyDescriptor[] getPropertyDescriptors() { try { return new PropertyDescriptor[] { new PropertyDescriptor("fileURL", LogFilePatternReceiver.class), new PropertyDescriptor( "timestampFormat", LogFilePatternReceiver.class), new PropertyDescriptor("logFormat", LogFilePatternReceiver.class), new PropertyDescriptor("name", LogFilePatternReceiver.class), new PropertyDescriptor("tailing", LogFilePatternReceiver.class), new PropertyDescriptor( "filterExpression", LogFilePatternReceiver.class), new PropertyDescriptor("waitMillis", LogFilePatternReceiver.class), new PropertyDescriptor("appendNonMatches", LogFilePatternReceiver.class), new PropertyDescriptor("customLevelDefinitions", LogFilePatternReceiver.class), new PropertyDescriptor("useCurrentThread", LogFilePatternReceiver.class), }; } catch (Exception e) { } return null; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/xml/000077500000000000000000000000001252742764200260525ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/xml/LogFileXMLReceiver.java000066400000000000000000000236101252742764200323060ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.xml; import org.apache.log4j.component.helpers.Constants; import org.apache.log4j.component.plugins.Receiver; import org.apache.log4j.rule.ExpressionRule; import org.apache.log4j.rule.Rule; import org.apache.log4j.receivers.spi.Decoder; import org.apache.log4j.spi.LoggingEvent; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.util.Collection; import java.util.Iterator; /** * LogFileXMLReceiver will read an xml-formated log file and make the events in the log file * available to the log4j framework. *

* This receiver supports log files created using log4j's XMLLayout, as well as java.util.logging * XMLFormatter (via the org.apache.log4j.spi.Decoder interface). *

* By default, log4j's XMLLayout is supported (no need to specify a decoder in that case). *

* To configure this receiver to support java.util.logging's XMLFormatter, specify a 'decoder' param * of org.apache.log4j.xml.UtilLoggingXMLDecoder. *

* Tailing -may- work, but not in all cases (try using a file:// URL). If a process has a log file * open, the receiver may be able to read and tail the file. If the process closes the file and * reopens the file, the receiver may not be able to continue tailing the file. *

* An expressionFilter may be specified. Only events passing the expression will be forwarded to the * log4j framework. *

* Once the event has been "posted", it will be handled by the appenders currently configured in the * LoggerRespository. * * @author Scott Deboy * @since 1.3 */ public class LogFileXMLReceiver extends Receiver { private String fileURL; private Rule expressionRule; private String filterExpression; private String decoder = "org.apache.log4j.xml.XMLDecoder"; private boolean tailing = false; private Decoder decoderInstance; private Reader reader; private static final String FILE_KEY = "file"; private String host; private String path; private boolean useCurrentThread; /** * Accessor * * @return file URL */ public String getFileURL() { return fileURL; } /** * Specify the URL of the XML-formatted file to process. * * @param fileURL */ public void setFileURL(String fileURL) { this.fileURL = fileURL; } /** * Accessor * * @return the decoder */ public String getDecoder() { return decoder; } /** * Specify the class name implementing org.apache.log4j.spi.Decoder that can process the file. * * @param _decoder */ public void setDecoder(String _decoder) { decoder = _decoder; } /** * Accessor * * @return filter expression */ public String getFilterExpression() { return filterExpression; } /** * Accessor * * @return tailing flag */ public boolean isTailing() { return tailing; } /** * Set the 'tailing' flag - may only work on file:// URLs and may stop tailing if the writing * process closes the file and reopens. * * @param tailing */ public void setTailing(boolean tailing) { this.tailing = tailing; } /** * Set the filter expression that will cause only events which pass the filter to be forwarded * to the log4j framework. * * @param filterExpression */ public void setFilterExpression(String filterExpression) { this.filterExpression = filterExpression; } private boolean passesExpression(LoggingEvent event) { if (event != null) { if (expressionRule != null) { return (expressionRule.evaluate(event, null)); } } return true; } public static void main(String[] args) { /* * LogFileXMLReceiver test = new LogFileXMLReceiver(); * test.setFileURL("file:///c:/samplelog.xml"); test.setFilterExpression("level >= TRACE"); * test.activateOptions(); */ } /** * Close the receiver, release any resources that are accessing the file. */ public void shutdown() { try { if (reader != null) { reader.close(); reader = null; } } catch (IOException ioe) { ioe.printStackTrace(); } } /** * Process the file */ public void activateOptions() { Runnable runnable = new Runnable() { public void run() { try { URL url = new URL(fileURL); host = url.getHost(); if (host != null && host.equals("")) { host = FILE_KEY; } path = url.getPath(); } catch (MalformedURLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { if (filterExpression != null) { expressionRule = ExpressionRule.getRule(filterExpression); } } catch (Exception e) { getLogger().warn("Invalid filter expression: " + filterExpression, e); } Class c; try { c = Class.forName(decoder); Object o = c.newInstance(); if (o instanceof Decoder) { decoderInstance = (Decoder) o; } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { reader = new InputStreamReader(new URL(getFileURL()).openStream()); process(reader); } catch (FileNotFoundException fnfe) { getLogger().info("file not available"); } catch (IOException ioe) { getLogger().warn("unable to load file", ioe); return; } } }; if (useCurrentThread) { runnable.run(); } else { Thread thread = new Thread(runnable, "LogFileXMLReceiver-" + getName()); thread.start(); } } private void process(Reader unbufferedReader) throws IOException { BufferedReader bufferedReader = new BufferedReader(unbufferedReader); char[] content = new char[10000]; getLogger().debug("processing starting: " + fileURL); int length = 0; do { System.out.println("in do loop-about to process"); while ((length = bufferedReader.read(content)) > -1) { processEvents(decoderInstance.decodeEvents(String.valueOf(content, 0, length))); } if (tailing) { try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } while (tailing); getLogger().debug("processing complete: " + fileURL); shutdown(); } private void processEvents(Collection c) { if (c == null) { return; } for (Iterator iter = c.iterator(); iter.hasNext();) { LoggingEvent evt = (LoggingEvent) iter.next(); if (passesExpression(evt)) { if (evt.getProperty(Constants.HOSTNAME_KEY) != null) { evt.setProperty(Constants.HOSTNAME_KEY, host); } if (evt.getProperty(Constants.APPLICATION_KEY) != null) { evt.setProperty(Constants.APPLICATION_KEY, path); } doPost(evt); } } } /** * When true, this property uses the current Thread to perform the import, otherwise when false * (the default), a new Thread is created and started to manage the import. * * @return true, if the current thread is used */ public final boolean isUseCurrentThread() { return useCurrentThread; } /** * Sets whether the current Thread or a new Thread is created to perform the import, the default * being false (new Thread created). * * @param useCurrentThread */ public final void setUseCurrentThread(boolean useCurrentThread) { this.useCurrentThread = useCurrentThread; } }UtilLoggingEntityResolver.java000066400000000000000000000030131252742764200337760ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/xml/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.xml; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import java.io.ByteArrayInputStream; /** * An {@link EntityResolver} specifically designed to return * an empty InputSource for logger.dtd. * */ public final class UtilLoggingEntityResolver implements EntityResolver { /** * Create new instance. */ public UtilLoggingEntityResolver() { super(); } /** {@inheritDoc} */ public InputSource resolveEntity(final String publicId, final String systemId) { if (systemId.endsWith("logger.dtd")) { return new InputSource(new ByteArrayInputStream(new byte[0])); } else { return null; } } } UtilLoggingXMLDecoder.java000066400000000000000000000327521252742764200327420ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/xml/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.xml; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.helpers.UtilLoggingLevel; import org.apache.log4j.receivers.spi.Decoder; import org.apache.log4j.spi.LocationInfo; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.ThrowableInformation; import org.apache.log4j.xml.SAXErrorHandler; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import javax.swing.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.awt.*; import java.io.*; import java.net.URL; import java.util.*; import java.util.zip.ZipInputStream; /** * Decodes JDK 1.4's java.util.logging package events * delivered via XML (using the logger.dtd). * * @author Scott Deboy (sdeboy@apache.org) * @author Paul Smith (psmith@apache.org) * */ public class UtilLoggingXMLDecoder implements Decoder { //NOTE: xml section is only handed on first delivery of events //on this first delivery of events, there is no end tag for the log element /** * Document prolog. */ private static final String BEGIN_PART = ""; /** * Document close. */ private static final String END_PART = ""; /** * Document builder. */ private DocumentBuilder docBuilder; /** * Additional properties. */ private Map additionalProperties = new HashMap(); /** * Partial event. */ private String partialEvent; /** * Record end. */ private static final String RECORD_END = ""; /** * Owner. */ private Component owner = null; private static final String ENCODING = "UTF-8"; /** * Create new instance. * @param o owner */ public UtilLoggingXMLDecoder(final Component o) { this(); this.owner = o; } /** * Create new instance. */ public UtilLoggingXMLDecoder() { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); try { docBuilder = dbf.newDocumentBuilder(); docBuilder.setErrorHandler(new SAXErrorHandler()); docBuilder.setEntityResolver(new UtilLoggingEntityResolver()); } catch (ParserConfigurationException pce) { System.err.println("Unable to get document builder"); } } /** * Sets an additionalProperty map, where each Key/Value pair is * automatically added to each LoggingEvent as it is decoded. * * This is useful, say, to include the source file name of the Logging events * @param properties additional properties */ public void setAdditionalProperties(final Map properties) { this.additionalProperties = properties; } /** * Converts the LoggingEvent data in XML string format into an actual * XML Document class instance. * @param data XML fragment * @return dom document */ private Document parse(final String data) { if (docBuilder == null || data == null) { return null; } Document document = null; try { // we change the system ID to a valid URI so that Crimson won't // complain. Indeed, "log4j.dtd" alone is not a valid URI which // causes Crimson to barf. The Log4jEntityResolver only cares // about the "log4j.dtd" ending. /** * resetting the length of the StringBuffer is dangerous, particularly * on some JDK 1.4 impls, there's a known Bug that causes a memory leak */ StringBuffer buf = new StringBuffer(1024); if (!data.startsWith(" // (which will be processed) and the partial event which // will be combined and processed in the next section //if the document does not contain a record end, // append it to the partial event string if (document.lastIndexOf(RECORD_END) == -1) { partialEvent = partialEvent + document; return null; } if (document.lastIndexOf(RECORD_END) + RECORD_END.length() < document.length()) { newDoc = document.substring(0, document.lastIndexOf(RECORD_END) + RECORD_END.length()); newPartialEvent = document.substring( document.lastIndexOf(RECORD_END) + RECORD_END.length()); } else { newDoc = document; } if (partialEvent != null) { newDoc = partialEvent + newDoc; } partialEvent = newPartialEvent; Document doc = parse(newDoc); if (doc == null) { return null; } return decodeEvents(doc); } return null; } /** * Converts the string data into an XML Document, and then soaks out the * relevant bits to form a new LoggingEvent instance which can be used * by any Log4j element locally. * @param data XML fragment * @return a single LoggingEvent or null */ public LoggingEvent decode(final String data) { Document document = parse(data); if (document == null) { return null; } Vector events = decodeEvents(document); if (events.size() > 0) { return (LoggingEvent) events.firstElement(); } return null; } /** * Given a Document, converts the XML into a Vector of LoggingEvents. * @param document XML document * @return Vector of LoggingEvents */ private Vector decodeEvents(final Document document) { Vector events = new Vector(); NodeList eventList = document.getElementsByTagName("record"); for (int eventIndex = 0; eventIndex < eventList.getLength(); eventIndex++) { Node eventNode = eventList.item(eventIndex); Logger logger = null; long timeStamp = 0L; Level level = null; String threadName = null; Object message = null; String ndc = null; String[] exception = null; String className = null; String methodName = null; String fileName = null; String lineNumber = null; Hashtable properties = new Hashtable(); //format of date: 2003-05-04T11:04:52 //ignore date or set as a property? using millis in constructor instead NodeList list = eventNode.getChildNodes(); int listLength = list.getLength(); if (listLength == 0) { continue; } for (int y = 0; y < listLength; y++) { String tagName = list.item(y).getNodeName(); if (tagName.equalsIgnoreCase("logger")) { logger = Logger.getLogger(getCData(list.item(y))); } if (tagName.equalsIgnoreCase("millis")) { timeStamp = Long.parseLong(getCData(list.item(y))); } if (tagName.equalsIgnoreCase("level")) { level = UtilLoggingLevel.toLevel(getCData(list.item(y))); } if (tagName.equalsIgnoreCase("thread")) { threadName = getCData(list.item(y)); } if (tagName.equalsIgnoreCase("sequence")) { properties.put("log4jid", getCData(list.item(y))); } if (tagName.equalsIgnoreCase("message")) { message = getCData(list.item(y)); } if (tagName.equalsIgnoreCase("class")) { className = getCData(list.item(y)); } if (tagName.equalsIgnoreCase("method")) { methodName = getCData(list.item(y)); } if (tagName.equalsIgnoreCase("exception")) { ArrayList exceptionList = new ArrayList(); NodeList exList = list.item(y).getChildNodes(); int exlistLength = exList.getLength(); for (int i2 = 0; i2 < exlistLength; i2++) { Node exNode = exList.item(i2); String exName = exList.item(i2).getNodeName(); if (exName.equalsIgnoreCase("message")) { exceptionList.add(getCData(exList.item(i2))); } if (exName.equalsIgnoreCase("frame")) { NodeList exList2 = exNode.getChildNodes(); int exlist2Length = exList2.getLength(); for (int i3 = 0; i3 < exlist2Length; i3++) { exceptionList.add(getCData(exList2.item(i3)) + "\n"); } } } if (exceptionList.size() > 0) { exception = (String[]) exceptionList.toArray(new String[exceptionList.size()]); } } } /** * We add all the additional properties to the properties * hashtable. Override properties that already exist */ if (additionalProperties.size() > 0) { if (properties == null) { properties = new Hashtable(additionalProperties); } Iterator i = additionalProperties.entrySet().iterator(); while (i.hasNext()) { Map.Entry e = (Map.Entry) i.next(); properties.put(e.getKey(), e.getValue()); } } LocationInfo info; if ((fileName != null) || (className != null) || (methodName != null) || (lineNumber != null)) { info = new LocationInfo(fileName, className, methodName, lineNumber); } else { info = LocationInfo.NA_LOCATION_INFO; } ThrowableInformation throwableInfo = null; if (exception != null) { throwableInfo = new ThrowableInformation(exception); } LoggingEvent loggingEvent = new LoggingEvent(null, logger, timeStamp, level, message, threadName, throwableInfo, ndc, info, properties); events.add(loggingEvent); } return events; } /** * Get contents of CDATASection. * @param n CDATASection * @return text content of all text or CDATA children of node. */ private String getCData(final Node n) { StringBuffer buf = new StringBuffer(); NodeList nl = n.getChildNodes(); for (int x = 0; x < nl.getLength(); x++) { Node innerNode = nl.item(x); if ( (innerNode.getNodeType() == Node.TEXT_NODE) || (innerNode.getNodeType() == Node.CDATA_SECTION_NODE)) { buf.append(innerNode.getNodeValue()); } } return buf.toString(); } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/receivers/xml/XMLDecoder.java000066400000000000000000000360741252742764200306550ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.xml; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.receivers.spi.Decoder; import org.apache.log4j.spi.LocationInfo; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.ThrowableInformation; import org.apache.log4j.xml.Log4jEntityResolver; import org.apache.log4j.xml.SAXErrorHandler; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import javax.swing.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.awt.*; import java.io.*; import java.net.URL; import java.util.*; import java.util.zip.ZipInputStream; /** * Decodes Logging Events in XML formated into elements that are used by * Chainsaw. * * This decoder can process a collection of log4j:event nodes ONLY * (no XML declaration nor eventSet node) * * NOTE: Only a single LoggingEvent is returned from the decode method * even though the DTD supports multiple events nested in an eventSet. * * NOTE: This class has been created on the assumption that all XML log files * are encoded in UTF-8. There is no current support for any other * encoding format at this time. * * @author Scott Deboy (sdeboy@apache.org) * @author Paul Smith (psmith@apache.org) * */ public class XMLDecoder implements Decoder { private static final String ENCODING = "UTF-8"; /** * Document prolog. */ private static final String BEGINPART = "" + "" + ""; /** * Document close. */ private static final String ENDPART = ""; /** * Record end. */ private static final String RECORD_END = ""; /** * Document builder. */ private DocumentBuilder docBuilder; /** * Additional properties. */ private Map additionalProperties = new HashMap(); /** * Partial event. */ private String partialEvent; /** * Owner. */ private Component owner = null; /** * Create new instance. * @param o owner */ public XMLDecoder(final Component o) { this(); this.owner = o; } /** * Create new instance. */ public XMLDecoder() { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); try { docBuilder = dbf.newDocumentBuilder(); docBuilder.setErrorHandler(new SAXErrorHandler()); docBuilder.setEntityResolver(new Log4jEntityResolver()); } catch (ParserConfigurationException pce) { System.err.println("Unable to get document builder"); } } /** * Sets an additionalProperty map, where each Key/Value pair is * automatically added to each LoggingEvent as it is decoded. * * This is useful, say, to include the source file name of the Logging events * @param properties additional properties */ public void setAdditionalProperties(final Map properties) { this.additionalProperties = properties; } /** * Converts the LoggingEvent data in XML string format into an actual * XML Document class instance. * @param data XML fragment * @return dom document */ private Document parse(final String data) { if (docBuilder == null || data == null) { return null; } Document document = null; try { // we change the system ID to a valid URI so that Crimson won't // complain. Indeed, "log4j.dtd" alone is not a valid URI which // causes Crimson to barf. The Log4jEntityResolver only cares // about the "log4j.dtd" ending. /** * resetting the length of the StringBuffer is dangerous, particularly * on some JDK 1.4 impls, there's a known Bug that causes a memory leak */ StringBuffer buf = new StringBuffer(1024); buf.append(BEGINPART); buf.append(data); buf.append(ENDPART); InputSource inputSource = new InputSource(new StringReader(buf.toString())); document = docBuilder.parse(inputSource); } catch (Exception e) { e.printStackTrace(); } return document; } /** * Decodes a File into a Vector of LoggingEvents. * @param url the url of a file containing events to decode * @return Vector of LoggingEvents * @throws IOException if IO error during processing. */ public Vector decode(final URL url) throws IOException { LineNumberReader reader; boolean isZipFile = url.getPath().toLowerCase().endsWith(".zip"); InputStream inputStream; if (isZipFile) { inputStream = new ZipInputStream(url.openStream()); //move stream to next entry so we can read it ((ZipInputStream)inputStream).getNextEntry(); } else { inputStream = url.openStream(); } if (owner != null) { reader = new LineNumberReader( new InputStreamReader( new ProgressMonitorInputStream(owner, "Loading " + url , inputStream), ENCODING)); } else { reader = new LineNumberReader(new InputStreamReader(inputStream, ENCODING)); } Vector v = new Vector(); String line; Vector events; try { while ((line = reader.readLine()) != null) { StringBuffer buffer = new StringBuffer(line); for (int i = 0; i < 1000; i++) { buffer.append(reader.readLine()).append("\n"); } events = decodeEvents(buffer.toString()); if (events != null) { v.addAll(events); } } } finally { partialEvent = null; try { if (reader != null) { reader.close(); } } catch (Exception e) { e.printStackTrace(); } } return v; } /** * Decodes a String representing a number of events into a * Vector of LoggingEvents. * @param document to decode events from * @return Vector of LoggingEvents */ public Vector decodeEvents(final String document) { if (document != null) { if (document.trim().equals("")) { return null; } String newDoc = null; String newPartialEvent = null; //separate the string into the last portion ending with // (which will be processed) and the // partial event which will be combined and // processed in the next section //if the document does not contain a record end, // append it to the partial event string if (document.lastIndexOf(RECORD_END) == -1) { partialEvent = partialEvent + document; return null; } if (document.lastIndexOf(RECORD_END) + RECORD_END.length() < document.length()) { newDoc = document.substring(0, document.lastIndexOf(RECORD_END) + RECORD_END.length()); newPartialEvent = document.substring( document.lastIndexOf(RECORD_END) + RECORD_END.length()); } else { newDoc = document; } if (partialEvent != null) { newDoc = partialEvent + newDoc; } partialEvent = newPartialEvent; Document doc = parse(newDoc); if (doc == null) { return null; } return decodeEvents(doc); } return null; } /** * Converts the string data into an XML Document, and then soaks out the * relevant bits to form a new LoggingEvent instance which can be used * by any Log4j element locally. * @param data XML fragment * @return a single LoggingEvent or null */ public LoggingEvent decode(final String data) { Document document = parse(data); if (document == null) { return null; } Vector events = decodeEvents(document); if (events.size() > 0) { return (LoggingEvent) events.firstElement(); } return null; } /** * Given a Document, converts the XML into a Vector of LoggingEvents. * @param document XML document * @return Vector of LoggingEvents */ private Vector decodeEvents(final Document document) { Vector events = new Vector(); Logger logger; long timeStamp; Level level; String threadName; Object message = null; String ndc = null; String[] exception = null; String className = null; String methodName = null; String fileName = null; String lineNumber = null; Hashtable properties = null; NodeList nl = document.getElementsByTagName("log4j:eventSet"); Node eventSet = nl.item(0); NodeList eventList = eventSet.getChildNodes(); for (int eventIndex = 0; eventIndex < eventList.getLength(); eventIndex++) { Node eventNode = eventList.item(eventIndex); //ignore carriage returns in xml if (eventNode.getNodeType() != Node.ELEMENT_NODE) { continue; } logger = Logger.getLogger(eventNode.getAttributes().getNamedItem("logger").getNodeValue()); timeStamp = Long.parseLong(eventNode.getAttributes().getNamedItem("timestamp").getNodeValue()); level = Level.toLevel(eventNode.getAttributes().getNamedItem("level").getNodeValue()); threadName = eventNode.getAttributes().getNamedItem("thread").getNodeValue(); NodeList list = eventNode.getChildNodes(); int listLength = list.getLength(); if (listLength == 0) { continue; } for (int y = 0; y < listLength; y++) { String tagName = list.item(y).getNodeName(); if (tagName.equalsIgnoreCase("log4j:message")) { message = getCData(list.item(y)); } if (tagName.equalsIgnoreCase("log4j:NDC")) { ndc = getCData(list.item(y)); } //still support receiving of MDC and convert to properties if (tagName.equalsIgnoreCase("log4j:MDC")) { properties = new Hashtable(); NodeList propertyList = list.item(y).getChildNodes(); int propertyLength = propertyList.getLength(); for (int i = 0; i < propertyLength; i++) { String propertyTag = propertyList.item(i).getNodeName(); if (propertyTag.equalsIgnoreCase("log4j:data")) { Node property = propertyList.item(i); String name = property.getAttributes().getNamedItem("name").getNodeValue(); String value = property.getAttributes().getNamedItem("value").getNodeValue(); properties.put(name, value); } } } if (tagName.equalsIgnoreCase("log4j:throwable")) { String exceptionString = getCData(list.item(y)); if (exceptionString != null && !exceptionString.trim().equals("")) { exception = new String[] {exceptionString.trim() }; } } if (tagName.equalsIgnoreCase("log4j:locationinfo")) { className = list.item(y).getAttributes().getNamedItem("class").getNodeValue(); methodName = list.item(y).getAttributes().getNamedItem("method").getNodeValue(); fileName = list.item(y).getAttributes().getNamedItem("file").getNodeValue(); lineNumber = list.item(y).getAttributes().getNamedItem("line").getNodeValue(); } if (tagName.equalsIgnoreCase("log4j:properties")) { if (properties == null) { properties = new Hashtable(); } NodeList propertyList = list.item(y).getChildNodes(); int propertyLength = propertyList.getLength(); for (int i = 0; i < propertyLength; i++) { String propertyTag = propertyList.item(i).getNodeName(); if (propertyTag.equalsIgnoreCase("log4j:data")) { Node property = propertyList.item(i); String name = property.getAttributes().getNamedItem("name").getNodeValue(); String value = property.getAttributes().getNamedItem("value").getNodeValue(); properties.put(name, value); } } } /** * We add all the additional properties to the properties * hashtable. Override properties that already exist */ if (additionalProperties.size() > 0) { if (properties == null) { properties = new Hashtable(additionalProperties); } Iterator i = additionalProperties.entrySet().iterator(); while (i.hasNext()) { Map.Entry e = (Map.Entry) i.next(); properties.put(e.getKey(), e.getValue()); } } } LocationInfo info; if ((fileName != null) || (className != null) || (methodName != null) || (lineNumber != null)) { info = new LocationInfo(fileName, className, methodName, lineNumber); } else { info = LocationInfo.NA_LOCATION_INFO; } ThrowableInformation throwableInfo = null; if (exception != null) { throwableInfo = new ThrowableInformation(exception); } LoggingEvent loggingEvent = new LoggingEvent(null, logger, timeStamp, level, message, threadName, throwableInfo, ndc, info, properties); events.add(loggingEvent); message = null; ndc = null; exception = null; className = null; methodName = null; fileName = null; lineNumber = null; properties = null; } return events; } /** * Get contents of CDATASection. * @param n CDATASection * @return text content of all text or CDATA children of node. */ private String getCData(final Node n) { StringBuffer buf = new StringBuffer(); NodeList nl = n.getChildNodes(); for (int x = 0; x < nl.getLength(); x++) { Node innerNode = nl.item(x); if ( (innerNode.getNodeType() == Node.TEXT_NODE) || (innerNode.getNodeType() == Node.CDATA_SECTION_NODE)) { buf.append(innerNode.getNodeValue()); } } return buf.toString(); } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rolling/000077500000000000000000000000001252742764200247315ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rolling/CompositeTriggeringPolicy.java000066400000000000000000000057301252742764200327450ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rolling; import java.util.HashSet; import java.util.Iterator; import java.util.Properties; import java.util.Set; import org.apache.log4j.Appender; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.OptionHandler; import org.apache.log4j.xml.UnrecognizedElementHandler; import org.w3c.dom.Element; /** * CompositeTriggeringPolicy determines if rolling should be triggered * by evaluating the current event against a set of triggering policies. * * TriggeringPolicy results are OR'd together - if any of the triggering policies report rolling should occur, * a rolling event will be triggered. * */ public final class CompositeTriggeringPolicy implements TriggeringPolicy, UnrecognizedElementHandler { Set triggeringPolicies = new HashSet(); public CompositeTriggeringPolicy() { } public boolean isTriggeringEvent(final Appender appender, final LoggingEvent event, final String file, final long fileLength) { boolean isTriggered = false; for (Iterator iter = triggeringPolicies.iterator();iter.hasNext();) { boolean result = ((TriggeringPolicy)iter.next()).isTriggeringEvent(appender, event, file, fileLength); isTriggered = isTriggered || result; } return isTriggered; } /** * Add triggering policy * * @param policy */ public void addTriggeringPolicy(final TriggeringPolicy policy) { triggeringPolicies.add(policy); } public void activateOptions() { for (Iterator iter = triggeringPolicies.iterator();iter.hasNext();) { ((TriggeringPolicy)iter.next()).activateOptions(); } } public boolean parseUnrecognizedElement(final Element element, final Properties props) throws Exception { final String nodeName = element.getNodeName(); if ("triggeringPolicy".equals(nodeName)) { OptionHandler policy = org.apache.log4j.extras.DOMConfigurator.parseElement(element, props, TriggeringPolicy.class); if (policy instanceof TriggeringPolicy) { policy.activateOptions(); addTriggeringPolicy((TriggeringPolicy)policy); } return true; } return false; } } FilterBasedTriggeringPolicy.java000066400000000000000000000077731252742764200331210ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rolling/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rolling; import org.apache.log4j.Appender; import org.apache.log4j.spi.Filter; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.OptionHandler; import org.apache.log4j.spi.TriggeringEventEvaluator; import org.apache.log4j.xml.UnrecognizedElementHandler; import org.w3c.dom.Element; import java.util.Properties; /** * FilterBasedTriggeringPolicy determines if rolling should be triggered * by evaluating the current message against a set of filters. Unless a * filter rejects a message, a rolling event will be triggered. * * @author Curt Arnold * */ public final class FilterBasedTriggeringPolicy implements TriggeringPolicy, TriggeringEventEvaluator, UnrecognizedElementHandler { /** * The first filter in the filter chain. Set to null initially. */ private Filter headFilter; /** * The last filter in the filter chain. */ private Filter tailFilter; /** * Creates a new FilterBasedTriggeringPolicy. */ public FilterBasedTriggeringPolicy() { } /** * {@inheritDoc} */ public boolean isTriggeringEvent(LoggingEvent event) { // // in the abnormal case of no contained filters // always return true to avoid each logging event // from having its own file. if (headFilter == null) { return false; } // // otherwise loop through the filters // for (Filter f = headFilter; f != null; f = f.next) { switch (f.decide(event)) { case Filter.DENY: return false; case Filter.ACCEPT: return true; } } return true; } /** * {@inheritDoc} * */ public boolean isTriggeringEvent( final Appender appender, final LoggingEvent event, final String file, final long fileLength) { return isTriggeringEvent(event); } /** * Add a filter to end of the filter list. * @param newFilter filter to add to end of list. */ public void addFilter(final Filter newFilter) { if (headFilter == null) { headFilter = newFilter; tailFilter = newFilter; } else { tailFilter.next = newFilter; tailFilter = newFilter; } } /** * Clear the filters chain. * */ public void clearFilters() { headFilter = null; tailFilter = null; } /** * Returns the head Filter. * @return head of filter chain, may be null. * */ public Filter getFilter() { return headFilter; } /** * {@inheritDoc} */ public void activateOptions() { for (Filter f = headFilter; f != null; f = f.next) { f.activateOptions(); } } /** * {@inheritDoc} */ public boolean parseUnrecognizedElement(final Element element, final Properties props) throws Exception { final String nodeName = element.getNodeName(); if ("filter".equals(nodeName)) { OptionHandler filter = org.apache.log4j.extras.DOMConfigurator.parseElement( element, props, Filter.class); if (filter instanceof Filter) { filter.activateOptions(); this.addFilter((Filter) filter); } return true; } return false; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rolling/FixedWindowRollingPolicy.java000066400000000000000000000223171252742764200325370ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rolling; import java.io.File; import java.util.ArrayList; import java.util.List; import org.apache.log4j.pattern.PatternConverter; import org.apache.log4j.rolling.helper.Action; import org.apache.log4j.rolling.helper.FileRenameAction; import org.apache.log4j.rolling.helper.GZCompressAction; import org.apache.log4j.rolling.helper.ZipCompressAction; import org.apache.log4j.helpers.LogLog; /** * When rolling over, FixedWindowRollingPolicy renames files * according to a fixed window algorithm as described below. * *

The ActiveFileName property, which is required, represents the name * of the file where current logging output will be written. * The FileNamePattern option represents the file name pattern for the * archived (rolled over) log files. If present, the FileNamePattern * option must include an integer token, that is the string "%i" somewhere * within the pattern. * *

Let max and min represent the values of respectively * the MaxIndex and MinIndex options. Let "foo.log" be the value * of the ActiveFile option and "foo.%i.log" the value of * FileNamePattern. Then, when rolling over, the file * foo.max.log will be deleted, the file * foo.max-1.log will be renamed as * foo.max.log, the file foo.max-2.log * renamed as foo.max-1.log, and so on, * the file foo.min+1.log renamed as * foo.min+2.log. Lastly, the active file foo.log * will be renamed as foo.min.log and a new active file name * foo.log will be created. * *

Given that this rollover algorithm requires as many file renaming * operations as the window size, large window sizes are discouraged. The * current implementation will automatically reduce the window size to 12 when * larger values are specified by the user. * * * @author Ceki Gülcü * */ public final class FixedWindowRollingPolicy extends RollingPolicyBase { /** * It's almost always a bad idea to have a large window size, say over 12. */ private static final int MAX_WINDOW_SIZE = 12; /** * Index for oldest retained log file. */ private int maxIndex; /** * Index for most recent log file. */ private int minIndex; /** * if true, then an explicit name for the active file was * specified using RollingFileAppender.file or the * redundent RollingPolicyBase.setActiveFile */ private boolean explicitActiveFile; /** * Constructs a new instance. */ public FixedWindowRollingPolicy() { minIndex = 1; maxIndex = 7; } /** * {@inheritDoc} */ public void activateOptions() { super.activateOptions(); if (maxIndex < minIndex) { LogLog.warn( "MaxIndex (" + maxIndex + ") cannot be smaller than MinIndex (" + minIndex + ")."); LogLog.warn("Setting maxIndex to equal minIndex."); maxIndex = minIndex; } if ((maxIndex - minIndex) > MAX_WINDOW_SIZE) { LogLog.warn("Large window sizes are not allowed."); maxIndex = minIndex + MAX_WINDOW_SIZE; LogLog.warn("MaxIndex reduced to " + String.valueOf(maxIndex) + "."); } PatternConverter itc = getIntegerPatternConverter(); if (itc == null) { throw new IllegalStateException( "FileNamePattern [" + getFileNamePattern() + "] does not contain a valid integer format specifier"); } } /** * {@inheritDoc} */ public RolloverDescription initialize( final String file, final boolean append) { String newActiveFile = file; explicitActiveFile = false; if (activeFileName != null) { explicitActiveFile = true; newActiveFile = activeFileName; } if (file != null) { explicitActiveFile = true; newActiveFile = file; } if (!explicitActiveFile) { StringBuffer buf = new StringBuffer(); formatFileName(new Integer(minIndex), buf); newActiveFile = buf.toString(); } return new RolloverDescriptionImpl(newActiveFile, append, null, null); } /** * {@inheritDoc} */ public RolloverDescription rollover(final String currentFileName) { if (maxIndex >= 0) { int purgeStart = minIndex; if (!explicitActiveFile) { purgeStart++; } if (!purge(purgeStart, maxIndex)) { return null; } StringBuffer buf = new StringBuffer(); formatFileName(new Integer(purgeStart), buf); String renameTo = buf.toString(); String compressedName = renameTo; Action compressAction = null; if (renameTo.endsWith(".gz")) { renameTo = renameTo.substring(0, renameTo.length() - 3); compressAction = new GZCompressAction( new File(renameTo), new File(compressedName), true); } else if (renameTo.endsWith(".zip")) { renameTo = renameTo.substring(0, renameTo.length() - 4); compressAction = new ZipCompressAction( new File(renameTo), new File(compressedName), true); } FileRenameAction renameAction = new FileRenameAction( new File(currentFileName), new File(renameTo), false); return new RolloverDescriptionImpl( currentFileName, false, renameAction, compressAction); } return null; } /** * Get index of oldest log file to be retained. * @return index of oldest log file. */ public int getMaxIndex() { return maxIndex; } /** * Get index of most recent log file. * @return index of oldest log file. */ public int getMinIndex() { return minIndex; } /** * Set index of oldest log file to be retained. * @param maxIndex index of oldest log file to be retained. */ public void setMaxIndex(int maxIndex) { this.maxIndex = maxIndex; } /** * Set index of most recent log file. * @param minIndex Index of most recent log file. */ public void setMinIndex(int minIndex) { this.minIndex = minIndex; } /** * Purge and rename old log files in preparation for rollover * @param lowIndex low index * @param highIndex high index. Log file associated with high * index will be deleted if needed. * @return true if purge was successful and rollover should be attempted. */ private boolean purge(final int lowIndex, final int highIndex) { int suffixLength = 0; List renames = new ArrayList(); StringBuffer buf = new StringBuffer(); formatFileName(new Integer(lowIndex), buf); String lowFilename = buf.toString(); if (lowFilename.endsWith(".gz")) { suffixLength = 3; } else if (lowFilename.endsWith(".zip")) { suffixLength = 4; } for (int i = lowIndex; i <= highIndex; i++) { File toRename = new File(lowFilename); boolean isBase = false; if (suffixLength > 0) { File toRenameBase = new File( lowFilename.substring(0, lowFilename.length() - suffixLength)); if (toRename.exists()) { if (toRenameBase.exists()) { toRenameBase.delete(); } } else { toRename = toRenameBase; isBase = true; } } if (toRename.exists()) { // // if at upper index then // attempt to delete last file // if that fails then abandon purge if (i == highIndex) { if (!toRename.delete()) { return false; } break; } // // if intermediate index // add a rename action to the list buf.setLength(0); formatFileName(new Integer(i + 1), buf); String highFilename = buf.toString(); String renameTo = highFilename; if (isBase) { renameTo = highFilename.substring(0, highFilename.length() - suffixLength); } renames.add(new FileRenameAction(toRename, new File(renameTo), true)); lowFilename = highFilename; } else { break; } } // // work renames backwards // for (int i = renames.size() - 1; i >= 0; i--) { Action action = (Action) renames.get(i); try { if (!action.execute()) { return false; } } catch (Exception ex) { LogLog.warn("Exception during purge in RollingFileAppender", ex); return false; } } return true; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rolling/RollingFileAppender.java000066400000000000000000000421071252742764200314650ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rolling; import org.apache.log4j.Appender; import org.apache.log4j.FileAppender; import org.apache.log4j.Logger; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.helpers.QuietWriter; import org.apache.log4j.rolling.helper.Action; import org.apache.log4j.spi.ErrorHandler; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.OptionHandler; import org.apache.log4j.xml.UnrecognizedElementHandler; import org.w3c.dom.Element; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Properties; /** * RollingFileAppender extends {@link FileAppender} to backup the log files * depending on {@link RollingPolicy} and {@link TriggeringPolicy}. *

* To be of any use, a RollingFileAppender instance must have both * a RollingPolicy and a TriggeringPolicy set up. * However, if its RollingPolicy also implements the * TriggeringPolicy interface, then only the former needs to be * set up. For example, {@link TimeBasedRollingPolicy} acts both as a * RollingPolicy and a TriggeringPolicy. * *

RollingFileAppender can be configured programattically or * using {@link org.apache.log4j.extras.DOMConfigurator} or * {@link org.apache.log4j.xml.DOMConfigurator} in log4j 1.2.15 or later. Here is a sample * configration file:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration>

<log4j:configuration debug="true">

  <appender name="ROLL" class="org.apache.log4j.rolling.RollingFileAppender">
    <rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
      <param name="FileNamePattern" value="/wombat/foo.%d{yyyy-MM}.gz"/>
    </rollingPolicy>

    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%c{1} - %m%n"/>
    </layout>
  </appender>

  <root">
    <appender-ref ref="ROLL"/>
  </root>

</log4j:configuration>
*

This configuration file specifies a monthly rollover schedule including * automatic compression of the archived files. See * {@link TimeBasedRollingPolicy} for more details. * * @author Heinz Richter * @author Ceki Gülcü * @since 1.3 * */ public final class RollingFileAppender extends FileAppender implements UnrecognizedElementHandler { /** * Triggering policy. */ private TriggeringPolicy triggeringPolicy; /** * Rolling policy. */ private RollingPolicy rollingPolicy; /** * Length of current active log file. */ private long fileLength = 0; /** * Asynchronous action (like compression) from previous rollover. */ private Action lastRolloverAsyncAction = null; /** * Construct a new instance. */ public RollingFileAppender() { } /** * Prepare instance of use. */ public void activateOptions() { if (rollingPolicy == null) { LogLog.warn( "Please set a rolling policy for the RollingFileAppender named '" + getName() + "'"); return; } // // if no explicit triggering policy and rolling policy is both. // if ( (triggeringPolicy == null) && rollingPolicy instanceof TriggeringPolicy) { triggeringPolicy = (TriggeringPolicy) rollingPolicy; } if (triggeringPolicy == null) { LogLog.warn( "Please set a TriggeringPolicy for the RollingFileAppender named '" + getName() + "'"); return; } Exception exception = null; synchronized (this) { triggeringPolicy.activateOptions(); rollingPolicy.activateOptions(); try { RolloverDescription rollover = rollingPolicy.initialize(getFile(), getAppend()); if (rollover != null) { Action syncAction = rollover.getSynchronous(); if (syncAction != null) { syncAction.execute(); } setFile(rollover.getActiveFileName()); setAppend(rollover.getAppend()); lastRolloverAsyncAction = rollover.getAsynchronous(); if (lastRolloverAsyncAction != null) { Thread runner = new Thread(lastRolloverAsyncAction); runner.start(); } } File activeFile = new File(getFile()); if (getAppend()) { fileLength = activeFile.length(); } else { fileLength = 0; } super.activateOptions(); } catch (Exception ex) { exception = ex; } } if (exception != null) { LogLog.warn( "Exception while initializing RollingFileAppender named '" + getName() + "'", exception); } } private QuietWriter createQuietWriter(final Writer writer) { ErrorHandler handler = errorHandler; if (handler == null) { handler = new DefaultErrorHandler(this); } return new QuietWriter(writer, handler); } /** Implements the usual roll over behaviour.

If MaxBackupIndex is positive, then files {File.1, ..., File.MaxBackupIndex -1} are renamed to {File.2, ..., File.MaxBackupIndex}. Moreover, File is renamed File.1 and closed. A new File is created to receive further log output.

If MaxBackupIndex is equal to zero, then the File is truncated with no backup files created. * @return true if rollover performed. */ public boolean rollover() { // // can't roll without a policy // if (rollingPolicy != null) { Exception exception = null; synchronized (this) { // // if a previous async task is still running //} if (lastRolloverAsyncAction != null) { // // block until complete // lastRolloverAsyncAction.close(); // // or don't block and return to rollover later // //if (!lastRolloverAsyncAction.isComplete()) return false; } try { RolloverDescription rollover = rollingPolicy.rollover(getFile()); if (rollover != null) { if (rollover.getActiveFileName().equals(getFile())) { closeWriter(); boolean success = true; if (rollover.getSynchronous() != null) { success = false; try { success = rollover.getSynchronous().execute(); } catch (Exception ex) { exception = ex; } } if (success) { if (rollover.getAppend()) { fileLength = new File(rollover.getActiveFileName()).length(); } else { fileLength = 0; } if (rollover.getAsynchronous() != null) { lastRolloverAsyncAction = rollover.getAsynchronous(); new Thread(lastRolloverAsyncAction).start(); } setFile( rollover.getActiveFileName(), rollover.getAppend(), bufferedIO, bufferSize); } else { setFile( rollover.getActiveFileName(), true, bufferedIO, bufferSize); if (exception == null) { LogLog.warn("Failure in post-close rollover action"); } else { LogLog.warn( "Exception in post-close rollover action", exception); } } } else { Writer newWriter = createWriter( createFileOutputStream( rollover.getActiveFileName(), rollover.getAppend())); closeWriter(); setFile(rollover.getActiveFileName()); this.qw = createQuietWriter(newWriter); boolean success = true; if (rollover.getSynchronous() != null) { success = false; try { success = rollover.getSynchronous().execute(); } catch (Exception ex) { exception = ex; } } if (success) { if (rollover.getAppend()) { fileLength = new File(rollover.getActiveFileName()).length(); } else { fileLength = 0; } if (rollover.getAsynchronous() != null) { lastRolloverAsyncAction = rollover.getAsynchronous(); new Thread(lastRolloverAsyncAction).start(); } } writeHeader(); } return true; } } catch (Exception ex) { exception = ex; } } if (exception != null) { LogLog.warn( "Exception during rollover, rollover deferred.", exception); } } return false; } /** * Creates a new FileOutputStream of a new log file, possibly creating first all the needed parent directories * * @param newFileName Filename of new log file to be created * @param append If file should be appended * @return newly created FileOutputStream * @throws FileNotFoundException if creating log file or parent directories was unsuccessful */ private FileOutputStream createFileOutputStream(String newFileName, boolean append) throws FileNotFoundException { try { // // attempt to create file // return new FileOutputStream(newFileName, append); } catch(FileNotFoundException ex) { // // if parent directory does not exist then // attempt to create it and try to create file // see bug 9150 // String parentName = new File(newFileName).getParent(); if (parentName != null) { File parentDir = new File(parentName); if (!parentDir.exists() && parentDir.mkdirs()) { return new FileOutputStream(newFileName, append); } else { throw ex; } } else { throw ex; } } } /** * {@inheritDoc} */ protected void subAppend(final LoggingEvent event) { // The rollover check must precede actual writing. This is the // only correct behavior for time driven triggers. if ( triggeringPolicy.isTriggeringEvent( this, event, getFile(), getFileLength())) { // // wrap rollover request in try block since // rollover may fail in case read access to directory // is not provided. However appender should still be in good // condition and the append should still happen. try { rollover(); } catch (Exception ex) { LogLog.warn("Exception during rollover attempt.", ex); } } super.subAppend(event); } /** * Get rolling policy. * @return rolling policy. */ public RollingPolicy getRollingPolicy() { return rollingPolicy; } /** * Get triggering policy. * @return triggering policy. */ public TriggeringPolicy getTriggeringPolicy() { return triggeringPolicy; } /** * Sets the rolling policy. * @param policy rolling policy. */ public void setRollingPolicy(final RollingPolicy policy) { rollingPolicy = policy; } /** * Set triggering policy. * @param policy triggering policy. */ public void setTriggeringPolicy(final TriggeringPolicy policy) { triggeringPolicy = policy; } /** * Close appender. Waits for any asynchronous file compression actions to be completed. */ public void close() { synchronized (this) { if (lastRolloverAsyncAction != null) { lastRolloverAsyncAction.close(); } } super.close(); } /** Returns an OutputStreamWriter when passed an OutputStream. The encoding used will depend on the value of the encoding property. If the encoding value is specified incorrectly the writer will be opened using the default system encoding (an error message will be printed to the loglog. @param os output stream, may not be null. @return new writer. */ protected OutputStreamWriter createWriter(final OutputStream os) { return super.createWriter(new CountingOutputStream(os, this)); } /** * Get byte length of current active log file. * @return byte length of current active log file. */ public long getFileLength() { return fileLength; } /** * Increments estimated byte length of current active log file. * @param increment additional bytes written to log file. */ public synchronized void incrementFileLength(int increment) { fileLength += increment; } /** * {@inheritDoc} */ public boolean parseUnrecognizedElement(final Element element, final Properties props) throws Exception { final String nodeName = element.getNodeName(); if ("rollingPolicy".equals(nodeName)) { OptionHandler rollingPolicy = org.apache.log4j.extras.DOMConfigurator.parseElement( element, props, RollingPolicy.class); if (rollingPolicy != null) { rollingPolicy.activateOptions(); this.setRollingPolicy((RollingPolicy) rollingPolicy); } return true; } if ("triggeringPolicy".equals(nodeName)) { OptionHandler triggerPolicy = org.apache.log4j.extras.DOMConfigurator.parseElement( element, props, TriggeringPolicy.class); if (triggerPolicy != null) { triggerPolicy.activateOptions(); this.setTriggeringPolicy((TriggeringPolicy) triggerPolicy); } return true; } return false; } /** * Wrapper for OutputStream that will report all write * operations back to this class for file length calculations. */ private static class CountingOutputStream extends OutputStream { /** * Wrapped output stream. */ private final OutputStream os; /** * Rolling file appender to inform of stream writes. */ private final RollingFileAppender rfa; /** * Constructor. * @param os output stream to wrap. * @param rfa rolling file appender to inform. */ public CountingOutputStream( final OutputStream os, final RollingFileAppender rfa) { this.os = os; this.rfa = rfa; } /** * {@inheritDoc} */ public void close() throws IOException { os.close(); } /** * {@inheritDoc} */ public void flush() throws IOException { os.flush(); } /** * {@inheritDoc} */ public void write(final byte[] b) throws IOException { os.write(b); rfa.incrementFileLength(b.length); } /** * {@inheritDoc} */ public void write(final byte[] b, final int off, final int len) throws IOException { os.write(b, off, len); rfa.incrementFileLength(len); } /** * {@inheritDoc} */ public void write(final int b) throws IOException { os.write(b); rfa.incrementFileLength(1); } } private static final class DefaultErrorHandler implements ErrorHandler { private final RollingFileAppender appender; public DefaultErrorHandler(final RollingFileAppender appender) { this.appender = appender; } /**@since 1.2*/ public void setLogger(Logger logger) { } public void error(String message, Exception ioe, int errorCode) { appender.close(); LogLog.error("IO failure for appender named "+ appender.getName(), ioe); } public void error(String message) { } /**@since 1.2*/ public void error(String message, Exception e, int errorCode, LoggingEvent event) { } /**@since 1.2*/ public void setAppender(Appender appender) { } /**@since 1.2*/ public void setBackupAppender(Appender appender) { } public void activateOptions() { } } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rolling/RollingPolicy.java000066400000000000000000000041561252742764200303700ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rolling; import org.apache.log4j.spi.OptionHandler; /** * A RollingPolicy specifies the actions taken * on a logging file rollover. * * @author Ceki Gülcü * @author Curt Arnold * */ public interface RollingPolicy extends OptionHandler { /** * Initialize the policy and return any initial actions for rolling file appender.. * * @param file current value of RollingFileAppender.getFile(). * @param append current value of RollingFileAppender.getAppend(). * @return Description of the initialization, may be null to indicate * no initialization needed. * @throws SecurityException if denied access to log files. */ public RolloverDescription initialize( final String file, final boolean append) throws SecurityException; /** * Prepare for a rollover. This method is called prior to * closing the active log file, performs any necessary * preliminary actions and describes actions needed * after close of current log file. * * @param activeFile file name for current active log file. * @return Description of pending rollover, may be null to indicate no rollover * at this time. * @throws SecurityException if denied access to log files. */ public RolloverDescription rollover(final String activeFile) throws SecurityException; } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rolling/RollingPolicyBase.java000066400000000000000000000120171252742764200311560ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rolling; import org.apache.log4j.pattern.ExtrasFormattingInfo; import org.apache.log4j.pattern.ExtrasPatternParser; import org.apache.log4j.pattern.PatternConverter; import org.apache.log4j.pattern.IntegerPatternConverter; import org.apache.log4j.pattern.DatePatternConverter; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.spi.OptionHandler; import java.util.ArrayList; import java.util.List; /** * Implements methods common to most, it not all, rolling * policies. Currently such methods are limited to a compression mode * getter/setter. * * @author Ceki Gülcü * @author Curt Arnold */ public abstract class RollingPolicyBase implements RollingPolicy, OptionHandler { /** * Error message. */ private static final String FNP_NOT_SET = "The FileNamePattern option must be set before using RollingPolicy. "; /** * Reference for error message. */ private static final String SEE_FNP_NOT_SET = "See also http://logging.apache.org/log4j/codes.html#tbr_fnp_not_set"; /** * File name pattern converters. */ private PatternConverter[] patternConverters; /** * File name field specifiers. */ private ExtrasFormattingInfo[] patternFields; /** * File name pattern. */ private String fileNamePatternStr; /** * Active file name may be null. * Duplicates FileAppender.file and should be removed. */ protected String activeFileName; /** * {@inheritDoc} */ public void activateOptions() { // find out period from the filename pattern if (fileNamePatternStr != null) { parseFileNamePattern(); } else { LogLog.warn(FNP_NOT_SET); LogLog.warn(SEE_FNP_NOT_SET); throw new IllegalStateException(FNP_NOT_SET + SEE_FNP_NOT_SET); } } /** * Set file name pattern. * @param fnp file name pattern. */ public void setFileNamePattern(String fnp) { fileNamePatternStr = fnp; } /** * Get file name pattern. * @return file name pattern. */ public String getFileNamePattern() { return fileNamePatternStr; } /** * ActiveFileName can be left unset, i.e. as null. * @param afn active file name. * @deprecated Duplicates FileAppender.file and should be removed */ public void setActiveFileName(String afn) { activeFileName = afn; } /** * Return the value of the ActiveFile option. * @deprecated Duplicates FileAppender.file and should be removed * @return active file name. */ public String getActiveFileName() { return activeFileName; } /** * Parse file name pattern. */ protected final void parseFileNamePattern() { List converters = new ArrayList(); List fields = new ArrayList(); ExtrasPatternParser.parse( fileNamePatternStr, converters, fields, null, ExtrasPatternParser.getFileNamePatternRules()); patternConverters = new PatternConverter[converters.size()]; patternConverters = (PatternConverter[]) converters.toArray(patternConverters); patternFields = new ExtrasFormattingInfo[converters.size()]; patternFields = (ExtrasFormattingInfo[]) fields.toArray(patternFields); } /** * Format file name. * * @param obj object to be evaluted in formatting, may not be null. * @param buf string buffer to which formatted file name is appended, may not be null. */ protected final void formatFileName( final Object obj, final StringBuffer buf) { for (int i = 0; i < patternConverters.length; i++) { int fieldStart = buf.length(); patternConverters[i].format(obj, buf); if (patternFields[i] != null) { patternFields[i].format(fieldStart, buf); } } } protected final PatternConverter getDatePatternConverter() { for (int i = 0; i < patternConverters.length; i++) { if (patternConverters[i] instanceof DatePatternConverter) { return patternConverters[i]; } } return null; } protected final PatternConverter getIntegerPatternConverter() { for (int i = 0; i < patternConverters.length; i++) { if (patternConverters[i] instanceof IntegerPatternConverter) { return patternConverters[i]; } } return null; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rolling/RolloverDescription.java000066400000000000000000000032761252742764200316140ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rolling; import org.apache.log4j.rolling.helper.Action; /** * Description of actions needed to complete rollover. * * @author Curt Arnold * */ public interface RolloverDescription { /** * Active log file name after rollover. * @return active log file name after rollover. */ String getActiveFileName(); /** * Specifies if active file should be opened for appending. * @return if true, active file should be opened for appending. */ boolean getAppend(); /** * Action to be completed after close of current active log file * before returning control to caller. * * @return action, may be null. */ Action getSynchronous(); /** * Action to be completed after close of current active log file * and before next rollover attempt, may be executed asynchronously. * * @return action, may be null. */ Action getAsynchronous(); } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rolling/RolloverDescriptionImpl.java000066400000000000000000000061251252742764200324320ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rolling; import org.apache.log4j.rolling.helper.Action; /** * Description of actions needed to complete rollover. * * @author Curt Arnold * */ public final class RolloverDescriptionImpl implements RolloverDescription { /** * Active log file name after rollover. */ private final String activeFileName; /** * Should active file be opened for appending. */ private final boolean append; /** * Action to be completed after close of current active log file * before returning control to caller. */ private final Action synchronous; /** * Action to be completed after close of current active log file * and before next rollover attempt, may be executed asynchronously. */ private final Action asynchronous; /** * Create new instance. * @param activeFileName active log file name after rollover, may not be null. * @param append true if active log file after rollover should be opened for appending. * @param synchronous action to be completed after close of current active log file, may be null. * @param asynchronous action to be completed after close of current active log file and * before next rollover attempt. */ public RolloverDescriptionImpl( final String activeFileName, final boolean append, final Action synchronous, final Action asynchronous) { if (activeFileName == null) { throw new NullPointerException("activeFileName"); } this.append = append; this.activeFileName = activeFileName; this.synchronous = synchronous; this.asynchronous = asynchronous; } /** * Active log file name after rollover. * @return active log file name after rollover. */ public String getActiveFileName() { return activeFileName; } /** * {@inheritDoc} */ public boolean getAppend() { return append; } /** * Action to be completed after close of current active log file * before returning control to caller. * * @return action, may be null. */ public Action getSynchronous() { return synchronous; } /** * Action to be completed after close of current active log file * and before next rollover attempt, may be executed asynchronously. * * @return action, may be null. */ public Action getAsynchronous() { return asynchronous; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rolling/SizeBasedTriggeringPolicy.java000066400000000000000000000044171252742764200326550ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rolling; import org.apache.log4j.Appender; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.OptionHandler; /** * SizeBasedTriggeringPolicy looks at size of the file being * currently written to. * * @author Ceki Gülcü * @author Curt Arnold * */ public final class SizeBasedTriggeringPolicy implements TriggeringPolicy, OptionHandler { /** * Rollover threshold size in bytes. */ private long maxFileSize = 10 * 1024 * 1024; // let 10 MB the default max size /** * Constructs a new instance. */ public SizeBasedTriggeringPolicy() { } /** * Constructs an new instance. * @param maxFileSize rollover threshold size in bytes. */ public SizeBasedTriggeringPolicy(final long maxFileSize) { this.maxFileSize = maxFileSize; } /** * {@inheritDoc} */ public boolean isTriggeringEvent( final Appender appender, final LoggingEvent event, final String file, final long fileLength) { //System.out.println("Size"+file.length()); return (fileLength >= maxFileSize); } /** * Gets rollover threshold size in bytes. * @return rollover threshold size in bytes. */ public long getMaxFileSize() { return maxFileSize; } /** * Sets rollover threshold size in bytes. * @param l new value for rollover threshold size. */ public void setMaxFileSize(long l) { maxFileSize = l; } /** * Prepares policy for use. */ public void activateOptions() { } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rolling/TimeBasedRollingPolicy.java000066400000000000000000000227171252742764200321510ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rolling; import java.io.File; import java.util.Date; import org.apache.log4j.Appender; import org.apache.log4j.pattern.PatternConverter; import org.apache.log4j.rolling.helper.Action; import org.apache.log4j.rolling.helper.FileRenameAction; import org.apache.log4j.rolling.helper.GZCompressAction; import org.apache.log4j.rolling.helper.ZipCompressAction; import org.apache.log4j.spi.LoggingEvent; /** * TimeBasedRollingPolicy is both easy to configure and quite * powerful. * *

In order to use TimeBasedRollingPolicy, the * FileNamePattern option must be set. It basically specifies the name of the * rolled log files. The value FileNamePattern should consist of * the name of the file, plus a suitably placed %d conversion * specifier. The %d conversion specifier may contain a date and * time pattern as specified by the {@link java.text.SimpleDateFormat} class. If * the date and time pattern is ommitted, then the default pattern of * "yyyy-MM-dd" is assumed. The following examples should clarify the point. * *

* * * * * * * * * * * * * * * * *
FileNamePattern valueRollover scheduleExample
/wombat/folder/foo.%dDaily rollover (at midnight). Due to the omission of the optional * time and date pattern for the %d token specifier, the default pattern * of "yyyy-MM-dd" is assumed, which corresponds to daily rollover. * During November 23rd, 2004, logging output will go to * the file /wombat/foo.2004-11-23. At midnight and for * the rest of the 24th, logging output will be directed to * /wombat/foo.2004-11-24. *
/wombat/foo.%d{yyyy-MM}.logRollover at the beginning of each month.During the month of October 2004, logging output will go to * /wombat/foo.2004-10.log. After midnight of October 31st * and for the rest of November, logging output will be directed to * /wombat/foo.2004-11.log. *
*

Automatic file compression

* TimeBasedRollingPolicy supports automatic file compression. * This feature is enabled if the value of the FileNamePattern option * ends with .gz or .zip. *

* * * * * * * * * * * *
FileNamePattern valueRollover scheduleExample
/wombat/foo.%d.gzDaily rollover (at midnight) with automatic GZIP compression of the * archived files.During November 23rd, 2004, logging output will go to * the file /wombat/foo.2004-11-23. However, at midnight that * file will be compressed to become /wombat/foo.2004-11-23.gz. * For the 24th of November, logging output will be directed to * /wombat/folder/foo.2004-11-24 until its rolled over at the * beginning of the next day. *
* *

Decoupling the location of the active log file and the archived log files

*

The active file is defined as the log file for the current period * whereas archived files are those files which have been rolled over * in previous periods. * *

By setting the ActiveFileName option you can decouple the location * of the active log file and the location of the archived log files. *

* * * * * * * * * * * * * * *
FileNamePattern valueActiveFileNameRollover scheduleExample
/wombat/foo.log.%d/wombat/foo.logDaily rollover.During November 23rd, 2004, logging output will go to * the file /wombat/foo.log. However, at midnight that file * will archived as /wombat/foo.log.2004-11-23. For the 24th * of November, logging output will be directed to * /wombat/folder/foo.log until its archived as * /wombat/foo.log.2004-11-24 at the beginning of the next * day. *
*

* If configuring programatically, do not forget to call {@link #activateOptions} * method before using this policy. Moreover, {@link #activateOptions} of * TimeBasedRollingPolicy must be called before calling * the {@link #activateOptions} method of the owning * RollingFileAppender. * * @author Ceki Gülcü * @author Curt Arnold */ public final class TimeBasedRollingPolicy extends RollingPolicyBase implements TriggeringPolicy { /** * Time for next determination if time for rollover. */ private long nextCheck = 0; /** * File name at last rollover. */ private String lastFileName = null; /** * Length of any file type suffix (.gz, .zip). */ private int suffixLength = 0; /** * Constructs a new instance. */ public TimeBasedRollingPolicy() { } /** * Prepares instance of use. */ public void activateOptions() { super.activateOptions(); PatternConverter dtc = getDatePatternConverter(); if (dtc == null) { throw new IllegalStateException( "FileNamePattern [" + getFileNamePattern() + "] does not contain a valid date format specifier"); } long n = System.currentTimeMillis(); StringBuffer buf = new StringBuffer(); formatFileName(new Date(n), buf); lastFileName = buf.toString(); suffixLength = 0; if (lastFileName.endsWith(".gz")) { suffixLength = 3; } else if (lastFileName.endsWith(".zip")) { suffixLength = 4; } } /** * {@inheritDoc} */ public RolloverDescription initialize( final String currentActiveFile, final boolean append) { long n = System.currentTimeMillis(); nextCheck = ((n / 1000) + 1) * 1000; StringBuffer buf = new StringBuffer(); formatFileName(new Date(n), buf); lastFileName = buf.toString(); // // RollingPolicyBase.activeFileName duplicates RollingFileAppender.file // and should be removed. // if (activeFileName != null) { return new RolloverDescriptionImpl(activeFileName, append, null, null); } else if (currentActiveFile != null) { return new RolloverDescriptionImpl( currentActiveFile, append, null, null); } else { return new RolloverDescriptionImpl( lastFileName.substring(0, lastFileName.length() - suffixLength), append, null, null); } } /** * {@inheritDoc} */ public RolloverDescription rollover(final String currentActiveFile) { long n = System.currentTimeMillis(); nextCheck = ((n / 1000) + 1) * 1000; StringBuffer buf = new StringBuffer(); formatFileName(new Date(n), buf); String newFileName = buf.toString(); // // if file names haven't changed, no rollover // if (newFileName.equals(lastFileName)) { return null; } Action renameAction = null; Action compressAction = null; String lastBaseName = lastFileName.substring(0, lastFileName.length() - suffixLength); String nextActiveFile = newFileName.substring(0, newFileName.length() - suffixLength); // // if currentActiveFile is not lastBaseName then // active file name is not following file pattern // and requires a rename plus maintaining the same name if (!currentActiveFile.equals(lastBaseName)) { renameAction = new FileRenameAction( new File(currentActiveFile), new File(lastBaseName), true); nextActiveFile = currentActiveFile; } if (suffixLength == 3) { compressAction = new GZCompressAction( new File(lastBaseName), new File(lastFileName), true); } if (suffixLength == 4) { compressAction = new ZipCompressAction( new File(lastBaseName), new File(lastFileName), true); } lastFileName = newFileName; return new RolloverDescriptionImpl( nextActiveFile, false, renameAction, compressAction); } /** * {@inheritDoc} */ public boolean isTriggeringEvent( final Appender appender, final LoggingEvent event, final String filename, final long fileLength) { return System.currentTimeMillis() >= nextCheck; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rolling/TriggeringPolicy.java000066400000000000000000000035721252742764200310640ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rolling; import org.apache.log4j.Appender; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.OptionHandler; /** * A TriggeringPolicy controls the conditions under which rollover * occurs. Such conditions include time of day, file size, an * external event, the log request or a combination thereof. * * @author Ceki Gülcü * @author Curt Arnold * */ public interface TriggeringPolicy extends OptionHandler { /** * Determines if a rollover may be appropriate at this time. If * true is returned, RolloverPolicy.rollover will be called but it * can determine that a rollover is not warranted. * * @param appender A reference to the appender. * @param event A reference to the currently event. * @param filename The filename for the currently active log file. * @param fileLength Length of the file in bytes. * @return true if a rollover should occur. */ public boolean isTriggeringEvent( final Appender appender, final LoggingEvent event, final String filename, final long fileLength); } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rolling/helper/000077500000000000000000000000001252742764200262105ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rolling/helper/Action.java000066400000000000000000000032111252742764200302650ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rolling.helper; import java.io.IOException; /** * The Action interface should be implemented by any class that performs * file system actions for RollingFileAppenders after the close of * the active log file. * * @author Curt Arnold */ public interface Action extends Runnable { /** * Perform an action. * @return true if action was successful. A return value of false will cause * the rollover to be aborted if possible. * @throws IOException if IO error, a thrown exception will cause the rollover * to be aborted if possible. */ boolean execute() throws IOException; /** * Cancels the action if not already initialized or waits till completion. */ void close(); /** * Determines if action has been completed. * @return true if action is complete. */ boolean isComplete(); } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rolling/helper/ActionBase.java000066400000000000000000000037531252742764200310730ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rolling.helper; import java.io.IOException; /** * Abstract base class for implementations of Action. * * @author Curt Arnold */ public abstract class ActionBase implements Action { /** * Is action complete. */ private boolean complete = false; /** * Is action interrupted. */ private boolean interrupted = false; /** * Constructor. */ protected ActionBase() { } /** * Perform action. * * @throws IOException if IO error. * @return true if successful. */ public abstract boolean execute() throws IOException; /** * {@inheritDoc} */ public synchronized void run() { if (!interrupted) { try { execute(); } catch (IOException ex) { reportException(ex); } complete = true; interrupted = true; } } /** * {@inheritDoc} */ public synchronized void close() { interrupted = true; } /** * Tests if the action is complete. * @return true if action is complete. */ public boolean isComplete() { return complete; } /** * Capture exception. * * @param ex exception. */ protected void reportException(final Exception ex) { } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rolling/helper/CompositeAction.java000066400000000000000000000050571252742764200321620ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rolling.helper; import java.io.IOException; import java.util.List; import org.apache.log4j.helpers.LogLog; /** * A group of Actions to be executed in sequence. * * @author Curt Arnold * */ public class CompositeAction extends ActionBase { /** * Actions to perform. */ private final Action[] actions; /** * Stop on error. */ private final boolean stopOnError; /** * Construct a new composite action. * @param actions list of actions, may not be null. * @param stopOnError if true, stop on the first false return value or exception. */ public CompositeAction(final List actions, final boolean stopOnError) { this.actions = new Action[actions.size()]; actions.toArray(this.actions); this.stopOnError = stopOnError; } /** * {@inheritDoc} */ public void run() { try { execute(); } catch (IOException ex) { LogLog.warn("Exception during file rollover.", ex); } } /** * Execute sequence of actions. * @return true if all actions were successful. * @throws IOException on IO error. */ public boolean execute() throws IOException { if (stopOnError) { for (int i = 0; i < actions.length; i++) { if (!actions[i].execute()) { return false; } } return true; } else { boolean status = true; IOException exception = null; for (int i = 0; i < actions.length; i++) { try { status &= actions[i].execute(); } catch (IOException ex) { status = false; if (exception == null) { exception = ex; } } } if (exception != null) { throw exception; } return status; } } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rolling/helper/FileRenameAction.java000066400000000000000000000043501252742764200322220ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rolling.helper; import java.io.File; /** * File rename action. * * @author Curt Arnold */ public final class FileRenameAction extends ActionBase { /** * Source. */ private final File source; /** * Destination. */ private final File destination; /** * If true, rename empty files, otherwise delete empty files. */ private final boolean renameEmptyFiles; /** * Creates an FileRenameAction. * * @param src current file name. * @param dst new file name. * @param renameEmptyFiles if true, rename file even if empty, otherwise delete empty files. */ public FileRenameAction( final File src, final File dst, boolean renameEmptyFiles) { source = src; destination = dst; this.renameEmptyFiles = renameEmptyFiles; } /** * Rename file. * * @return true if successfully renamed. */ public boolean execute() { return execute(source, destination, renameEmptyFiles); } /** * Rename file. * @param source current file name. * @param destination new file name. * @param renameEmptyFiles if true, rename file even if empty, otherwise delete empty files. * @return true if successfully renamed. */ public static boolean execute( final File source, final File destination, boolean renameEmptyFiles) { if (renameEmptyFiles || (source.length() > 0)) { return source.renameTo(destination); } return source.delete(); } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rolling/helper/GZCompressAction.java000066400000000000000000000071411252742764200322500ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rolling.helper; import org.apache.log4j.helpers.LogLog; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.GZIPOutputStream; /** * Compresses a file using GZ compression. * * @author Curt Arnold */ public final class GZCompressAction extends ActionBase { /** * Source file. */ private final File source; /** * Destination file. */ private final File destination; /** * If true, attempt to delete file on completion. */ private final boolean deleteSource; /** * Create new instance of GZCompressAction. * * @param source file to compress, may not be null. * @param destination compressed file, may not be null. * @param deleteSource if true, attempt to delete file on completion. Failure to delete * does not cause an exception to be thrown or affect return value. */ public GZCompressAction( final File source, final File destination, final boolean deleteSource) { if (source == null) { throw new NullPointerException("source"); } if (destination == null) { throw new NullPointerException("destination"); } this.source = source; this.destination = destination; this.deleteSource = deleteSource; } /** * Compress. * @return true if successfully compressed. * @throws IOException on IO exception. */ public boolean execute() throws IOException { return execute(source, destination, deleteSource); } /** * Compress a file. * * @param source file to compress, may not be null. * @param destination compressed file, may not be null. * @param deleteSource if true, attempt to delete file on completion. Failure to delete * does not cause an exception to be thrown or affect return value. * @return true if source file compressed. * @throws IOException on IO exception. */ public static boolean execute( final File source, final File destination, final boolean deleteSource) throws IOException { if (source.exists()) { FileInputStream fis = new FileInputStream(source); FileOutputStream fos = new FileOutputStream(destination); GZIPOutputStream gzos = new GZIPOutputStream(fos); byte[] inbuf = new byte[8102]; int n; while ((n = fis.read(inbuf)) != -1) { gzos.write(inbuf, 0, n); } gzos.close(); fis.close(); if (deleteSource && !source.delete()) { LogLog.warn("Unable to delete " + source.toString() + "."); } return true; } return false; } /** * Capture exception. * * @param ex exception. */ protected void reportException(final Exception ex) { LogLog.warn("Exception during compression of '" + source.toString() + "'.", ex); } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rolling/helper/ZipCompressAction.java000066400000000000000000000073341252742764200324760ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rolling.helper; import org.apache.log4j.helpers.LogLog; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * Compresses a file using Zip compression. * * @author Curt Arnold */ public final class ZipCompressAction extends ActionBase { /** * Source file. */ private final File source; /** * Destination file. */ private final File destination; /** * If true, attempt to delete file on completion. */ private final boolean deleteSource; /** * Create new instance of GZCompressAction. * * @param source file to compress, may not be null. * @param destination compressed file, may not be null. * @param deleteSource if true, attempt to delete file on completion. Failure to delete * does not cause an exception to be thrown or affect return value. */ public ZipCompressAction( final File source, final File destination, final boolean deleteSource) { if (source == null) { throw new NullPointerException("source"); } if (destination == null) { throw new NullPointerException("destination"); } this.source = source; this.destination = destination; this.deleteSource = deleteSource; } /** * Compress. * @return true if successfully compressed. * @throws IOException on IO exception. */ public boolean execute() throws IOException { return execute(source, destination, deleteSource); } /** * Compress a file. * * @param source file to compress, may not be null. * @param destination compressed file, may not be null. * @param deleteSource if true, attempt to delete file on completion. Failure to delete * does not cause an exception to be thrown or affect return value. * @return true if source file compressed. * @throws IOException on IO exception. */ public static boolean execute( final File source, final File destination, final boolean deleteSource) throws IOException { if (source.exists()) { FileInputStream fis = new FileInputStream(source); FileOutputStream fos = new FileOutputStream(destination); ZipOutputStream zos = new ZipOutputStream(fos); ZipEntry zipEntry = new ZipEntry(source.getName()); zos.putNextEntry(zipEntry); byte[] inbuf = new byte[8102]; int n; while ((n = fis.read(inbuf)) != -1) { zos.write(inbuf, 0, n); } zos.close(); fis.close(); if (deleteSource && !source.delete()) { LogLog.warn("Unable to delete " + source.toString() + "."); } return true; } return false; } /** * Capture exception. * * @param ex exception. */ protected void reportException(final Exception ex) { LogLog.warn("Exception during compression of '" + source.toString() + "'.", ex); } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rolling/helper/package.html000066400000000000000000000017171252742764200304770ustar00rootroot00000000000000

Internal helper classes used by {@link org.apache.log4j.rolling} package.


apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rolling/package.html000066400000000000000000000023501252742764200272120ustar00rootroot00000000000000

Implements various file rolling policies.

The {@link org.apache.log4j.rolling.RollingFileAppender} class serves as the linchpin of this package. Its behaviour is controlled by two subcomponents of type {@link org.apache.log4j.rolling.RollingPolicy} and {@link org.apache.log4j.rolling.TriggeringPolicy}.

apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rule/000077500000000000000000000000001252742764200242325ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rule/AbstractRule.java000066400000000000000000000047121252742764200274740ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rule; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.Serializable; /** * An abstract Rule class that provides the PropertyChange support plumbing. * * @author Paul Smith (psmith@apache.org) * @author Scott Deboy (sdeboy@apache.org) */ public abstract class AbstractRule implements Rule, Serializable { /** * Serialization id. */ static final long serialVersionUID = -2844288145563025172L; /** * PropertySupport instance. */ private PropertyChangeSupport propertySupport = new PropertyChangeSupport(this); /** * Add property change listener. * @param l listener. */ public void addPropertyChangeListener(final PropertyChangeListener l) { propertySupport.addPropertyChangeListener(l); } /** * Remove property change listener. * @param l listener. */ public void removePropertyChangeListener(final PropertyChangeListener l) { propertySupport.removePropertyChangeListener(l); } /** * Send property change notification to attached listeners. * @param propertyName property name. * @param oldVal old value. * @param newVal new value. */ protected void firePropertyChange( final String propertyName, final Object oldVal, final Object newVal) { propertySupport.firePropertyChange(propertyName, oldVal, newVal); } /** * Send property change notification to attached listeners. * @param evt property change event. */ public void firePropertyChange(final PropertyChangeEvent evt) { propertySupport.firePropertyChange(evt); } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rule/AndRule.java000066400000000000000000000100751252742764200264320ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rule; import org.apache.log4j.spi.LoggingEvent; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.Stack; /** * A Rule class implementing a logical 'and'. * * @author Scott Deboy (sdeboy@apache.org) */ public class AndRule extends AbstractRule { /** * First rule. */ private final Rule firstRule; /** * Second rule. */ private final Rule secondRule; /** * Serialization id. */ static final long serialVersionUID = -8233444426923854651L; /** * Create new instance. * @param first first rule. * @param second second rule. */ private AndRule(final Rule first, final Rule second) { super(); this.firstRule = first; this.secondRule = second; } /** * Create rule from top two elements of stack. * @param stack stack of rules. * @return Rule that evaluates true only if both rules are true. */ public static Rule getRule(final Stack stack) { if (stack.size() < 2) { throw new IllegalArgumentException( "Invalid AND rule - expected two rules but received " + stack.size()); } Object o2 = stack.pop(); Object o1 = stack.pop(); if ((o2 instanceof Rule) && (o1 instanceof Rule)) { Rule p2 = (Rule) o2; Rule p1 = (Rule) o1; return new AndRule(p1, p2); } throw new IllegalArgumentException("Invalid AND rule: " + o2 + "..." + o1); } /** * Get rule. * @param firstParam first rule. * @param secondParam second rule. * @return Rule that evaluates true only if both rules are true. */ public static Rule getRule(final Rule firstParam, final Rule secondParam) { return new AndRule(firstParam, secondParam); } /** * {@inheritDoc} */ public boolean evaluate(final LoggingEvent event, Map matches) { if (matches == null) { return firstRule.evaluate(event, null) && secondRule.evaluate(event, null); } Map tempMatches1 = new HashMap(); Map tempMatches2 = new HashMap(); boolean result = firstRule.evaluate(event, tempMatches1) && secondRule.evaluate(event, tempMatches2); if (result) { for (Iterator iter = tempMatches1.entrySet().iterator();iter.hasNext();) { Map.Entry entry = (Map.Entry)iter.next(); Object key = entry.getKey(); Set value = (Set)entry.getValue(); Set mainSet = (Set) matches.get(key); if (mainSet == null) { mainSet = new HashSet(); matches.put(key, mainSet); } mainSet.addAll(value); } for (Iterator iter = tempMatches2.entrySet().iterator();iter.hasNext();) { Map.Entry entry = (Map.Entry)iter.next(); Object key = entry.getKey(); Set value = (Set)entry.getValue(); Set mainSet = (Set) matches.get(key); if (mainSet == null) { mainSet = new HashSet(); matches.put(key, mainSet); } mainSet.addAll(value); } } return result; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rule/ColorRule.java000066400000000000000000000061761252742764200270150ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rule; import java.awt.Color; import java.io.Serializable; import java.util.Map; import org.apache.log4j.spi.LoggingEvent; /** * A Rule class which also holds a color. * * @author Scott Deboy (sdeboy@apache.org) */ public class ColorRule extends AbstractRule implements Serializable { /** * Serialization id. */ static final long serialVersionUID = -794434783372847773L; /** * Wrapped rule. */ private final Rule rule; /** * Foreground color. */ private final Color foregroundColor; /** * Background color. */ private final Color backgroundColor; /** * Expression. */ private final String expression; /** * Create new instance. * @param expression expression. * @param rule rule. * @param backgroundColor background color. * @param foregroundColor foreground color. */ public ColorRule(final String expression, final Rule rule, final Color backgroundColor, final Color foregroundColor) { super(); this.expression = expression; this.rule = rule; this.backgroundColor = backgroundColor; this.foregroundColor = foregroundColor; } /** * Get rule. * @return underlying rule. */ public Rule getRule() { return rule; } /** * Get foreground color. * @return foreground color. */ public Color getForegroundColor() { return foregroundColor; } /** * Get background color. * @return background color. */ public Color getBackgroundColor() { return backgroundColor; } /** * Get expression. * @return expression. */ public String getExpression() { return expression; } /** * {@inheritDoc} */ public boolean evaluate(final LoggingEvent event, Map matches) { //no need for color rules to build matches return (rule != null && rule.evaluate(event, null)); } /** * {@inheritDoc} */ public String toString() { StringBuffer buf = new StringBuffer("color rule - expression: "); buf.append(expression); buf.append(", rule: "); buf.append(rule); buf.append(" bg: "); buf.append(backgroundColor); buf.append(" fg: "); buf.append(foregroundColor); return buf.toString(); } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rule/EqualsRule.java000066400000000000000000000066021252742764200271630ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rule; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.LoggingEventFieldResolver; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.Stack; /** * A Rule class which returns the result of * performing equals against two strings. * * @author Scott Deboy (sdeboy@apache.org) */ public class EqualsRule extends AbstractRule { /** * Serialization ID. */ static final long serialVersionUID = 1712851553477517245L; /** * Resolver. */ private static final LoggingEventFieldResolver RESOLVER = LoggingEventFieldResolver.getInstance(); /** * Value. */ private final String value; /** * Field. */ private final String field; /** * Create new instance. * @param field field * @param value value */ private EqualsRule(final String field, final String value) { super(); if (!RESOLVER.isField(field)) { throw new IllegalArgumentException( "Invalid EQUALS rule - " + field + " is not a supported field"); } this.field = field; this.value = value; } /** * Create new instance from top two elements of stack. * @param stack stack * @return new instance */ public static Rule getRule(final Stack stack) { if (stack.size() < 2) { throw new IllegalArgumentException( "Invalid EQUALS rule - expected two parameters but received " + stack.size()); } String p2 = stack.pop().toString(); String p1 = stack.pop().toString(); return getRule(p1, p2); } /** * Create new instance. * @param p1 field, special treatment for level and timestamp. * @param p2 value * @return new instance */ public static Rule getRule(final String p1, final String p2) { if (p1.equalsIgnoreCase(LoggingEventFieldResolver.LEVEL_FIELD)) { return LevelEqualsRule.getRule(p2); } else if (p1.equalsIgnoreCase(LoggingEventFieldResolver.TIMESTAMP_FIELD)) { return TimestampEqualsRule.getRule(p2); } else { return new EqualsRule(p1, p2); } } /** {@inheritDoc} */ public boolean evaluate(final LoggingEvent event, Map matches) { Object p2 = RESOLVER.getValue(field, event); boolean result = (p2 != null) && p2.toString().equals(value); if (result && matches != null) { Set entries = (Set) matches.get(field.toUpperCase()); if (entries == null) { entries = new HashSet(); matches.put(field.toUpperCase(), entries); } entries.add(value); } return result; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rule/ExistsRule.java000066400000000000000000000056451252742764200272160ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rule; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.LoggingEventFieldResolver; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.Stack; /** * A Rule class implementing a not null (and not empty string) check. * * @author Scott Deboy (sdeboy@apache.org) */ public class ExistsRule extends AbstractRule { /** * Serialization id. */ static final long serialVersionUID = -5386265224649967464L; /** * field resolver. */ private static final LoggingEventFieldResolver RESOLVER = LoggingEventFieldResolver.getInstance(); /** * field name. */ private final String field; /** * Create new instance. * @param fld field name. */ private ExistsRule(final String fld) { super(); if (!RESOLVER.isField(fld)) { throw new IllegalArgumentException( "Invalid EXISTS rule - " + fld + " is not a supported field"); } this.field = fld; } /** * Get an instance of ExistsRule. * @param field field. * @return instance of ExistsRule. */ public static Rule getRule(final String field) { return new ExistsRule(field); } /** * Create an instance of ExistsRule using the * top name on the stack. * @param stack stack * @return instance of ExistsRule. */ public static Rule getRule(final Stack stack) { if (stack.size() < 1) { throw new IllegalArgumentException( "Invalid EXISTS rule - expected one parameter but received " + stack.size()); } return new ExistsRule(stack.pop().toString()); } /** * {@inheritDoc} */ public boolean evaluate(final LoggingEvent event, Map matches) { Object p2 = RESOLVER.getValue(field, event); boolean result = !((p2 == null) || (p2.toString().equals(""))); if (result && matches != null) { Set entries = (Set) matches.get(field.toUpperCase()); if (entries == null) { entries = new HashSet(); matches.put(field.toUpperCase(), entries); } entries.add(p2); } return result; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rule/ExpressionRule.java000066400000000000000000000130501252742764200300630ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rule; import java.util.Map; import java.util.Stack; import org.apache.log4j.spi.LoggingEvent; /** * A Rule class supporting both infix and postfix expressions, * accepting any rule which * is supported by the RuleFactory. * * NOTE: parsing is supported through the use of * StringTokenizer, which * implies two limitations: * 1: all tokens in the expression must be separated by spaces, * including parenthesis * 2: operands which contain spaces MUST be wrapped in single quotes. * For example, the expression: * msg == 'some msg' * is a valid expression. * 3: To group expressions, use parentheses. * For example, the expression: * level >= INFO || ( msg == 'some msg' || logger == 'test' ) * is a valid expression. * See org.apache.log4j.rule.InFixToPostFix for a * description of supported operators. * See org.apache.log4j.spi.LoggingEventFieldResolver for field keywords. * * @author Scott Deboy (sdeboy@apache.org) */ public class ExpressionRule extends AbstractRule { /** * Serialization ID. */ static final long serialVersionUID = 5809121703146893729L; /** * Converter. */ private static final InFixToPostFix CONVERTER = new InFixToPostFix(); /** * Compiler. */ private static final PostFixExpressionCompiler COMPILER = new PostFixExpressionCompiler(); /** * Rule. */ private final Rule rule; /** * Create new instance. * @param r rule */ private ExpressionRule(final Rule r) { super(); this.rule = r; } /** * Get rule. * @param expression expression. * @return rule. */ public static Rule getRule(final String expression) { return getRule(expression, false); } /** * Get rule. * @param expression expression. * @param isPostFix If post-fix. * @return rule */ public static Rule getRule(final String expression, final boolean isPostFix) { String postFix = expression; if (!isPostFix) { postFix = CONVERTER.convert(expression); } return new ExpressionRule(COMPILER.compileExpression(postFix)); } /** * {@inheritDoc} */ public boolean evaluate(final LoggingEvent event, Map matches) { return rule.evaluate(event, matches); } /** * {@inheritDoc} */ public String toString() { return rule.toString(); } /** * Evaluate a boolean postfix expression. * */ static final class PostFixExpressionCompiler { /** * Compile expression. * @param expression expression. * @return rule. */ public Rule compileExpression(final String expression) { RuleFactory factory = RuleFactory.getInstance(); Stack stack = new Stack(); InFixToPostFix.CustomTokenizer tokenizer = new InFixToPostFix.CustomTokenizer(expression); while (tokenizer.hasMoreTokens()) { //examine each token String token = tokenizer.nextToken(); if (token.startsWith("'") || token.startsWith("\"")) { String quoteChar = token.substring(0, 1); token = token.substring(1); while (!token.endsWith(quoteChar) && tokenizer.hasMoreTokens()) { token = token + " " + tokenizer.nextToken(); } if (token.length() > 0) { token = token.substring(0, token.length() - 1); } } else { //if a symbol is found, pop 2 off the stack, // evaluate and push the result if (factory.isRule(token)) { Rule r = factory.getRule(token, stack); stack.push(r); //null out the token so we don't try to push it below token = null; } } //variables or constants are pushed onto the stack if (token != null && token.length() > 0) { stack.push(token); } } if ((stack.size() == 1) && (!(stack.peek() instanceof Rule))) { //while this may be an attempt at creating an expression, //for ease of use, convert this single entry to a partial-text //match on the MSG field Object o = stack.pop(); stack.push("MSG"); stack.push(o); return factory.getRule("~=", stack); } //stack should contain a single rule if the expression is valid if ((stack.size() != 1) || (!(stack.peek() instanceof Rule))) { throw new IllegalArgumentException("invalid expression: " + expression); } else { return (Rule) stack.pop(); } } } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rule/InFixToPostFix.java000066400000000000000000000270401252742764200277350ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rule; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Stack; import java.util.Vector; import org.apache.log4j.spi.LoggingEventFieldResolver; /** * A helper class which converts infix expressions to postfix expressions * Currently grouping is supported, as well as all of the * Rules supported by RuleFactory * * Supports grouping via parens, mult-word operands using single or double quotes, * and these operators: * * ! NOT operator * != NOT EQUALS operator * == EQUALS operator * ~= CASE-INSENSITIVE equals operator * || OR operator * && AND operator * like REGEXP operator * exists NOT NULL operator * < LESS THAN operator * > GREATER THAN operator * <= LESS THAN EQUALS operator * >= GREATER THAN EQUALS operator * * @author Scott Deboy (sdeboy@apache.org) */ public class InFixToPostFix { /** * Precedence map. */ private static final Map precedenceMap = new HashMap(); /** * Operators. */ private static final List operators = new Vector(); static { //order multi-char operators before single-char operators (will use this order during parsing) operators.add("<="); operators.add(">="); operators.add("!="); operators.add("=="); operators.add("~="); operators.add("||"); operators.add("&&"); operators.add("like"); operators.add("exists"); operators.add("!"); operators.add("<"); operators.add(">"); //boolean precedence precedenceMap.put("<", new Integer(3)); precedenceMap.put(">", new Integer(3)); precedenceMap.put("<=", new Integer(3)); precedenceMap.put(">=", new Integer(3)); precedenceMap.put("!", new Integer(3)); precedenceMap.put("!=", new Integer(3)); precedenceMap.put("==", new Integer(3)); precedenceMap.put("~=", new Integer(3)); precedenceMap.put("like", new Integer(3)); precedenceMap.put("exists", new Integer(3)); precedenceMap.put("||", new Integer(2)); precedenceMap.put("&&", new Integer(2)); } /** * Convert in-fix expression to post-fix. * @param expression in-fix expression. * @return post-fix expression. */ public String convert(final String expression) { return infixToPostFix(new CustomTokenizer(expression)); } /** * Evaluates whether symbol is operand. * @param s symbol. * @return true if operand. */ public static boolean isOperand(final String s) { String symbol = s.toLowerCase(Locale.ENGLISH); return (!operators.contains(symbol)); } /** * Determines whether one symbol precedes another. * @param s1 symbol 1 * @param s2 symbol 2 * @return true if symbol 1 precedes symbol 2 */ boolean precedes(final String s1, final String s2) { String symbol1 = s1.toLowerCase(Locale.ENGLISH); String symbol2 = s2.toLowerCase(Locale.ENGLISH); if (!precedenceMap.keySet().contains(symbol1)) { return false; } if (!precedenceMap.keySet().contains(symbol2)) { return false; } int index1 = ((Integer) precedenceMap.get(symbol1)).intValue(); int index2 = ((Integer) precedenceMap.get(symbol2)).intValue(); boolean precedesResult = (index1 < index2); return precedesResult; } /** * convert in-fix expression to post-fix. * @param tokenizer tokenizer. * @return post-fix expression. */ String infixToPostFix(final CustomTokenizer tokenizer) { final String space = " "; StringBuffer postfix = new StringBuffer(); Stack stack = new Stack(); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); boolean inText = (token.startsWith("'") && (!token.endsWith("'"))) || (token.startsWith("\"") && (!token.endsWith("\""))); String quoteChar = token.substring(0, 1); if (inText) { while (inText && tokenizer.hasMoreTokens()) { token = token + " " + tokenizer.nextToken(); inText = !(token.endsWith(quoteChar)); } } if ("(".equals(token)) { //recurse postfix.append(infixToPostFix(tokenizer)); postfix.append(space); } else if (")".equals(token)) { //exit recursion level while (stack.size() > 0) { postfix.append(stack.pop().toString()); postfix.append(space); } return postfix.toString(); } else if (isOperand(token)) { postfix.append(token); postfix.append(space); } else { //operator.. //peek the stack..if the top element has a lower precedence than token //(peeked + has lower precedence than token *), // push token onto the stack //otherwise, pop top element off stack and add to postfix string //in a loop until lower precedence or empty..then push token if (stack.size() > 0) { String peek = stack.peek().toString(); if (precedes(peek, token)) { stack.push(token); } else { boolean bypass = false; do { if ( (stack.size() > 0) && !precedes(stack.peek().toString(), token)) { postfix.append(stack.pop().toString()); postfix.append(space); } else { bypass = true; } } while (!bypass); stack.push(token); } } else { stack.push(token); } } } while (stack.size() > 0) { postfix.append(stack.pop().toString()); postfix.append(space); } return postfix.toString(); } public static class CustomTokenizer { private LinkedList linkedList = new LinkedList(); public CustomTokenizer(String input) { parseInput(input, linkedList); } public void parseInput(String input, LinkedList linkedList) { /* Operators: ! != == ~= || && like exists < <= > >= */ //for operators, handle multi-char matches before single-char matches //order does not matter for keywords List keywords = LoggingEventFieldResolver.KEYWORD_LIST; //remove PROP. from the keyword list...it is a keyword in that list, but is handled separately here from the other keywords since its name is not fixed keywords.remove("PROP."); int pos = 0; while (pos < input.length()) { if (nextValueIs(input, pos, "'") || nextValueIs(input, pos, "\"")) { pos = handleQuotedString(input, pos, linkedList); } if (nextValueIs(input, pos, "PROP.")) { pos = handleProperty(input, pos, linkedList); } boolean operatorFound = false; for (Iterator iter = operators.iterator();iter.hasNext();) { String operator = (String)iter.next(); if (nextValueIs(input, pos, operator)) { operatorFound = true; pos = handle(pos, linkedList, operator); } } boolean keywordFound = false; for (Iterator iter = keywords.iterator();iter.hasNext();) { String keyword = (String)iter.next(); if (nextValueIs(input, pos, keyword)) { keywordFound = true; pos = handle(pos, linkedList, keyword); } } if (operatorFound || keywordFound) { continue; } if (nextValueIs(input, pos, ")")) { pos = handle(pos, linkedList, ")"); } else if (nextValueIs(input, pos, "(")) { pos = handle(pos, linkedList, "("); } else if (nextValueIs(input, pos, " ")) { pos++; } else { pos = handleText(input, pos, linkedList); } } } private boolean nextValueIs(String input, int pos, String value) { return (input.length() >= (pos + value.length())) && (input.substring(pos, pos + value.length()).equalsIgnoreCase(value)); } private int handle(int pos, LinkedList linkedList, String value) { linkedList.add(value); return pos + value.length(); } private int handleQuotedString(String input, int pos, LinkedList linkedList) { String quoteChar = input.substring(pos, pos + 1); int nextSingleQuotePos = input.indexOf(quoteChar, pos + 1); if (nextSingleQuotePos < 0) { throw new IllegalArgumentException("Missing an end quote"); } String result = input.substring(pos, nextSingleQuotePos + 1); linkedList.add(result); return nextSingleQuotePos + 1; } private int handleText(String input, int pos, LinkedList linkedList) { StringBuffer text = new StringBuffer(""); int newPos = pos; while (newPos < input.length()) { if (nextValueIs(input, newPos, " ")) { linkedList.add(text); return newPos; } if (nextValueIs(input, newPos, "(")) { linkedList.add(text); return newPos; } if (nextValueIs(input, newPos, ")")) { linkedList.add(text); return newPos; } for (Iterator iter = operators.iterator();iter.hasNext();) { String operator = (String)iter.next(); if (nextValueIs(input, newPos, operator)) { linkedList.add(text); return newPos; } } text.append(input.substring(newPos, ++newPos)); } //don't add empty text entry (may be at end) if (!text.toString().trim().equals("")) { linkedList.add(text); } return newPos; } private int handleProperty(String input, int pos, LinkedList linkedList) { int propertyPos = pos + "PROP.".length(); StringBuffer propertyName = new StringBuffer("PROP."); while (propertyPos < input.length()) { if (nextValueIs(input, propertyPos, " ")) { linkedList.add(propertyName); return propertyPos; } if (nextValueIs(input, propertyPos, "(")) { linkedList.add(propertyName); return propertyPos; } if (nextValueIs(input, propertyPos, ")")) { linkedList.add(propertyName); return propertyPos; } for (Iterator iter = operators.iterator();iter.hasNext();) { String operator = (String)iter.next(); if (nextValueIs(input, propertyPos, operator)) { linkedList.add(propertyName); return propertyPos; } } propertyName.append(input.substring(propertyPos, ++propertyPos)); } linkedList.add(propertyName); return propertyPos; } public boolean hasMoreTokens() { return linkedList.size() > 0; } public String nextToken() { return linkedList.remove().toString(); } } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rule/InequalityRule.java000066400000000000000000000117171252742764200300600ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rule; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.LoggingEventFieldResolver; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.Stack; /** * A Rule class implementing inequality evaluation. * expects to be able to convert two values to longs. * If a specific inequality evaluation class has been provided * for the event field, the appropriate rule is returned. * (For example, if the expression is Level < DEBUG, * a LevelInequalityRule is returned). * * @author Scott Deboy (sdeboy@apache.org) */ public class InequalityRule extends AbstractRule { /** * Serialization ID. */ static final long serialVersionUID = -5592986598528885122L; /** * field RESOLVER. */ private static final LoggingEventFieldResolver RESOLVER = LoggingEventFieldResolver.getInstance(); /** * Field name. */ private final String field; /** * Comparison value. */ private final String value; /** * Inequality symbol. */ private final String inequalitySymbol; /** * Create new instance. * @param inequalitySymbol inequality symbol. * @param field field * @param value comparison value. */ private InequalityRule( final String inequalitySymbol, final String field, final String value) { super(); this.inequalitySymbol = inequalitySymbol; if (!RESOLVER.isField(field)) { throw new IllegalArgumentException("Invalid " + inequalitySymbol + " rule - " + field + " is not a supported field"); } this.field = field; this.value = value; } /** * Create new instance from top two elements on stack. * @param inequalitySymbol inequality symbol. * @param stack stack. * @return rule. */ public static Rule getRule(final String inequalitySymbol, final Stack stack) { if (stack.size() < 2) { throw new IllegalArgumentException("Invalid " + inequalitySymbol + " rule - expected two parameters but received " + stack.size()); } String p2 = stack.pop().toString(); String p1 = stack.pop().toString(); return getRule(inequalitySymbol, p1, p2); } /** * Create new instance from top two elements on stack. * @param inequalitySymbol inequality symbol. * @param field field. * @param value comparison value. * @return rule. */ public static Rule getRule(final String inequalitySymbol, final String field, final String value) { if (field.equalsIgnoreCase(LoggingEventFieldResolver.LEVEL_FIELD)) { //push the value back on the stack and // allow the level-specific rule pop values return LevelInequalityRule.getRule(inequalitySymbol, value); } else if ( field.equalsIgnoreCase(LoggingEventFieldResolver.TIMESTAMP_FIELD)) { return TimestampInequalityRule.getRule(inequalitySymbol, value); } else { return new InequalityRule(inequalitySymbol, field, value); } } /** {@inheritDoc} */ public boolean evaluate(final LoggingEvent event, Map matches) { long first = 0; try { first = new Long(RESOLVER.getValue(field, event).toString()).longValue(); } catch (NumberFormatException nfe) { return false; } long second = 0; try { second = new Long(value).longValue(); } catch (NumberFormatException nfe) { return false; } boolean result = false; if ("<".equals(inequalitySymbol)) { result = first < second; } else if (">".equals(inequalitySymbol)) { result = first > second; } else if ("<=".equals(inequalitySymbol)) { result = first <= second; } else if (">=".equals(inequalitySymbol)) { result = first >= second; } if (result && matches != null) { Set entries = (Set) matches.get(field.toUpperCase()); if (entries == null) { entries = new HashSet(); matches.put(field.toUpperCase(), entries); } entries.add(String.valueOf(first)); } return result; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rule/LevelEqualsRule.java000066400000000000000000000105421252742764200301510ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rule; import java.io.IOException; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.log4j.Level; import org.apache.log4j.helpers.UtilLoggingLevel; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.LoggingEventFieldResolver; /** * A Rule class implementing equals against two levels. * * @author Scott Deboy (sdeboy@apache.org) */ public class LevelEqualsRule extends AbstractRule { /** * Serialization ID. */ static final long serialVersionUID = -3638386582899583994L; /** * Level. */ private transient Level level; /** * List of levels. */ private static List levelList = new LinkedList(); static { populateLevels(); } /** * Create new instance. * @param level level. */ private LevelEqualsRule(final Level level) { super(); this.level = level; } /** * Populate list of levels. */ private static void populateLevels() { levelList = new LinkedList(); levelList.add(Level.FATAL.toString()); levelList.add(Level.ERROR.toString()); levelList.add(Level.WARN.toString()); levelList.add(Level.INFO.toString()); levelList.add(Level.DEBUG.toString()); Level trace = Level.toLevel(5000, null); if (trace != null) { levelList.add(trace.toString()); } } /** * Create new rule. * @param value name of level. * @return instance of LevelEqualsRule. */ public static Rule getRule(final String value) { Level thisLevel; if (levelList.contains(value.toUpperCase())) { thisLevel = Level.toLevel(value.toUpperCase()); } else { thisLevel = UtilLoggingLevel.toLevel(value.toUpperCase()); } return new LevelEqualsRule(thisLevel); } /** * {@inheritDoc} */ public boolean evaluate(final LoggingEvent event, Map matches) { //both util.logging and log4j contain 'info' - use the int values instead of equality //info level set to the same value for both levels Level eventLevel = event.getLevel(); boolean result = (level.toInt() == eventLevel.toInt()); if (result && matches != null) { Set entries = (Set) matches.get(LoggingEventFieldResolver.LEVEL_FIELD); if (entries == null) { entries = new HashSet(); matches.put(LoggingEventFieldResolver.LEVEL_FIELD, entries); } entries.add(eventLevel); } return result; } /** * Deserialize the state of the object. * * @param in object input stream. * * @throws IOException if error in reading stream for deserialization. */ private void readObject(final java.io.ObjectInputStream in) throws IOException { populateLevels(); boolean isUtilLogging = in.readBoolean(); int levelInt = in.readInt(); if (isUtilLogging) { level = UtilLoggingLevel.toLevel(levelInt); } else { level = Level.toLevel(levelInt); } } /** * Serialize the state of the object. * * @param out object output stream. * * @throws IOException if error in writing stream during serialization. */ private void writeObject(final java.io.ObjectOutputStream out) throws IOException { out.writeBoolean(level instanceof UtilLoggingLevel); out.writeInt(level.toInt()); } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rule/LevelInequalityRule.java000066400000000000000000000210571252742764200310460ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rule; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.log4j.Level; import org.apache.log4j.helpers.UtilLoggingLevel; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.LoggingEventFieldResolver; /** * A Rule class implementing inequality evaluation for Levels (log4j and * util.logging) using the toInt method. * * @author Scott Deboy (sdeboy@apache.org) */ public class LevelInequalityRule { /** * Level list. */ private static List levelList; /** * List equivalents of java.util.logging levels. */ private static List utilLoggingLevelList; static { populateLevels(); } /** * Create new instance. */ private LevelInequalityRule() { super(); } /** * Populate list of levels. */ private static void populateLevels() { levelList = new LinkedList(); levelList.add(Level.FATAL.toString()); levelList.add(Level.ERROR.toString()); levelList.add(Level.WARN.toString()); levelList.add(Level.INFO.toString()); levelList.add(Level.DEBUG.toString()); Level trace = Level.toLevel(5000, null); if (trace != null) { levelList.add(trace.toString()); } utilLoggingLevelList = new LinkedList(); utilLoggingLevelList.add(UtilLoggingLevel.SEVERE.toString()); utilLoggingLevelList.add(UtilLoggingLevel.WARNING.toString()); utilLoggingLevelList.add(UtilLoggingLevel.INFO.toString()); utilLoggingLevelList.add(UtilLoggingLevel.CONFIG.toString()); utilLoggingLevelList.add(UtilLoggingLevel.FINE.toString()); utilLoggingLevelList.add(UtilLoggingLevel.FINER.toString()); utilLoggingLevelList.add(UtilLoggingLevel.FINEST.toString()); } /** * Create new rule. * @param inequalitySymbol inequality symbol. * @param value Symbolic name of comparison level. * @return instance of AbstractRule. */ public static Rule getRule(final String inequalitySymbol, final String value) { Level thisLevel; //if valid util.logging levels are used against events // with log4j levels, the //DEBUG level is used and an illegalargumentexception won't be generated //an illegalargumentexception is only generated // if the user types a level name //that doesn't exist as either a log4j or util.logging level name if (levelList.contains(value.toUpperCase())) { thisLevel = Level.toLevel(value.toUpperCase()); } else if (utilLoggingLevelList.contains(value.toUpperCase())) { thisLevel = UtilLoggingLevel.toLevel(value.toUpperCase()); } else { throw new IllegalArgumentException( "Invalid level inequality rule - " + value + " is not a supported level"); } if ("<".equals(inequalitySymbol)) { return new LessThanRule(thisLevel); } if (">".equals(inequalitySymbol)) { return new GreaterThanRule(thisLevel); } if ("<=".equals(inequalitySymbol)) { return new LessThanEqualsRule(thisLevel); } if (">=".equals(inequalitySymbol)) { return new GreaterThanEqualsRule(thisLevel); } return null; } /** * Rule returning true if event level less than specified level. */ private static final class LessThanRule extends AbstractRule { /** * Comparison level. */ private final int newLevelInt; /** * Create new instance. * @param level comparison level. */ public LessThanRule(final Level level) { super(); newLevelInt = level.toInt(); } /** {@inheritDoc} */ public boolean evaluate(final LoggingEvent event, Map matches) { Level eventLevel = event.getLevel(); boolean result = (eventLevel.toInt() < newLevelInt); if (result && matches != null) { Set entries = (Set) matches.get(LoggingEventFieldResolver.LEVEL_FIELD); if (entries == null) { entries = new HashSet(); matches.put(LoggingEventFieldResolver.LEVEL_FIELD, entries); } entries.add(eventLevel); } return result; } } /** * Rule returning true if event level greater than specified level. */ private static final class GreaterThanRule extends AbstractRule { /** * Comparison level. */ private final int newLevelInt; /** * Create new instance. * @param level comparison level. */ public GreaterThanRule(final Level level) { super(); newLevelInt = level.toInt(); } /** {@inheritDoc} */ public boolean evaluate(final LoggingEvent event, Map matches) { Level eventLevel = event.getLevel(); boolean result = (eventLevel.toInt() > newLevelInt); if (result && matches != null) { Set entries = (Set) matches.get(LoggingEventFieldResolver.LEVEL_FIELD); if (entries == null) { entries = new HashSet(); matches.put(LoggingEventFieldResolver.LEVEL_FIELD, entries); } entries.add(eventLevel); } return result; } } /** * Rule returning true if event level greater than * or equal to specified level. */ private static final class GreaterThanEqualsRule extends AbstractRule { /** * Comparison level. */ private final int newLevelInt; /** * Create new instance. * @param level comparison level. */ public GreaterThanEqualsRule(final Level level) { super(); newLevelInt = level.toInt(); } /** {@inheritDoc} */ public boolean evaluate(final LoggingEvent event, Map matches) { Level eventLevel = event.getLevel(); boolean result = eventLevel.toInt() >= newLevelInt; if (result && matches != null) { Set entries = (Set) matches.get(LoggingEventFieldResolver.LEVEL_FIELD); if (entries == null) { entries = new HashSet(); matches.put(LoggingEventFieldResolver.LEVEL_FIELD, entries); } entries.add(eventLevel); } return result; } } /** * Rule returning true if event level less than or * equal to specified level. */ private static final class LessThanEqualsRule extends AbstractRule { /** * Comparison level. */ private final int newLevelInt; /** * Create new instance. * @param level comparison level. */ public LessThanEqualsRule(final Level level) { super(); newLevelInt = level.toInt(); } /** {@inheritDoc} */ public boolean evaluate(final LoggingEvent event, Map matches) { Level eventLevel = event.getLevel(); boolean result = eventLevel.toInt() <= newLevelInt; if (result && matches != null) { Set entries = (Set) matches.get(LoggingEventFieldResolver.LEVEL_FIELD); if (entries == null) { entries = new HashSet(); matches.put(LoggingEventFieldResolver.LEVEL_FIELD, entries); } entries.add(eventLevel); } return result; } } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rule/LikeRule.java000066400000000000000000000116461252742764200266210ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rule; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.LoggingEventFieldResolver; import java.io.IOException; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.Stack; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /** * A Rule class supporting java.util.regex regular expression syntax. * * @author Scott Deboy (sdeboy@apache.org) */ public class LikeRule extends AbstractRule { /** * Serialization ID. */ static final long serialVersionUID = -3375458885595683156L; /** * Resolver. */ private static final LoggingEventFieldResolver RESOLVER = LoggingEventFieldResolver.getInstance(); /** * Pattern. */ private transient Pattern pattern; /** * Regular expression matcher. */ private transient Matcher matcher = null; /** * Field. */ private transient String field; /** * Create new instance. * @param field field * @param pattern pattern */ private LikeRule(final String field, final Pattern pattern) { super(); if (!RESOLVER.isField(field)) { throw new IllegalArgumentException( "Invalid LIKE rule - " + field + " is not a supported field"); } this.field = field; this.pattern = pattern; } /** * Create new instance from top two elements of stack. * @param stack stack * @return new instance */ public static Rule getRule(final Stack stack) { if (stack.size() < 2) { throw new IllegalArgumentException( "Invalid LIKE rule - expected two parameters but received " + stack.size()); } String p2 = stack.pop().toString(); String p1 = stack.pop().toString(); return getRule(p1, p2); } /** * Create new instance. * @param field field * @param pattern pattern * @return new instance */ public static Rule getRule(final String field, final String pattern) { try { return new LikeRule(field, Pattern.compile(pattern, Pattern.CASE_INSENSITIVE)); } catch (PatternSyntaxException e) { throw new IllegalArgumentException( "Invalid LIKE rule - " + e.getMessage()); } } /** {@inheritDoc} */ public boolean evaluate(final LoggingEvent event, Map matches) { //no need to figure out what part of the string matched, just set the entire string as a match Object input = RESOLVER.getValue(field, event); if((input != null) && (pattern != null)) { if (matcher == null) { matcher = pattern.matcher(input.toString()); } else { matcher.reset(input.toString()); } boolean result = matcher.matches(); if (result && matches != null) { Set entries = (Set) matches.get(field.toUpperCase()); if (entries == null) { entries = new HashSet(); matches.put(field.toUpperCase(), entries); } entries.add(input); } return result; } return false; } /** * Deserialize the state of the object. * * @param in object input stream * * @throws IOException if IOException during deserialization * @throws ClassNotFoundException if class not found. */ private void readObject(final java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { try { field = (String) in.readObject(); String patternString = (String) in.readObject(); pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE); } catch (PatternSyntaxException e) { throw new IOException("Invalid LIKE rule - " + e.getMessage()); } } /** * Serialize the state of the object. * * @param out object output stream * * @throws IOException if IOException during serialization */ private void writeObject(final java.io.ObjectOutputStream out) throws IOException { out.writeObject(field); out.writeObject(pattern.pattern()); } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rule/NotEqualsRule.java000066400000000000000000000066711252742764200276520ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rule; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.Stack; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.LoggingEventFieldResolver; /** * A Rule class implementing not equals against two strings. * * @author Scott Deboy (sdeboy@apache.org) */ public class NotEqualsRule extends AbstractRule { /** * Serialization ID. */ static final long serialVersionUID = -1135478467213793211L; /** * Resolver. */ private static final LoggingEventFieldResolver RESOLVER = LoggingEventFieldResolver.getInstance(); /** * Field. */ private final String field; /** * Value. */ private final String value; /** * Create new instance. * @param field field * @param value value */ private NotEqualsRule(final String field, final String value) { super(); if (!RESOLVER.isField(field)) { throw new IllegalArgumentException( "Invalid NOT EQUALS rule - " + field + " is not a supported field"); } this.field = field; this.value = value; } /** * Get new instance. * @param field field * @param value value * @return new instance. */ public static Rule getRule(final String field, final String value) { if (field.equalsIgnoreCase(LoggingEventFieldResolver.LEVEL_FIELD)) { return NotLevelEqualsRule.getRule(value); } else { return new NotEqualsRule(field, value); } } /** * Get new instance from top two elements of stack. * @param stack stack. * @return new instance. */ public static Rule getRule(final Stack stack) { if (stack.size() < 2) { throw new IllegalArgumentException( "Invalid NOT EQUALS rule - expected two parameters but received " + stack.size()); } String p2 = stack.pop().toString(); String p1 = stack.pop().toString(); if (p1.equalsIgnoreCase(LoggingEventFieldResolver.LEVEL_FIELD)) { return NotLevelEqualsRule.getRule(p2); } else { return new NotEqualsRule(p1, p2); } } /** {@inheritDoc} */ public boolean evaluate(final LoggingEvent event, Map matches) { Object p2 = RESOLVER.getValue(field, event); boolean result = (p2 != null) && !(p2.toString().equals(value)); if (result && matches != null) { //not equals - add the text that isn't equal (p2) Set entries = (Set) matches.get(field.toUpperCase()); if (entries == null) { entries = new HashSet(); matches.put(field.toUpperCase(), entries); } entries.add(value); } return result; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rule/NotLevelEqualsRule.java000066400000000000000000000105601252742764200306320ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rule; import java.io.IOException; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.log4j.Level; import org.apache.log4j.helpers.UtilLoggingLevel; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.LoggingEventFieldResolver; /** * A Rule class implementing not equals against two levels. * * @author Scott Deboy (sdeboy@apache.org) */ public class NotLevelEqualsRule extends AbstractRule { /** * Serialization ID. */ static final long serialVersionUID = -3638386582899583994L; /** * Level. */ private transient Level level; /** * List of levels. */ private static List levelList = new LinkedList(); static { populateLevels(); } /** * Create new instance. * @param level level. */ private NotLevelEqualsRule(final Level level) { super(); this.level = level; } /** * Populate list of levels. */ private static void populateLevels() { levelList = new LinkedList(); levelList.add(Level.FATAL.toString()); levelList.add(Level.ERROR.toString()); levelList.add(Level.WARN.toString()); levelList.add(Level.INFO.toString()); levelList.add(Level.DEBUG.toString()); Level trace = Level.toLevel(5000, null); if (trace != null) { levelList.add(trace.toString()); } } /** * Create new rule. * @param value name of level. * @return instance of NotLevelEqualsRule. */ public static Rule getRule(final String value) { Level thisLevel; if (levelList.contains(value.toUpperCase())) { thisLevel = Level.toLevel(value.toUpperCase()); } else { thisLevel = UtilLoggingLevel.toLevel(value.toUpperCase()); } return new NotLevelEqualsRule(thisLevel); } /** * {@inheritDoc} */ public boolean evaluate(final LoggingEvent event, Map matches) { //both util.logging and log4j contain 'info' - use the int values instead of equality //info level set to the same value for both levels Level eventLevel = event.getLevel(); boolean result = level.toInt() != eventLevel.toInt(); if (result && matches != null) { Set entries = (Set) matches.get(LoggingEventFieldResolver.LEVEL_FIELD); if (entries == null) { entries = new HashSet(); matches.put(LoggingEventFieldResolver.LEVEL_FIELD, entries); } entries.add(eventLevel); } return result; } /** * Deserialize the state of the object. * * @param in object input stream. * * @throws IOException if error in reading stream for deserialization. */ private void readObject(final java.io.ObjectInputStream in) throws IOException { populateLevels(); boolean isUtilLogging = in.readBoolean(); int levelInt = in.readInt(); if (isUtilLogging) { level = UtilLoggingLevel.toLevel(levelInt); } else { level = Level.toLevel(levelInt); } } /** * Serialize the state of the object. * * @param out object output stream. * * @throws IOException if error in writing stream during serialization. */ private void writeObject(final java.io.ObjectOutputStream out) throws IOException { out.writeBoolean(level instanceof UtilLoggingLevel); out.writeInt(level.toInt()); } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rule/NotRule.java000066400000000000000000000057701252742764200264760ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rule; import org.apache.log4j.spi.LoggingEvent; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.Stack; /** * A Rule class implementing logical not. * * @author Scott Deboy (sdeboy@apache.org) */ public class NotRule extends AbstractRule { /** * Serialization ID. */ static final long serialVersionUID = -6827159473117969306L; /** * Enclosed rule. */ private final Rule rule; /** * Create new instance. * @param rule enclosed rule. */ private NotRule(final Rule rule) { super(); this.rule = rule; } /** * Create new instance. * @param rule enclosed rule. * @return new rule. */ public static Rule getRule(final Rule rule) { return new NotRule(rule); } /** * Create new instance from top element of stack. * @param stack stack * @return new rule. */ public static Rule getRule(final Stack stack) { if (stack.size() < 1) { throw new IllegalArgumentException( "Invalid NOT rule - expected one rule but received " + stack.size()); } Object o1 = stack.pop(); if (o1 instanceof Rule) { Rule p1 = (Rule) o1; return new NotRule(p1); } throw new IllegalArgumentException( "Invalid NOT rule: - expected rule but received " + o1); } /** {@inheritDoc} */ public boolean evaluate(final LoggingEvent event, Map matches) { if (matches == null) { return !(rule.evaluate(event, null)); } Map tempMatches = new HashMap(); boolean result = !(rule.evaluate(event, tempMatches)); if (result) { for (Iterator iter = tempMatches.entrySet().iterator();iter.hasNext();) { Map.Entry entry = (Map.Entry)iter.next(); Object key = entry.getKey(); Set value = (Set)entry.getValue(); Set mainSet = (Set) matches.get(key); if (mainSet == null) { mainSet = new HashSet(); matches.put(key, mainSet); } mainSet.addAll(value); } } return result; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rule/OrRule.java000066400000000000000000000100551252742764200263060ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rule; import org.apache.log4j.spi.LoggingEvent; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.Stack; /** * A Rule class implementing logical or. * * @author Scott Deboy (sdeboy@apache.org) */ public class OrRule extends AbstractRule { /** * Serialization ID. */ static final long serialVersionUID = 2088765995061413165L; /** * rule 1. */ private final Rule rule1; /** * Rule 2. */ private final Rule rule2; /** * Create new instance. * @param firstParam first rule * @param secondParam second rule */ private OrRule(final Rule firstParam, final Rule secondParam) { super(); this.rule1 = firstParam; this.rule2 = secondParam; } /** * Create new instance. * @param firstParam first rule * @param secondParam second rule * @return new instance */ public static Rule getRule(final Rule firstParam, final Rule secondParam) { return new OrRule(firstParam, secondParam); } /** * Create new instance from top two elements of stack. * @param stack stack * @return new instance */ public static Rule getRule(final Stack stack) { if (stack.size() < 2) { throw new IllegalArgumentException( "Invalid OR rule - expected two rules but received " + stack.size()); } Object o2 = stack.pop(); Object o1 = stack.pop(); if ((o2 instanceof Rule) && (o1 instanceof Rule)) { Rule p2 = (Rule) o2; Rule p1 = (Rule) o1; return new OrRule(p1, p2); } throw new IllegalArgumentException("Invalid OR rule: " + o2 + "..." + o1); } /** {@inheritDoc} */ public boolean evaluate(final LoggingEvent event, Map matches) { if (matches == null) { return (rule1.evaluate(event, null) || rule2.evaluate(event, null)); } Map tempMatches1 = new HashMap(); Map tempMatches2 = new HashMap(); //not short-circuiting because we want to build the matches list boolean result1 = rule1.evaluate(event, tempMatches1); boolean result2 = rule2.evaluate(event, tempMatches2); boolean result = result1 || result2; if (result) { for (Iterator iter = tempMatches1.entrySet().iterator();iter.hasNext();) { Map.Entry entry = (Map.Entry)iter.next(); Object key = entry.getKey(); Set value = (Set)entry.getValue(); Set mainSet = (Set) matches.get(key); if (mainSet == null) { mainSet = new HashSet(); matches.put(key, mainSet); } mainSet.addAll(value); } for (Iterator iter = tempMatches2.entrySet().iterator();iter.hasNext();) { Map.Entry entry = (Map.Entry)iter.next(); Object key = entry.getKey(); Set value = (Set)entry.getValue(); Set mainSet = (Set) matches.get(key); if (mainSet == null) { mainSet = new HashSet(); matches.put(key, mainSet); } mainSet.addAll(value); } } return result; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rule/PartialTextMatchRule.java000066400000000000000000000063261252742764200311520ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rule; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.LoggingEventFieldResolver; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.Stack; /** * A Rule class implementing case-insensitive * partial-text matches against two strings. * * @author Scott Deboy (sdeboy@apache.org) */ public class PartialTextMatchRule extends AbstractRule { /** * Serialization ID. */ static final long serialVersionUID = 6963284773637727558L; /** * Resolver. */ private static final LoggingEventFieldResolver RESOLVER = LoggingEventFieldResolver.getInstance(); /** * Field. */ private final String field; /** * Value. */ private final String value; /** * Create new instance. * @param field field * @param value value */ private PartialTextMatchRule(final String field, final String value) { super(); if (!RESOLVER.isField(field)) { throw new IllegalArgumentException( "Invalid partial text rule - " + field + " is not a supported field"); } this.field = field; this.value = value; } /** * Create new instance. * @param field field * @param value value * @return new instance */ public static Rule getRule(final String field, final String value) { return new PartialTextMatchRule(field, value); } /** * Create new instance from top two elements of stack. * @param stack stack * @return new instance */ public static Rule getRule(final Stack stack) { if (stack.size() < 2) { throw new IllegalArgumentException( "invalid partial text rule - expected two parameters but received " + stack.size()); } String p2 = stack.pop().toString(); String p1 = stack.pop().toString(); return new PartialTextMatchRule(p1, p2); } /** {@inheritDoc} */ public boolean evaluate(final LoggingEvent event, Map matches) { Object p2 = RESOLVER.getValue(field, event); boolean result = ((p2 != null) && (value != null) && (p2.toString().toLowerCase().indexOf(value.toLowerCase()) > -1)); if (result && matches != null) { Set entries = (Set) matches.get(field.toUpperCase()); if (entries == null) { entries = new HashSet(); matches.put(field.toUpperCase(), entries); } entries.add(value); } return result; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rule/Rule.java000066400000000000000000000044511252742764200260100ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rule; import org.apache.log4j.spi.LoggingEvent; import java.beans.PropertyChangeListener; import java.util.Map; /** * A Rule evaluates to true of false given a LoggingEvent object, and can notify * listeners when the underlying implementation of this Rule has it's * criteria changed by using the standard PropertyChangeListener infrastructure. * * @author Paul Smith (psmith@apache.org) * @author Scott Deboy (sdeboy@apache.org) */ public interface Rule { /** * Returns true if this implementation of the rule accepts the LoggingEvent, * or false if not. * *

What True/False means can be client-specific. * * @param e LoggingEvent this instance will evaluate * @param matches a Map of event field keys to Sets of matching strings (may be null) which will be * updated during execution of this method to include field and string matches based on the rule * evaluation results * @return true if this Rule instance accepts the event, otherwise false. */ boolean evaluate(LoggingEvent e, Map matches); /** * Adds a PropertyChangeListener to this instance, which is notified when * underlying Rule information has changed. * (there are no specific property name events). * @param listener listener */ void addPropertyChangeListener(PropertyChangeListener listener); /** * Removes a known PropertyChangeListener from this Rule. * @param listener listener */ void removePropertyChangeListener(PropertyChangeListener listener); } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rule/RuleFactory.java000066400000000000000000000120201252742764200273270ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rule; import java.util.Collection; import java.util.LinkedList; import java.util.Locale; import java.util.Stack; /** * A Factory class which, given a string representation of the rule, * and a context stack, will * return a Rule ready for evaluation against events. * If an operator is requested that isn't supported, * an IllegalArgumentException is thrown. * * @author Scott Deboy (sdeboy@apache.org) */ public final class RuleFactory { /** * Singleton instance. */ private static final RuleFactory FACTORY = new RuleFactory(); /** * Rules. */ private static final Collection RULES = new LinkedList(); /** * AND operator literal. */ private static final String AND_RULE = "&&"; /** * OR operator literal. */ private static final String OR_RULE = "||"; /** * NOT operator literal. */ private static final String NOT_RULE = "!"; /** * Inequality operator literal. */ private static final String NOT_EQUALS_RULE = "!="; /** * Equality operator literal. */ private static final String EQUALS_RULE = "=="; /** * Partial match operator literal. */ private static final String PARTIAL_TEXT_MATCH_RULE = "~="; /** * Like operator literal. */ private static final String LIKE_RULE = "like"; /** * Exists operator literal. */ private static final String EXISTS_RULE = "exists"; /** * Less than operator literal. */ private static final String LESS_THAN_RULE = "<"; /** * Greater than operator literal. */ private static final String GREATER_THAN_RULE = ">"; /** * Less than or equal operator literal. */ private static final String LESS_THAN_EQUALS_RULE = "<="; /** * Greater than or equal operator literal. */ private static final String GREATER_THAN_EQUALS_RULE = ">="; static { RULES.add(AND_RULE); RULES.add(OR_RULE); RULES.add(NOT_RULE); RULES.add(NOT_EQUALS_RULE); RULES.add(EQUALS_RULE); RULES.add(PARTIAL_TEXT_MATCH_RULE); RULES.add(LIKE_RULE); RULES.add(EXISTS_RULE); RULES.add(LESS_THAN_RULE); RULES.add(GREATER_THAN_RULE); RULES.add(LESS_THAN_EQUALS_RULE); RULES.add(GREATER_THAN_EQUALS_RULE); } /** * Create instance. */ private RuleFactory() { super(); } /** * Get instance. * @return rule factory instance. */ public static RuleFactory getInstance() { return FACTORY; } /** * Determine if specified string is a known operator. * @param symbol string * @return true if string is a known operator */ public boolean isRule(final String symbol) { return ((symbol != null) && (RULES.contains(symbol.toLowerCase(Locale.ENGLISH)))); } /** * Create rule from applying operator to stack. * @param symbol symbol * @param stack stack * @return new instance */ public Rule getRule(final String symbol, final Stack stack) { if (AND_RULE.equals(symbol)) { return AndRule.getRule(stack); } if (OR_RULE.equals(symbol)) { return OrRule.getRule(stack); } if (NOT_RULE.equals(symbol)) { return NotRule.getRule(stack); } if (NOT_EQUALS_RULE.equals(symbol)) { return NotEqualsRule.getRule(stack); } if (EQUALS_RULE.equals(symbol)) { return EqualsRule.getRule(stack); } if (PARTIAL_TEXT_MATCH_RULE.equals(symbol)) { return PartialTextMatchRule.getRule(stack); } if (RULES.contains(LIKE_RULE) && LIKE_RULE.equalsIgnoreCase(symbol)) { return LikeRule.getRule(stack); } if (EXISTS_RULE.equalsIgnoreCase(symbol)) { return ExistsRule.getRule(stack); } if (LESS_THAN_RULE.equals(symbol)) { return InequalityRule.getRule(LESS_THAN_RULE, stack); } if (GREATER_THAN_RULE.equals(symbol)) { return InequalityRule.getRule(GREATER_THAN_RULE, stack); } if (LESS_THAN_EQUALS_RULE.equals(symbol)) { return InequalityRule.getRule(LESS_THAN_EQUALS_RULE, stack); } if (GREATER_THAN_EQUALS_RULE.equals(symbol)) { return InequalityRule.getRule(GREATER_THAN_EQUALS_RULE, stack); } throw new IllegalArgumentException("Invalid rule: " + symbol); } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rule/TimestampEqualsRule.java000066400000000000000000000072751252742764200310560ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rule; import java.io.IOException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.LoggingEventFieldResolver; /** * A Rule class implementing equality evaluation for timestamps. * * @author Scott Deboy (sdeboy@apache.org) */ public class TimestampEqualsRule extends AbstractRule { /** * Serialization ID. */ static final long serialVersionUID = 1639079557187790321L; /** * Resolver. */ private static final LoggingEventFieldResolver RESOLVER = LoggingEventFieldResolver.getInstance(); /** * Date format. */ private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); /** * time stamp. */ private long timeStamp; /** * Create new instance. * @param value string representation of date. */ private TimestampEqualsRule(final String value) { super(); //expects value to be a timestamp value represented as a long try { timeStamp = DATE_FORMAT.parse(value).getTime(); } catch (ParseException pe) { throw new IllegalArgumentException("Could not parse date: " + value); } } /** * Create new instance. * @param value string representation of date. * @return new instance */ public static Rule getRule(final String value) { return new TimestampEqualsRule(value); } /** {@inheritDoc} */ public boolean evaluate(final LoggingEvent event, Map matches) { String eventTimeStampString = RESOLVER.getValue(LoggingEventFieldResolver.TIMESTAMP_FIELD, event).toString(); long eventTimeStamp = Long.parseLong(eventTimeStampString) / 1000 * 1000; boolean result = (eventTimeStamp == timeStamp); if (result && matches != null) { Set entries = (Set) matches.get(LoggingEventFieldResolver.TIMESTAMP_FIELD); if (entries == null) { entries = new HashSet(); matches.put(LoggingEventFieldResolver.TIMESTAMP_FIELD, entries); } entries.add(eventTimeStampString); } return result; } /** * Deserialize the state of the object. * * @param in object input stream * * @throws IOException if IO error during deserialization * @throws ClassNotFoundException if class not found during * deserialization */ private void readObject(final java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { timeStamp = in.readLong(); } /** * Serialize the state of the object. * * @param out object output stream * * @throws IOException if IO error during serialization */ private void writeObject(final java.io.ObjectOutputStream out) throws IOException { out.writeLong(timeStamp); } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/rule/TimestampInequalityRule.java000066400000000000000000000106221252742764200317360ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rule; import java.io.IOException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.LoggingEventFieldResolver; /** * A Rule class implementing inequality evaluation for timestamps. * * @author Scott Deboy (sdeboy@apache.org) */ public class TimestampInequalityRule extends AbstractRule { /** * Serialization ID. */ static final long serialVersionUID = -4642641663914789241L; /** * Resolver. */ private static final LoggingEventFieldResolver RESOLVER = LoggingEventFieldResolver.getInstance(); /** * Date format. */ private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); /** * Inequality symbol. */ private transient String inequalitySymbol; /** * Timestamp. */ private long timeStamp; /** * Create new instance. * @param inequalitySymbol inequality symbol. * @param value string representation of date. */ private TimestampInequalityRule( final String inequalitySymbol, final String value) { super(); this.inequalitySymbol = inequalitySymbol; try { timeStamp = DATE_FORMAT.parse(value).getTime(); } catch (ParseException pe) { throw new IllegalArgumentException("Could not parse date: " + value); } } /** * Create new instance. * @param inequalitySymbol inequality symbol * @param value string representation of date * @return new instance */ public static Rule getRule(final String inequalitySymbol, final String value) { return new TimestampInequalityRule(inequalitySymbol, value); } /** {@inheritDoc} */ public boolean evaluate(final LoggingEvent event, Map matches) { String eventTimeStampString = RESOLVER.getValue(LoggingEventFieldResolver.TIMESTAMP_FIELD, event).toString(); long eventTimeStamp = Long.parseLong( eventTimeStampString) / 1000 * 1000; boolean result = false; long first = eventTimeStamp; long second = timeStamp; if ("<".equals(inequalitySymbol)) { result = first < second; } else if (">".equals(inequalitySymbol)) { result = first > second; } else if ("<=".equals(inequalitySymbol)) { result = first <= second; } else if (">=".equals(inequalitySymbol)) { result = first >= second; } if (result && matches != null) { Set entries = (Set) matches.get(LoggingEventFieldResolver.TIMESTAMP_FIELD); if (entries == null) { entries = new HashSet(); matches.put(LoggingEventFieldResolver.TIMESTAMP_FIELD, entries); } entries.add(eventTimeStampString); } return result; } /** * Deserialize the state of the object. * * @param in object input stream * * @throws IOException if IO error during deserialization * @throws ClassNotFoundException if class not found */ private void readObject(final java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { inequalitySymbol = (String) in.readObject(); timeStamp = in.readLong(); } /** * Serialize the state of the object. * * @param out object output stream * * @throws IOException if IO error during serialization */ private void writeObject(final java.io.ObjectOutputStream out) throws IOException { out.writeObject(inequalitySymbol); out.writeLong(timeStamp); } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/spi/000077500000000000000000000000001252742764200240565ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/spi/LoggingEventFieldResolver.java000066400000000000000000000223471252742764200320070ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.spi; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Locale; import org.apache.log4j.rule.InFixToPostFix; /** * A singleton helper utility which accepts a field name * and a LoggingEvent and returns the value of that field. * * This class defines a grammar used in creation of an expression-based Rule. * * The only available method is * Object getField(String fieldName, LoggingEvent event). * * Here is a description of the mapping of field names in the grammar * to fields on the logging event. While the getField method returns an Object, * the individual types returned per field are described here: * * Field Name Field value (String representation Return type * LOGGER category name (logger) String * LEVEL level Level * CLASS locationInformation's class name String * FILE locationInformation's file name String * LINE locationInformation's line number String * METHOD locationInformation's method name String * MSG message Object * NDC NDC String * EXCEPTION throwable string representation ThrowableInformation * TIMESTAMP timestamp Long * THREAD thread String * PROP.keyName entry in the Property hashtable String * mapped to the key [keyName] * NOTE: the values for the 'keyName' portion of the MDC and PROP mappings must * be an exact match to the key in the hashTable (case sensitive). * * If the passed-in field is null or doesn't match an entry * in the above-described mapping, an exception is thrown. * * @author Scott Deboy (sdeboy@apache.org) * @author Paul Smith (psmith@apache.org) * */ public final class LoggingEventFieldResolver { /** * Keyword list. */ public static final List KEYWORD_LIST = new ArrayList(); /** * LOGGER string literal. */ public static final String LOGGER_FIELD = "LOGGER"; /** * LEVEL string literal. */ public static final String LEVEL_FIELD = "LEVEL"; /** * CLASS string literal. */ public static final String CLASS_FIELD = "CLASS"; /** * FILE string literal. */ public static final String FILE_FIELD = "FILE"; /** * LINE string literal. */ public static final String LINE_FIELD = "LINE"; /** * METHOD string literal. */ public static final String METHOD_FIELD = "METHOD"; /** * MSG string literal. */ public static final String MSG_FIELD = "MSG"; /** * NDC string literal. */ public static final String NDC_FIELD = "NDC"; /** * EXCEPTION string literal. */ public static final String EXCEPTION_FIELD = "EXCEPTION"; /** * TIMESTAMP string literal. */ public static final String TIMESTAMP_FIELD = "TIMESTAMP"; /** * THREAD string literal. */ public static final String THREAD_FIELD = "THREAD"; /** * PROP. string literal. */ public static final String PROP_FIELD = "PROP."; /** * empty string literal. */ public static final String EMPTY_STRING = ""; /** * LOGGER string literal. */ private static final LoggingEventFieldResolver RESOLVER = new LoggingEventFieldResolver(); /** * Create new instance. */ private LoggingEventFieldResolver() { super(); KEYWORD_LIST.add(LOGGER_FIELD); KEYWORD_LIST.add(LEVEL_FIELD); KEYWORD_LIST.add(CLASS_FIELD); KEYWORD_LIST.add(FILE_FIELD); KEYWORD_LIST.add(LINE_FIELD); KEYWORD_LIST.add(METHOD_FIELD); KEYWORD_LIST.add(MSG_FIELD); KEYWORD_LIST.add(NDC_FIELD); KEYWORD_LIST.add(EXCEPTION_FIELD); KEYWORD_LIST.add(TIMESTAMP_FIELD); KEYWORD_LIST.add(THREAD_FIELD); KEYWORD_LIST.add(PROP_FIELD); } /** * Apply fields. * @param replaceText replacement text. * @param event logging event. * @return evaluted expression */ public String applyFields(final String replaceText, final LoggingEvent event) { if (replaceText == null) { return null; } InFixToPostFix.CustomTokenizer tokenizer = new InFixToPostFix.CustomTokenizer(replaceText); StringBuffer result = new StringBuffer(); boolean found = false; while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); if (isField(token) || token.toUpperCase(Locale.US).startsWith(PROP_FIELD)) { result.append(getValue(token, event).toString()); found = true; } else { result.append(token); } } if (found) { return result.toString(); } return null; } /** * Get singleton instance. * @return singleton instance */ public static LoggingEventFieldResolver getInstance() { return RESOLVER; } /** * Determines if specified string is a recognized field. * @param fieldName field name * @return true if recognized field. */ public boolean isField(final String fieldName) { if (fieldName != null) { return (KEYWORD_LIST.contains( fieldName.toUpperCase(Locale.US)) || fieldName.toUpperCase().startsWith(PROP_FIELD)); } return false; } /** * Get value of field. * @param fieldName field * @param event event * @return value of field */ public Object getValue(final String fieldName, final LoggingEvent event) { String upperField = fieldName.toUpperCase(Locale.US); if (LOGGER_FIELD.equals(upperField)) { return event.getLoggerName(); } else if (LEVEL_FIELD.equals(upperField)) { return event.getLevel(); } else if (MSG_FIELD.equals(upperField)) { return event.getMessage(); } else if (NDC_FIELD.equals(upperField)) { String ndcValue = event.getNDC(); return ((ndcValue == null) ? EMPTY_STRING : ndcValue); } else if (EXCEPTION_FIELD.equals(upperField)) { String[] throwableRep = event.getThrowableStrRep(); if (throwableRep == null) { return EMPTY_STRING; } else { return getExceptionMessage(throwableRep); } } else if (TIMESTAMP_FIELD.equals(upperField)) { return new Long(event.timeStamp); } else if (THREAD_FIELD.equals(upperField)) { return event.getThreadName(); } else if (upperField.startsWith(PROP_FIELD)) { //note: need to use actual fieldname since case matters Object propValue = event.getMDC(fieldName.substring(5)); if (propValue == null) { //case-specific match didn't work, try case insensitive match String lowerPropKey = fieldName.substring(5).toLowerCase(); Set entrySet = event.getProperties().entrySet(); for (Iterator iter = entrySet.iterator();iter.hasNext();) { Map.Entry thisEntry = (Map.Entry) iter.next(); if (thisEntry.getKey().toString().equalsIgnoreCase(lowerPropKey)) { propValue = thisEntry.getValue(); } } } return ((propValue == null) ? EMPTY_STRING : propValue.toString()); } else { LocationInfo info = event.getLocationInformation(); if (CLASS_FIELD.equals(upperField)) { return ((info == null) ? EMPTY_STRING : info.getClassName()); } else if (FILE_FIELD.equals(upperField)) { return ((info == null) ? EMPTY_STRING : info.getFileName()); } else if (LINE_FIELD.equals(upperField)) { return ((info == null) ? EMPTY_STRING : info.getLineNumber()); } else if (METHOD_FIELD.equals(upperField)) { return ((info == null) ? EMPTY_STRING : info.getMethodName()); } } //there wasn't a match, so throw a runtime exception throw new IllegalArgumentException("Unsupported field name: " + fieldName); } /** * Get message from throwable representation. * @param exception exception * @return message */ private static String getExceptionMessage(final String[] exception) { StringBuffer buff = new StringBuffer(); for (int i = 0; i < exception.length; i++) { buff.append(exception[i]); } return buff.toString(); } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/varia/000077500000000000000000000000001252742764200243655ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/varia/SoundAppender.java000066400000000000000000000056071252742764200300070ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.varia; import java.applet.Applet; import java.applet.AudioClip; import java.net.MalformedURLException; import java.net.URL; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.helpers.LogLog; /** * Plays a sound clip created using Applet.newAudioClip when an event is received. * * If the audio format is not supported, a message stating the SoundAppender could * not be initialized is logged. * * Use a filter in combination with this appender to control when the appender is * triggered. * * For example, in the appender definition, include a LevelMatchFilter configured * to accept WARN or greater, followed by a DenyAllFilter. * * @author Scott Deboy * */ public final class SoundAppender extends AppenderSkeleton { private AudioClip clip; private String audioURL; public SoundAppender() { } /** * Attempt to initialize the appender by creating a reference to an AudioClip. * * Will log a message if format is not supported, file not found, etc. * */ public void activateOptions() { /* * AudioSystem.getAudioInputStream requires jdk 1.3, * so we use applet.newaudioclip instead * */ try { clip = Applet.newAudioClip(new URL(audioURL)); } catch (MalformedURLException mue) { LogLog.error("unable to initialize SoundAppender", mue);} if (clip == null) { LogLog.error("Unable to initialize SoundAppender"); } } /** * Accessor * * @return audio file */ public String getAudioURL() { return audioURL; } /** * Mutator - common format for a file-based url: * file:///c:/path/someaudioclip.wav * * @param audioURL */ public void setAudioURL(String audioURL) { this.audioURL = audioURL; } /** * Play the sound if an event is being processed */ protected void append(LoggingEvent event) { if (clip != null) { clip.play(); } } public void close() { //nothing to do } /** * Gets whether appender requires a layout. * @return false */ public boolean requiresLayout() { return false; } } apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/xml/000077500000000000000000000000001252742764200240635ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/java/org/apache/log4j/xml/XSLTLayout.java000066400000000000000000000431071252742764200267230ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.xml; import org.apache.log4j.Layout; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.helpers.MDCKeySetExtractor; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.LocationInfo; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.Templates; import javax.xml.transform.Transformer; import javax.xml.transform.sax.TransformerHandler; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.stream.StreamSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.dom.DOMSource; import javax.xml.parsers.DocumentBuilderFactory; import java.io.InputStream; import java.io.ByteArrayOutputStream; import java.io.ByteArrayInputStream; import java.util.Set; import java.util.Properties; import java.util.Arrays; import java.util.TimeZone; import java.nio.charset.Charset; import java.nio.ByteBuffer; import org.apache.log4j.pattern.CachedDateFormat; import java.text.SimpleDateFormat; import org.w3c.dom.Document; import org.xml.sax.helpers.AttributesImpl; /** * XSLTLayout transforms each event as a document using * a specified or default XSLT transform. The default * XSLT transform produces a result similar to XMLLayout. * * When used with a FileAppender or similar, the transformation of * an event will be appended to the results for previous * transforms. If each transform results in an XML element, then * resulting file will only be an XML entity * since an XML document requires one and only one top-level element. * To process the entity, reference it in a XML document like so: * *

 *  <!DOCTYPE log4j:eventSet [<!ENTITY data SYSTEM "data.xml">]>
 *
 *  <log4j:eventSet xmlns:log4j="http://jakarta.apache.org/log4j/">
 *    &data
 *  </log4j:eventSet>
 *
 * 
* * The layout will detect the encoding and media-type specified in * the transform. If no encoding is specified in the transform, * an xsl:output element specifying the US-ASCII encoding will be inserted * before processing the transform. If an encoding is specified in the transform, * the same encoding should be explicitly specified for the appender. * * Extracting MDC values can be expensive when used with log4j releases * prior to 1.2.15. Output of MDC values is enabled by default * but be suppressed by setting properties to false. * * Extracting location info can be expensive regardless of log4j version. * Output of location info is disabled by default but can be enabled * by setting locationInfo to true. * * Embedded transforms in XML configuration should not * depend on namespace prefixes defined earlier in the document * as namespace aware parsing in not generally performed when * using DOMConfigurator. The transform will serialize * and reparse to get the namespace aware document needed. * */ public final class XSLTLayout extends Layout implements UnrecognizedElementHandler { /** * Namespace for XSLT. */ private static final String XSLT_NS = "http://www.w3.org/1999/XSL/Transform"; /** * Namespace for log4j events. */ private static final String LOG4J_NS = "http://jakarta.apache.org/log4j/"; /** * Whether location information should be written. */ private boolean locationInfo = false; /** * media-type (mime type) extracted from XSLT transform. */ private String mediaType = "text/plain"; /** * Encoding extracted from XSLT transform. */ private Charset encoding; /** * Transformer factory. */ private SAXTransformerFactory transformerFactory; /** * XSLT templates. */ private Templates templates; /** * Output stream. */ private final ByteArrayOutputStream outputStream; /** * Whether throwable information should be ignored. */ private boolean ignoresThrowable = false; /** * Whether properties should be extracted. */ private boolean properties = true; /** * Whether activateOptions has been called. */ private boolean activated = false; /** * DateFormat for UTC time. */ private final CachedDateFormat utcDateFormat; /** * Default constructor. * */ public XSLTLayout() { outputStream = new ByteArrayOutputStream(); transformerFactory = (SAXTransformerFactory) TransformerFactory.newInstance(); SimpleDateFormat zdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); zdf.setTimeZone(TimeZone.getTimeZone("UTC")); utcDateFormat = new CachedDateFormat(zdf, 1000); } /** * {@inheritDoc} */ public synchronized String getContentType() { return mediaType; } /** * The LocationInfo option takes a boolean value. By default, it is * set to false which means there will be no location information output by * this layout. If the the option is set to true, then the file name and line * number of the statement at the origin of the log statement will be output. * *

* If you are embedding this layout within an {@link * org.apache.log4j.net.SMTPAppender} then make sure to set the * LocationInfo option of that appender as well. * * @param flag new value. */ public synchronized void setLocationInfo(final boolean flag) { locationInfo = flag; } /** * Gets whether location info should be output. * @return if location is output. */ public synchronized boolean getLocationInfo() { return locationInfo; } /** * Sets whether MDC key-value pairs should be output, default false. * @param flag new value. */ public synchronized void setProperties(final boolean flag) { properties = flag; } /** * Gets whether MDC key-value pairs should be output. * @return true if MDC key-value pairs are output. */ public synchronized boolean getProperties() { return properties; } /** {@inheritDoc} */ public synchronized void activateOptions() { if (templates == null) { try { InputStream is = XSLTLayout.class.getResourceAsStream("default.xslt"); StreamSource ss = new StreamSource(is); templates = transformerFactory.newTemplates(ss); encoding = Charset.forName("US-ASCII"); mediaType = "text/plain"; } catch (Exception ex) { LogLog.error("Error loading default.xslt", ex); } } activated = true; } /** * Gets whether throwables should not be output. * @return true if throwables should not be output. */ public synchronized boolean ignoresThrowable() { return ignoresThrowable; } /** * Sets whether throwables should not be output. * @param ignoresThrowable if true, throwables should not be output. */ public synchronized void setIgnoresThrowable(boolean ignoresThrowable) { this.ignoresThrowable = ignoresThrowable; } /** * {@inheritDoc} */ public synchronized String format(final LoggingEvent event) { if (!activated) { activateOptions(); } if (templates != null && encoding != null) { outputStream.reset(); try { TransformerHandler transformer = transformerFactory.newTransformerHandler(templates); transformer.setResult(new StreamResult(outputStream)); transformer.startDocument(); // // event element // AttributesImpl attrs = new AttributesImpl(); attrs.addAttribute(null, "logger", "logger", "CDATA", event.getLoggerName()); attrs.addAttribute(null, "timestamp", "timestamp", "CDATA", Long.toString(event.timeStamp)); attrs.addAttribute(null, "level", "level", "CDATA", event.getLevel().toString()); attrs.addAttribute(null, "thread", "thread", "CDATA", event.getThreadName()); StringBuffer buf = new StringBuffer(); utcDateFormat.format(event.timeStamp, buf); attrs.addAttribute(null, "time", "time", "CDATA", buf.toString()); transformer.startElement(LOG4J_NS, "event", "event", attrs); attrs.clear(); // // message element // transformer.startElement(LOG4J_NS, "message", "message", attrs); String msg = event.getRenderedMessage(); if (msg != null && msg.length() > 0) { transformer.characters(msg.toCharArray(), 0, msg.length()); } transformer.endElement(LOG4J_NS, "message", "message"); // // NDC element // String ndc = event.getNDC(); if (ndc != null) { transformer.startElement(LOG4J_NS, "NDC", "NDC", attrs); char[] ndcChars = ndc.toCharArray(); transformer.characters(ndcChars, 0, ndcChars.length); transformer.endElement(LOG4J_NS, "NDC", "NDC"); } // // throwable element unless suppressed // if (!ignoresThrowable) { String[] s = event.getThrowableStrRep(); if (s != null) { transformer.startElement(LOG4J_NS, "throwable", "throwable", attrs); char[] nl = new char[] { '\n' }; for (int i = 0; i < s.length; i++) { char[] line = s[i].toCharArray(); transformer.characters(line, 0, line.length); transformer.characters(nl, 0, nl.length); } transformer.endElement(LOG4J_NS, "throwable", "throwable"); } } // // location info unless suppressed // // if (locationInfo) { LocationInfo locationInfo = event.getLocationInformation(); attrs.addAttribute(null, "class", "class", "CDATA", locationInfo.getClassName()); attrs.addAttribute(null, "method", "method", "CDATA", locationInfo.getMethodName()); attrs.addAttribute(null, "file", "file", "CDATA", locationInfo.getFileName()); attrs.addAttribute(null, "line", "line", "CDATA", locationInfo.getLineNumber()); transformer.startElement(LOG4J_NS, "locationInfo", "locationInfo", attrs); transformer.endElement(LOG4J_NS, "locationInfo", "locationInfo"); } if (properties) { // // write MDC contents out as properties element // Set mdcKeySet = MDCKeySetExtractor.INSTANCE.getPropertyKeySet(event); if ((mdcKeySet != null) && (mdcKeySet.size() > 0)) { attrs.clear(); transformer.startElement(LOG4J_NS, "properties", "properties", attrs); Object[] keys = mdcKeySet.toArray(); Arrays.sort(keys); for (int i = 0; i < keys.length; i++) { String key = keys[i].toString(); Object val = event.getMDC(key); attrs.clear(); attrs.addAttribute(null, "name", "name", "CDATA", key); attrs.addAttribute(null, "value", "value", "CDATA", val.toString()); transformer.startElement(LOG4J_NS, "data", "data", attrs); transformer.endElement(LOG4J_NS, "data", "data"); } } } transformer.endElement(LOG4J_NS, "event", "event"); transformer.endDocument(); String body = encoding.decode( ByteBuffer.wrap(outputStream.toByteArray())).toString(); outputStream.reset(); // // must remove XML declaration since it may // result in erroneous encoding info // if written by FileAppender in a different encoding if (body.startsWith(""); if (endDecl != -1) { for(endDecl += 2; endDecl < body.length() && (body.charAt(endDecl) == '\n' || body.charAt(endDecl) == '\r'); endDecl++); return body.substring(endDecl); } } return body; } catch (Exception ex) { LogLog.error("Error during transformation", ex); return ex.toString(); } } return "No valid transform or encoding specified."; } /** * Sets XSLT transform. * @param xsltdoc DOM document containing XSLT transform source, * may be modified. * @throws TransformerConfigurationException if transformer can not be * created. */ public void setTransform(final Document xsltdoc) throws TransformerConfigurationException { // // scan transform source for xsl:output elements // and extract encoding, media (mime) type and output method // String encodingName = null; mediaType = null; String method = null; NodeList nodes = xsltdoc.getElementsByTagNameNS( XSLT_NS, "output"); for(int i = 0; i < nodes.getLength(); i++) { Element outputElement = (Element) nodes.item(i); if (method == null || method.length() == 0) { method = outputElement.getAttributeNS(null, "method"); } if (encodingName == null || encodingName.length() == 0) { encodingName = outputElement.getAttributeNS(null, "encoding"); } if (mediaType == null || mediaType.length() == 0) { mediaType = outputElement.getAttributeNS(null, "media-type"); } } if (mediaType == null || mediaType.length() == 0) { if ("html".equals(method)) { mediaType = "text/html"; } else if ("xml".equals(method)) { mediaType = "text/xml"; } else { mediaType = "text/plain"; } } // // if encoding was not specified, // add xsl:output encoding=US-ASCII to XSLT source // if (encodingName == null || encodingName.length() == 0) { Element transformElement = xsltdoc.getDocumentElement(); Element outputElement = xsltdoc. createElementNS(XSLT_NS, "output"); outputElement.setAttributeNS(null, "encoding", "US-ASCII"); transformElement.insertBefore(outputElement, transformElement.getFirstChild()); encoding = Charset.forName("US-ASCII"); } else { encoding = Charset.forName(encodingName); } DOMSource transformSource = new DOMSource(xsltdoc); templates = transformerFactory.newTemplates(transformSource); } /** * {@inheritDoc} */ public boolean parseUnrecognizedElement(final Element element, final Properties props) throws Exception { if (XSLT_NS.equals(element.getNamespaceURI()) || element.getNodeName().indexOf("transform") != -1 || element.getNodeName().indexOf("stylesheet") != -1) { // // DOMConfigurator typically not namespace aware // serialize tree and reparse. ByteArrayOutputStream os = new ByteArrayOutputStream(); DOMSource source = new DOMSource(element); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(source, new StreamResult(os)); ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray()); DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); Document xsltdoc = domFactory.newDocumentBuilder().parse(is); setTransform(xsltdoc); return true; } return false; } } apache-log4j-extras1.2-1.2.17/src/main/resources/000077500000000000000000000000001252742764200213255ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/resources/META-INF/000077500000000000000000000000001252742764200224655ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/resources/META-INF/LICENSE000066400000000000000000000261461252742764200235030ustar00rootroot00000000000000 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. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 1999-2005 The Apache Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. apache-log4j-extras1.2-1.2.17/src/main/resources/META-INF/NOTICE000066400000000000000000000002721252742764200233720ustar00rootroot00000000000000Apache Extras Companion for log4j 1.2. Copyright 2007 The Apache Software Foundation This product includes software developed at The Apache Software Foundation (http://www.apache.org/).apache-log4j-extras1.2-1.2.17/src/main/resources/org/000077500000000000000000000000001252742764200221145ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/resources/org/apache/000077500000000000000000000000001252742764200233355ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/resources/org/apache/log4j/000077500000000000000000000000001252742764200243545ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/resources/org/apache/log4j/extras/000077500000000000000000000000001252742764200256625ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/resources/org/apache/log4j/extras/log4j.dtd000066400000000000000000000150761252742764200274070ustar00rootroot00000000000000 apache-log4j-extras1.2-1.2.17/src/main/resources/org/apache/log4j/xml/000077500000000000000000000000001252742764200251545ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/main/resources/org/apache/log4j/xml/default.xslt000066400000000000000000000053631252742764200275230ustar00rootroot00000000000000 apache-log4j-extras1.2-1.2.17/src/site/000077500000000000000000000000001252742764200173335ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/site/apt/000077500000000000000000000000001252742764200201175ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/site/apt/download.apt000066400000000000000000000071671252742764200224470ustar00rootroot00000000000000~~ Licensed to the Apache Software Foundation (ASF) under one or more ~~ contributor license agreements. See the NOTICE file distributed with ~~ this work for additional information regarding copyright ownership. ~~ The ASF licenses this file to You 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. ------ Download Apache Extras Companion\u2122 for Apache log4j\u2122 ------ ------ ------ Download Apache Extras Companion\u2122 for Apache log4j\u2122 "Apache Extras\u2122 for Apache log4j\u2122 is distributed under the {{{http://www.apache.org/licenses/LICENSE-2.0.html} Apache License","version 2.0}}." The link in the Mirrors column should display a list of available mirrors with a default selection based on your inferred location. If you do not see that page, try a different browser. The checksum and signature are links to the originals on the main distribution server. *-------------------------+---------+----------+-----------+ | | Mirrors | Checksum | Signature | *-------------------------+---------+----------+-----------+ | apache-log4j-extras-1.2.17 (tar.gz) | {{{http://www.apache.org/dyn/closer.cgi/logging/log4j/extras/1.2.17/apache-log4j-extras-1.2.17.tar.gz} apache-log4j-extras-1.2.17.tar.gz}} | {{{http://www.apache.org/dist/logging/log4j/extras/1.2/apache-log4j-extras-1.2.17.tar.gz.md5} apache-log4j-extras-1.2.17.tar.gz.md5}} | {{{http://www.apache.org/dist/logging/log4j/extras/1.2/apache-log4j-extras-1.2.17.tar.gz.asc} apache-log4j-extras-1.2.17.tar.gz.asc}} | *-------------------------+---------+----------+-----------+ | apache-log4j-extras-1.2.17 (zip) | {{{http://www.apache.org/dyn/closer.cgi/logging/log4j/extras/1.2.17/apache-log4j-extras-1.2.17.zip} apache-log4j-extras-1.2.17.zip}} | {{{http://www.apache.org/dist/logging/log4j/extras/1.2/apache-log4j-extras-1.2.17.zip.md5} apache-log4j-extras-1.2.17.zip.md5}} | {{{http://www.apache.org/dist/logging/log4j/extras/1.2/apache-log4j-extras-1.2.17.zip.asc} apache-log4j-extras-1.2.17.zip.asc}} | *-------------------------+---------+----------+-----------+ It is essential that you verify the integrity of the downloaded files using the PGP or MD5 signatures. Please read {{{http://httpd.apache.org/dev/verification.html}Verifying Apache HTTP Server Releases}} for more information on why you should verify our releases. The PGP signatures can be verified using PGP or GPG. First download the {{{http://www.apache.org/dist/logging/KEYS}KEYS}} as well as the asc signature file for the relevant distribution. Make sure you get these files from the {{{http://www.apache.org/dist/logging/}main distribution directory}}, rather than from a mirror. Then verify the signatures using --- % gpg --import KEYS % gpg --verify apache-log4j-extras-1.2.17.tar.gz.asc --- Apache Extras for Apache log4j 1.2.17 is signed by Christian Grobmeier 42196CA8 Alternatively, you can verify the MD5 signature on the files. A unix program called md5 or md5sum is included in many unix distributions. * Previous Releases Previous releases can be found in the {{{http://archive.apache.org/dist/logging/log4j/companions}archive repository}}. apache-log4j-extras1.2-1.2.17/src/site/apt/index.apt000066400000000000000000000040311252742764200217320ustar00rootroot00000000000000~~ Licensed to the Apache Software Foundation (ASF) under one or more ~~ contributor license agreements. See the NOTICE file distributed with ~~ this work for additional information regarding copyright ownership. ~~ The ASF licenses this file to You 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. ------ Apache Extras\u2122 for Apache log4j\u2122 ------ ------ ------ Apache Extras\u2122 for Apache log4j\u2122 Apache Extras\u2122 for Apache log4j\u2122 is a jar file full of additional functionality for log4j 1.2.x. Apache Extras for Apache log4j is a product of the {{{http://logging.apache.org}Apache Logging Services Project}}, a project of {{{http://www.apache.org}The Apache Software Foundation}}. Many of these components were originally developed in the discontinued Apache log4j 1.3 development effort. Version naming: The package will use the log4j it requires + optional bugfix version after version 1.2. For example, if the Companions release requires log4j 1.2.17 to work, the Companions release will have the version number 1.2.17 too. If new version is necessary, the release will be named 1.2.17.1, 1.2.17.2 and so on. * Component The component classes implements on log4j 1.2 the component framework from the discontinued log4j 1.3 development activity to support backporting log4j 1.3 code that depends on the framework. * Receivers A collection of receivers classes from the log4j 1.3 project for use with log4j 1.2. * Extras A collection of appenders, filters, and layouts for Apache log4j 1.2.apache-log4j-extras1.2-1.2.17/src/site/apt/roadmap.apt000066400000000000000000000022141252742764200222470ustar00rootroot00000000000000~~ Licensed to the Apache Software Foundation (ASF) under one or more ~~ contributor license agreements. See the NOTICE file distributed with ~~ this work for additional information regarding copyright ownership. ~~ The ASF licenses this file to You 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. ------ Apache Extras\u2122 for Apache log4j\u2122 Roadmap ------ ------ ------ Apache Extras\u2122 for Apache log4j\u2122 Roadmap The extras component is open to additional generally useful features that are compatible with the widely deployed Apache log4j > 1.2.17 releases and do not add additional dependencies. No more development is anticipated. apache-log4j-extras1.2-1.2.17/src/site/maven-site.vm000066400000000000000000000440401252742764200217510ustar00rootroot00000000000000 #macro ( link $href $name $target $img $position $alt $border $width $height ) #set ( $linkTitle = ' title="' + $name + '"' ) #if( $target ) #set ( $linkTarget = ' target="' + $target + '"' ) #else #set ( $linkTarget = "" ) #end #if ( ( $href.toLowerCase().startsWith("http") || $href.toLowerCase().startsWith("https") ) ) #set ( $linkClass = ' class="externalLink"' ) #else #set ( $linkClass = "" ) #end #if ( $img ) #if ( $position == "left" ) #image($img $alt $border $width $height)$name #else $name #image($img $alt $border $width $height) #end #else $name #end #end ## #macro ( image $img $alt $border $width $height ) #if( $img ) #if ( ! ( $img.toLowerCase().startsWith("http") || $img.toLowerCase().startsWith("https") ) ) #set ( $imgSrc = $PathTool.calculateLink( $img, $relativePath ) ) #set ( $imgSrc = $imgSrc.replaceAll( '\\', '/' ) ) #set ( $imgSrc = ' src="' + $imgSrc + '"' ) #else #set ( $imgSrc = ' src="' + $img + '"' ) #end #if( $alt ) #set ( $imgAlt = ' alt="' + $alt + '"' ) #else #set ( $imgAlt = ' alt=""' ) #end #if( $border ) #set ( $imgBorder = ' border="' + $border + '"' ) #else #set ( $imgBorder = "" ) #end #if( $width ) #set ( $imgWidth = ' width="' + $width + '"' ) #else #set ( $imgWidth = "" ) #end #if( $height ) #set ( $imgHeight = ' height="' + $height + '"' ) #else #set ( $imgHeight = "" ) #end #end #end #macro ( banner $banner $id ) #if ( $banner ) #if( $banner.href ) #else

#end ## #if( $banner.src ) #set ( $src = $banner.src ) #if ( ! ( $src.toLowerCase().startsWith("http") || $src.toLowerCase().startsWith("https") ) ) #set ( $src = $PathTool.calculateLink( $src, $relativePath ) ) #set ( $src = $src.replaceAll( '\\', '/' ) ) #end #if ( $banner.alt ) #set ( $alt = $banner.alt ) #else #set ( $alt = $banner.name ) #end $alt #else $banner.name #end ## #if( $banner.href ) #else
#end #end #end ## #macro ( links $links ) #set ( $counter = 0 ) #foreach( $item in $links ) #set ( $counter = $counter + 1 ) #set ( $currentItemHref = $PathTool.calculateLink( $item.href, $relativePath ) ) #set ( $currentItemHref = $currentItemHref.replaceAll( '\\', '/' ) ) #link( $currentItemHref $item.name $item.target $item.img $item.position $item.alt $item.border $item.width $item.height ) #if ( $links.size() > $counter ) | #end #end #end ## #macro ( breadcrumbs $breadcrumbs ) #set ( $counter = 0 ) #foreach( $item in $breadcrumbs ) #set ( $counter = $counter + 1 ) #set ( $currentItemHref = $PathTool.calculateLink( $item.href, $relativePath ) ) #set ( $currentItemHref = $currentItemHref.replaceAll( '\\', '/' ) ) ## #if ( $currentItemHref == $alignedFileName || $currentItemHref == "" ) $item.name #else #link( $currentItemHref $item.name $item.target $item.img $item.position $item.alt $item.border $item.width $item.height ) #end #if ( $breadcrumbs.size() > $counter ) > #end #end #end ## #macro ( displayTree $display $item ) #if ( $item && $item.items && $item.items.size() > 0 ) #foreach( $subitem in $item.items ) #set ( $subitemHref = $PathTool.calculateLink( $subitem.href, $relativePath ) ) #set ( $subitemHref = $subitemHref.replaceAll( '\\', '/' ) ) #if ( $alignedFileName == $subitemHref ) #set ( $display = true ) #end ## #displayTree( $display $subitem ) #end #end #end ## #macro ( menuItem $item ) #set ( $collapse = "none" ) #set ( $currentItemHref = $PathTool.calculateLink( $item.href, $relativePath ) ) #set ( $currentItemHref = $currentItemHref.replaceAll( '\\', '/' ) ) ## #if ( $item && $item.items && $item.items.size() > 0 ) #if ( $item.collapse == false ) #set ( $collapse = "expanded" ) #else ## By default collapsed #set ( $collapse = "collapsed" ) #end ## #set ( $display = false ) #displayTree( $display $item ) ## #if ( $alignedFileName == $currentItemHref || $display ) #set ( $collapse = "expanded" ) #end #end
  • #if ( $item.img ) #if ( $item.position == "left" ) #if ( $alignedFileName == $currentItemHref ) #image($item.img $item.alt $item.border $item.width $item.height) $item.name #else #link($currentItemHref $item.name $item.target $item.img $item.position $item.alt $item.border $item.width $item.height) #end #else #if ( $alignedFileName == $currentItemHref ) $item.name #image($item.img $item.alt $item.border $item.width $item.height) #else #link($currentItemHref $item.name $item.target $item.img $item.position $item.alt $item.border $item.width $item.height) #end #end #else #if ( $alignedFileName == $currentItemHref ) $item.name #else #link( $currentItemHref $item.name $item.target $item.img $item.position $item.alt $item.border $item.width $item.height ) #end #end #if ( $item && $item.items && $item.items.size() > 0 ) #if ( $collapse == "expanded" ) #end #end
  • #end ## #macro ( mainMenu $menus ) #foreach( $menu in $menus ) #if ( $menu.name ) #if ( $menu.img ) #if( $menu.position ) #set ( $position = $menu.position ) #else #set ( $position = "left" ) #end ## #if ( ! ( $menu.img.toLowerCase().startsWith("http") || $menu.img.toLowerCase().startsWith("https") ) ) #set ( $src = $PathTool.calculateLink( $menu.img, $relativePath ) ) #set ( $src = $src.replaceAll( '\\', '/' ) ) #set ( $src = ' src="' + $src + '"' ) #else #set ( $src = ' src="' + $menu.img + '"' ) #end ## #if( $menu.alt ) #set ( $alt = ' alt="' + $menu.alt + '"' ) #else #set ( $alt = ' alt="' + $menu.name + '"' ) #end ## #if( $menu.border ) #set ( $border = ' border="' + $menu.border + '"' ) #else #set ( $border = ' border="0"' ) #end ## #if( $menu.width ) #set ( $width = ' width="' + $menu.width + '"' ) #else #set ( $width = "" ) #end #if( $menu.height ) #set ( $height = ' height="' + $menu.height + '"' ) #else #set ( $height = "" ) #end ## #set ( $img = '" ) ## #if ( $position == "left" )
    $img $menu.name
    #else
    $menu.name $img
    #end #else
    $menu.name
    #end #end #if ( $menu.items && $menu.items.size() > 0 ) #end #end #end ## #macro ( copyright ) #if ( $project ) #if ( ${project.organization} && ${project.organization.name} ) #set ( $period = "" ) #else #set ( $period = "." ) #end ## #set ( $currentYear = ${currentDate.year} + 1900 ) ## #if ( ${project.inceptionYear} && ( ${project.inceptionYear} != ${currentYear.toString()} ) ) ${project.inceptionYear}-${currentYear}${period} #else ${currentYear}${period} #end ## #if ( ${project.organization} ) #if ( ${project.organization.name} && ${project.organization.url} ) ${project.organization.name}. #elseif ( ${project.organization.name} ) ${project.organization.name}. #end #end #end #end ## #macro ( publishDate $position $publishDate $version ) #if ( $publishDate && $publishDate.format ) #set ( $format = $publishDate.format ) #else #set ( $format = "yyyy-MM-dd" ) #end ## $dateFormat.applyPattern( $format ) ## #set ( $dateToday = $dateFormat.format( $currentDate ) ) ## #if ( $publishDate && $publishDate.position ) #set ( $datePosition = $publishDate.position ) #else #set ( $datePosition = "left" ) #end ## #if ( $version ) #if ( $version.position ) #set ( $versionPosition = $version.position ) #else #set ( $versionPosition = "left" ) #end #else #set ( $version = "" ) #set ( $versionPosition = "left" ) #end ## #set ( $breadcrumbs = $decoration.body.breadcrumbs ) #set ( $links = $decoration.body.links ) #if ( $datePosition.equalsIgnoreCase( "right" ) && $links && $links.size() > 0 ) #set ( $prefix = " |" ) #else #set ( $prefix = "" ) #end ## #if ( $datePosition.equalsIgnoreCase( $position ) ) #if ( ( $datePosition.equalsIgnoreCase( "right" ) ) || ( $datePosition.equalsIgnoreCase( "bottom" ) ) ) $prefix $i18n.getString( "site-renderer", $locale, "template.lastpublished" ): $dateToday #if ( $versionPosition.equalsIgnoreCase( $position ) )  | $i18n.getString( "site-renderer", $locale, "template.version" ): ${project.version} #end #elseif ( ( $datePosition.equalsIgnoreCase( "navigation-bottom" ) ) || ( $datePosition.equalsIgnoreCase( "navigation-top" ) ) )
    $i18n.getString( "site-renderer", $locale, "template.lastpublished" ): $dateToday #if ( $versionPosition.equalsIgnoreCase( $position ) )  | $i18n.getString( "site-renderer", $locale, "template.version" ): ${project.version} #end
    #elseif ( $datePosition.equalsIgnoreCase("left") )
    $i18n.getString( "site-renderer", $locale, "template.lastpublished" ): $dateToday #if ( $versionPosition.equalsIgnoreCase( $position ) )  | $i18n.getString( "site-renderer", $locale, "template.version" ): ${project.version} #end #if ( $breadcrumbs && $breadcrumbs.size() > 0 ) | #breadcrumbs( $breadcrumbs ) #end
    #end #elseif ( $versionPosition.equalsIgnoreCase( $position ) ) #if ( ( $versionPosition.equalsIgnoreCase( "right" ) ) || ( $versionPosition.equalsIgnoreCase( "bottom" ) ) ) $prefix $i18n.getString( "site-renderer", $locale, "template.version" ): ${project.version} #elseif ( ( $versionPosition.equalsIgnoreCase( "navigation-bottom" ) ) || ( $versionPosition.equalsIgnoreCase( "navigation-top" ) ) )
    $i18n.getString( "site-renderer", $locale, "template.version" ): ${project.version}
    #elseif ( $versionPosition.equalsIgnoreCase("left") )
    $i18n.getString( "site-renderer", $locale, "template.version" ): ${project.version} #if ( $breadcrumbs && $breadcrumbs.size() > 0 ) | #breadcrumbs( $breadcrumbs ) #end
    #end #elseif ( $position.equalsIgnoreCase( "left" ) ) #if ( $breadcrumbs && $breadcrumbs.size() > 0 )
    #breadcrumbs( $breadcrumbs )
    #end #end #end ## #macro ( poweredByLogo $poweredBy ) #if( $poweredBy ) #foreach ($item in $poweredBy) #if( $item.href ) #set ( $href = $PathTool.calculateLink( $item.href, $relativePath ) ) #set ( $href = $href.replaceAll( '\\', '/' ) ) #else #set ( $href="http://maven.apache.org/" ) #end ## #if( $item.name ) #set ( $name = $item.name ) #else #set ( $name = $i18n.getString( "site-renderer", $locale, "template.builtby" ) ) #set ( $name = "${name} Maven" ) #end ## #if( $item.img ) #set ( $img = $item.img ) #else #set ( $img = "images/logos/maven-feather.png" ) #end ## #if ( ! ( $img.toLowerCase().startsWith("http") || $img.toLowerCase().startsWith("https") ) ) #set ( $img = $PathTool.calculateLink( $img, $relativePath ) ) #set ( $img = $src.replaceAll( '\\', '/' ) ) #end ## #if( $item.alt ) #set ( $alt = ' alt="' + $item.alt + '"' ) #else #set ( $alt = ' alt="' + $name + '"' ) #end ## #if( $item.border ) #set ( $border = ' border="' + $item.border + '"' ) #else #set ( $border = "" ) #end ## #if( $item.width ) #set ( $width = ' width="' + $item.width + '"' ) #else #set ( $width = "" ) #end #if( $item.height ) #set ( $height = ' height="' + $item.height + '"' ) #else #set ( $height = "" ) #end ## #end #if( $poweredBy.isEmpty() ) $i18n.getString( #end #else $i18n.getString( #end #end ## $title #foreach( $author in $authors ) #end #if ( $dateCreation ) #end #if ( $dateRevision ) #end #if ( $locale ) #end #if ( $decoration.body.head ) #foreach( $item in $decoration.body.head.getChildren() ) ## Workaround for DOXIA-150 due to a non-desired behaviour in p-u ## @see org.codehaus.plexus.util.xml.Xpp3Dom#toString() ## @see org.codehaus.plexus.util.xml.Xpp3Dom#toUnescapedString() #set ( $documentHeader = '' ) #if ( $item.name == "script" ) $StringUtils.replace( $item.toUnescapedString(), $documentHeader, "" ) #else $StringUtils.replace( $item.toString(), $documentHeader, "" ) #end #end #end
    $bodyContent

    apache-log4j-extras1.2-1.2.17/src/site/resources/000077500000000000000000000000001252742764200213455ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/site/resources/css/000077500000000000000000000000001252742764200221355ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/site/resources/css/maven-base.css000066400000000000000000000060151252742764200246670ustar00rootroot00000000000000/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You 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. */ body { margin: 0px; padding: 0px; } img { border:none; } table { padding:0px; width: 100%; margin-left: -2px; margin-right: -2px; } acronym { cursor: help; border-bottom: 1px dotted #feb; } table.bodyTable th, table.bodyTable td { padding: 2px 4px 2px 4px; vertical-align: top; } div.clear{ clear:both; visibility: hidden; } div.clear hr{ display: none; } #bannerLeft, #bannerRight { font-size: xx-large; font-weight: bold; } #bannerLeft img, #bannerRight img { margin: 0px; } .xleft, #bannerLeft img { float:left; } .xright, #bannerRight { float:right; } #banner { padding: 0px; } #banner img { border: none; } #breadcrumbs { padding: 3px 10px 3px 10px; } #leftColumn { width: 170px; float:left; overflow: auto; } #bodyColumn { margin-right: 1.5em; margin-left: 197px; } #legend { padding: 8px 0 8px 0; } #navcolumn { padding: 8px 4px 0 8px; } #navcolumn h5 { margin: 0; padding: 0; font-size: small; } #navcolumn ul { margin: 0; padding: 0; font-size: small; } #navcolumn li { list-style-type: none; background-image: none; background-repeat: no-repeat; background-position: 0 0.4em; padding-left: 16px; list-style-position: outside; line-height: 1.2em; font-size: smaller; } #navcolumn li.expanded { background-image: url(../images/expanded.gif); } #navcolumn li.collapsed { background-image: url(../images/collapsed.gif); } #poweredBy { text-align: center; } #navcolumn img { margin-top: 10px; margin-bottom: 3px; } #poweredBy img { display:block; margin: 20px 0 20px 17px; } #search img { margin: 0px; display: block; } #search #q, #search #btnG { border: 1px solid #999; margin-bottom:10px; } #search form { margin: 0px; } #lastPublished { font-size: x-small; } .navSection { margin-bottom: 2px; padding: 8px; } .navSectionHead { font-weight: bold; font-size: x-small; } .section { padding: 4px; } #footer { padding: 3px 10px 3px 10px; font-size: x-small; } #breadcrumbs { font-size: x-small; margin: 0pt; } .source { padding: 12px; margin: 1em 7px 1em 7px; } .source pre { margin: 0px; padding: 0px; } #navcolumn img.imageLink, .imageLink{ padding-left: 0px; padding-bottom: 0px; padding-top: 0px; padding-right: 2px; border: 0px; margin: 0px; } apache-log4j-extras1.2-1.2.17/src/site/resources/css/site.css000066400000000000000000000014101252742764200236070ustar00rootroot00000000000000/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You 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. */ apache-log4j-extras1.2-1.2.17/src/site/resources/images/000077500000000000000000000000001252742764200226125ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/site/resources/images/logo.jpg000066400000000000000000000544371252742764200242710ustar00rootroot00000000000000JFIFHHRExifMM*bj(1r2i ' 'Adobe Photoshop CS3 Windows2010:11:04 20:17:20Ϡ&(.HHJFIFHH Adobe_CMAdobed            k" ?   3!1AQa"q2B#$Rb34rC%Scs5&DTdE£t6UeuF'Vfv7GWgw5!1AQaq"2B#R3$brCScs4%&5DTdEU6teuFVfv'7GWgw ?D:I)d$$%*)IJIWW@xoݸ+x7O[U1M3@ :i ?><^EY쭚n'5?|Ӓ#JuάU7kk'b vT2F{$ޭ:ۮ.Φmn"Rߛk()j /ѾF>?ݙrwSV_ǶvWcm{*zI:JZTLLRYyLSql ^x4~v͚ۜ8/%4LW~{i$-d@D9W$ g2!Ɉ澠~i)i]?>ӑkmn5?A;'*L8Mk:kk$6f?=7-2QӺn-S^|wXP=;`!۰K?GU2r-0[]ldacccʃ}hBG&Au(_tOGD/W(Ĵ#x hWomtiZZ1=͑$rnKcR|T9u)Gs岫kp/Τcߌ#ٻbZekD50o ."7YYY}16s>kFRǼr~^JƍAl0?l~C>Z"]Y]:ScjZ@"?=kwVO,!%o }󛣫nv?؝2v+l)(0ASZuI$*IKpH߬K; ' a>7yr 尭&R1՛XOÚ'Y0k{[,?}nUmf: Aip`>ּMMqCF25GF?bY ZZ@v!oՠ'ȏ]?_2.WЦC,wŘdSW}G)̺]V_^ OƳgU/h@A>e]y!qa?w>uf>cQǾkv!#eֺ~Sz 0Ѿ-e9z-5[u9EZoYǦەDĐtR)zDN\">Cwp{lKɍNJ֋I_ڡ-wbTz 6:=?m.}No/UµV`=4 v_mؤΗuZio ib#'=gRfuC8=RhajGDY=[/&m6=.hf׵}5mǁmdL;o~5Bgb43&nNX Y2Gy>IXY1 >?v'Kȴ s$moKsOau˨߳8'sc/ǘ? f~_͂xN`Dz 6}*,#r,c, C g3:;[w}{1L60ﹰ{+9̸J":?U ZWgMED)-XɶI"Equ2o:`|U9<IL<BORB䨬es٨{AcY_+7.:Lc;+.<=O^͏K"O2W%K||n6lypѹT~s!XX׎챾TիԨ^uh{%i}Ճq:f8cO:} }ߥS,%"B<, D?ຝ1z;z;\*U̶z@>a7|Qgt;1N?4;,ߝدu]ãg8:6I%Q>gJ<&Y4?W]kw=ᤵ1v累kPΗ.ȱhk]oՍO+*c`e>V.jGBˈG3 u\y:"F0cB<ep27z[߭յh@kZo3=#8G6suzN6>K+a7lxi]vC_,ŗ;i?3^oe#.9cjYu]:t1+}n28hα}>|hl1.~ Q3GxjgdCm%ēc:;%fKպq*+pƈ݌a N,7t)5kqߋV?-NK vѳnջ @M#8\OEМJCb?S/?mUK8S,ߘf6mM-uAYUJ` tdk:PSfh{'m5}?`Z/Yu !zͤ Vߤ?O]&x8\>0[%8߄D ſQqbؗޓlT݈^hC]lP}dfWTm6l}w=Eb^3?<[Emy86=Joƿ1] {V>WUʡeRKe6C~~&?KI:˄Dń|O@$M:>Dzzly5g,:!n&^Us^Q^H ?yf,Z=!+={<<:GvowekoF9Zi,n-ϊ@D}1OKP\$5~3p.^;1MNeȭ-u='~bֺ/Jn0{K }h~uqhx 6X~.\>(rCkt~Ur2_d-oUkbC|8[ G`_\) Vוar .mNB TN'IOTI%)$IKSInU:?%|$t cMeNpww8/"gM&b$+G$@x)iD 8N7KBtAJI$SDPhotoshop 3.08BIM8BIM%ô`ٻHTsH8BIMHH8BIM&?8BIM 8BIM8BIM 8BIM 8BIM' 8BIMH/fflff/ff2Z5-8BIMp8BIM8BIM8BIM08BIM-8BIM@@8BIM8BIM=logonullboundsObjcRct1Top longLeftlongBtomlongRghtlongslicesVlLsObjcslicesliceIDlonggroupIDlongoriginenum ESliceOrigin autoGeneratedTypeenum ESliceTypeImg boundsObjcRct1Top longLeftlongBtomlongRghtlongurlTEXTnullTEXTMsgeTEXTaltTagTEXTcellTextIsHTMLboolcellTextTEXT horzAlignenumESliceHorzAligndefault vertAlignenumESliceVertAligndefault bgColorTypeenumESliceBGColorTypeNone topOutsetlong leftOutsetlong bottomOutsetlong rightOutsetlong8BIM( ?8BIM8BIM8BIM 8kȠJFIFHH Adobe_CMAdobed            k" ?   3!1AQa"q2B#$Rb34rC%Scs5&DTdE£t6UeuF'Vfv7GWgw5!1AQaq"2B#R3$brCScs4%&5DTdEU6teuFVfv'7GWgw ?D:I)d$$%*)IJIWW@xoݸ+x7O[U1M3@ :i ?><^EY쭚n'5?|Ӓ#JuάU7kk'b vT2F{$ޭ:ۮ.Φmn"Rߛk()j /ѾF>?ݙrwSV_ǶvWcm{*zI:JZTLLRYyLSql ^x4~v͚ۜ8/%4LW~{i$-d@D9W$ g2!Ɉ澠~i)i]?>ӑkmn5?A;'*L8Mk:kk$6f?=7-2QӺn-S^|wXP=;`!۰K?GU2r-0[]ldacccʃ}hBG&Au(_tOGD/W(Ĵ#x hWomtiZZ1=͑$rnKcR|T9u)Gs岫kp/Τcߌ#ٻbZekD50o ."7YYY}16s>kFRǼr~^JƍAl0?l~C>Z"]Y]:ScjZ@"?=kwVO,!%o }󛣫nv?؝2v+l)(0ASZuI$*IKpH߬K; ' a>7yr 尭&R1՛XOÚ'Y0k{[,?}nUmf: Aip`>ּMMqCF25GF?bY ZZ@v!oՠ'ȏ]?_2.WЦC,wŘdSW}G)̺]V_^ OƳgU/h@A>e]y!qa?w>uf>cQǾkv!#eֺ~Sz 0Ѿ-e9z-5[u9EZoYǦەDĐtR)zDN\">Cwp{lKɍNJ֋I_ڡ-wbTz 6:=?m.}No/UµV`=4 v_mؤΗuZio ib#'=gRfuC8=RhajGDY=[/&m6=.hf׵}5mǁmdL;o~5Bgb43&nNX Y2Gy>IXY1 >?v'Kȴ s$moKsOau˨߳8'sc/ǘ? f~_͂xN`Dz 6}*,#r,c, C g3:;[w}{1L60ﹰ{+9̸J":?U ZWgMED)-XɶI"Equ2o:`|U9<IL<BORB䨬es٨{AcY_+7.:Lc;+.<=O^͏K"O2W%K||n6lypѹT~s!XX׎챾TիԨ^uh{%i}Ճq:f8cO:} }ߥS,%"B<, D?ຝ1z;z;\*U̶z@>a7|Qgt;1N?4;,ߝدu]ãg8:6I%Q>gJ<&Y4?W]kw=ᤵ1v累kPΗ.ȱhk]oՍO+*c`e>V.jGBˈG3 u\y:"F0cB<ep27z[߭յh@kZo3=#8G6suzN6>K+a7lxi]vC_,ŗ;i?3^oe#.9cjYu]:t1+}n28hα}>|hl1.~ Q3GxjgdCm%ēc:;%fKպq*+pƈ݌a N,7t)5kqߋV?-NK vѳnջ @M#8\OEМJCb?S/?mUK8S,ߘf6mM-uAYUJ` tdk:PSfh{'m5}?`Z/Yu !zͤ Vߤ?O]&x8\>0[%8߄D ſQqbؗޓlT݈^hC]lP}dfWTm6l}w=Eb^3?<[Emy86=Joƿ1] {V>WUʡeRKe6C~~&?KI:˄Dń|O@$M:>Dzzly5g,:!n&^Us^Q^H ?yf,Z=!+={<<:GvowekoF9Zi,n-ϊ@D}1OKP\$5~3p.^;1MNeȭ-u='~bֺ/Jn0{K }h~uqhx 6X~.\>(rCkt~Ur2_d-oUkbC|8[ G`_\) Vוar .mNB TN'IOTI%)$IKSInU:?%|$t cMeNpww8/"gM&b$+G$@x)iD 8N7KBtAJI$S8BIM!UAdobe PhotoshopAdobe Photoshop CS38BIMhttp://ns.adobe.com/xap/1.0/ Adobed           s!1AQa"q2B#R3b$r%C4Scs5D'6Tdt& EFVU(eufv7GWgw8HXhx)9IYiy*:JZjzm!1AQa"q2#BRbr3$4CS%cs5DT &6E'dtU7()󄔤euFVfvGWgw8HXhx9IYiy*:JZjz ?E*UU>8Wb*1WSu1Woڻ|(u Zj5m-O5Ubju*H]v*UثWb] V+A\ƽHNW,# .aڑkM2kŪY`]!&O!)c,?1]gvEH?d (32K"~8yB4}MgmNxfa[ 5ejIϏ,S[mơEYy?So "+z*UثWb_H]v*Z@〥kM \ؒhHǃ DpX Dt*fy~캧?9e?L~ytڻ=ܕUD7Ȝ^gsҲH3xGVbMVF]Fi,-f1K^i%QT|z|MMf,d[r(cte$je)4m11~3 /t;sMdy֖ۢ*X^YeA,2O&;1K9i$@~KZ>,=wWaԺ—b]H]v*" Cww\ǞER ;M˯ixH)/5YF1՘g>Yi9$y)W?[@hBm1.M$kZoo>2EqA!(y3$ t{XD"(!IiYͬ {=ڵAcisvxARWmT_%7qhƀGN"1<)d<=Zy̜Y`%XP֗ٓG`*:Xy^yc Cuh䀜@fDqH&Qv^`eF`ޞs":9Q 7:ؾu1/sGxR6"-)|N2h⠎!_?d~ۖ]v*H]|0cZξ\;f$)ZxÀjs@p}IO5~5\XϏ5%xi̘۠ Q $쒱iAd<p~edm^C%jPK\O&W%ɯK'($0ey%XNKmt ˃ b>B˰$yOGoq4f֕My)r8!d M&q"Fxvڝ x2Wn7]Ͼ_BB+u  ~1j '%%,#@aC]RVv:wge4g΢)Z0.()ogmKCxX(S'1<2y1 d-\Z@|ex// 够f]mcP`WvzO_)148(DznjJ!J6̟=';+w]WaKWb_H]dO 1ّ3$r xS8d+!%sQfAV$_,eŰi>O>PMRMy)ӗC ɲ0F[ +SSܫ]̨4A%AFj2' bT}vSXB%I(znr4JPYB^(!HIa҂t9o rw[\qt۸.tkӑ~5 6]/O0Dg7>m|^n 3Cܩsg/8rӧCu}v~W+oeZP;gf9;o ]v*E1APxᅦ,zI2 d#r@i>dVtp@5q!?.&?5\-$t֜@*HlvۉNg&.7Z<0JKU .OY9~-}?")Q(d[X[<޶I3K?I ګ#Mzup.xP i|FVM:ZC';f_9y*+wj$&ѹ;rbxxY"5PVyЄxh:_ p~?VmiO$pe$ڵ=rH!v [veFTbRr#)d$&i2Z x VPM?pb"(VnF{> kȠXftJxsvn\=J闉<(+RJx1D: E8YRLWvJ;zrē6zh-ٕ:{fS6]>_FPc 3Yއ*Zd3-(@$**o1Ӏr= u۞K)v*UثGlP+BJ1Fߧ y>fVuwΚɎ&6%q[9.Y>{ikxDnݓ4%W K4F\]21Qy0Z%9,l()*|?g5P)br{jf2G ˞F&ԯ҃k?aFfnJfN@2C渝Qcs#o#nS.Vرsc◤{e:ؽOIǨFo|XC_7{VY1I_iVzV%d9y'گ_'1|Py|o Wu1:]cy&=0aA/: w1%8o[VߙzӐ}?K{"B$g$PSkʹ8X7 ?vo ]B[oa#NK&l T_ՂRDH3p$yw(d8q^ =[B1XӾ krjK ,Ԡ巐ʬFj35e22d^I^xДִ=HZ6]hq7 62JUثWAꂖy8wOm_ey{ο&)G14?y'菼]:[.L~}#wQq>~II#٩H}e[+ms-ًo61!dd]ʪ濴aYWlEmg}`D%ƊOad"8u _veQOw{rIu&޴Rʹ]cro*ssIRvQ67MҡAZF;)ځse|]:+moy"Pio, Jŗڦcp!k_,;*E(jxe9dLBPRr#揳i ˰~<"(fWV*­_FR1 0I9鿼_vmaI齢#/Wl6/$!kr4̩^Mȭ^ZΟsߛpzg?w-^noO[7]qޙgre;<,(X|rN.?X`z^lwUq_֭yϭF.(Mk+$sBcsׄF:ded9-<=}.#C57%C80b?.<59Kck:4axi pfQrًG~?ݟr~?yڇoҵ+f˦۔R|I"%o3i;#>,]K/-O͍ %Nu@s vu|^cE,5kvdyv9E*yq:d9B=.ϴr -5,#FZG FYY\˯${9ɫ0*m"b Rz0[#Df I,_M?OmȖAsR k)1=}D#.{eVʕ)3ԒEv¼~ŗebf^L[㗟mw$-<<ĝ@ʹF9 iVZ5Dܪ##P~emA/08 +e%IJJ h)AMO<}skM_li\0Wbl ®_@0)bXG2P;Em_+,9X^)ʾX SIx期;1t]^vn}8cZ$ZlWy'ziy0M,(?<7L2 LW![C2\(A5yr]I16y$z ]l\ ؅0_[6g\sKO2Ȟ Q6Վ}[]cq1+>˨p[Ze.>_yU<`R*~ $;C/_+H&ʦYz:Oa$PsZJc1rY-Mq 7ߤ ϗ34E k/St>Ɇ^x톷}kaY[vM:YQәRD>r9néQ,yQֿdKKf3CorU >QC?m3OWhv??d,vH0U,}Ɩ7ǜĖch:NB(if"gI1 6LБC}lno j_ WN*bWSjѸ (T3"&)f8}s)NzI*/*ļ>sNSSRX ]Vf7nŅm?PI#VSR)@۱>mm&ܙc>*1 )-qə2,JT3mQߛ#q7)T-[jEnI߲ \gl.c1'66$4Q 2=@%oJ4,W">paE#>vMi|pp\.T80=T ȫxUޘxWH]v*UigBIaTQp<DT#M7dmi勰PP@iC\e;~?:V?gkS={ISV^5ଽؓTe NWD69-kR91) .?0uV{kAyS'$5*3_$keԦXҩRN^arIL4%ޥ;(LEv +l1,vY~?39 8D"oA7̎>H[ܽoGQi&+hrkY h7fS NȪov*H]v*UTd|!P NZ,V,rKfY jd+9'deH($`0ĀKi20gSN2]:!HlA8t$aE%W"P_"6+MS)3ZEnjm*0=qVWbH]v*Uت:MT, "si5X$Aɦ J'KcCK>D֗.|13Z^Qz])Qb*2;0"d\UB#j b]v*H]v*UثXZzvQLJS o!W-?q*jBOUQzUq*r*vv*UثWbapache-log4j-extras1.2-1.2.17/src/site/resources/images/logos/000077500000000000000000000000001252742764200237355ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/site/resources/images/logos/maven-feather.png000066400000000000000000000064021252742764200271670ustar00rootroot00000000000000PNG  IHDRZ#/ pHYs.#.#x?vgAMA|Q cHRMz%u0`:o_F xIDATxb`H  FFblnڳg!߿?x8ߟ? XQtƍ.[LL,##CAAM'O\WW7eooog o߾1cFuu5ABCC&=qߟ7j%7<Ճ Jϟ?yfZZZJJ ''gpp0666mmm c߾}o޼ٰaCoo/\۷oh'.33 366^zW<{sb['>>׌}'|vJzdt9&^=bpE@@*;;ɓ'@ٳg_~ȸz… 1y]>ucǎMO}}ŋդI._ sUU߿֭[@`&F˖-Ѽ}OgU:̪M͟"oo3.?Ú)Jz֝U ݽ?  XTwΝV8P^^2555sa`dxyyZtuu&>}:77䘘ٵk׳gϘ /ԁ&&& 7lxɞ[1K3+J2>eggaA3|~9gǚ37Va㖕e$)8QWW:9s$&&Q T#** 2p XX T`vww[...( ,b`\|1g]*˟ y|?';#?FAvVN=\JzK_`r|y9 y0*r Krp&@!!!'= ~a4)))`2??s;y>/~œO}]_EҜ;q֏, _~:ZGpYGLL"R&X "68~ X@=y`Vd@a?~@9w܃T_\\ ,**rttQUU&+XX@V%=ygO}{;vo/q?Blߘ$lY[{ET8u/NW*pGQ9X*))S{zzXX nnnSS &ܹRkߜ`1  SBl?~rr2<8]>5[V:rn_bz΢U1w?`M=%C.?2~3o=cS@J%+* l71~ ` L u}ߏot?#+'3'&.&L,18 .9}$,f.qfIvvF~t@ X#}݅ÃT~߽~ϯ9}9Y/A2L?M}a]X!DQp Q`'<% ?."T/|ݛ?~{˯nN%A/lls1?l\\<4t3@AM$]VM/` X.B`kXpk޼yR {:"!8Ab 6sssC+u31~QtH#0W ,Ae bh0Zʅ r6"„NSTOr?]PXm;8pKm6{0XbDغ FLKK &R`T4 XkC2`O08 t1#+}@.0^|  c",M7Bv "2<܁l`O!|`[˗/ `Kn.ЕGkY`2`ߙ1> eC`]N3,]UH:t*)$Kxǧ(@ĉᝫOB[l[80??{Ύǖ6$0Ctmذȝ9s& A Ağ AjRRDWcc#XHKx= b9`At+&&owK `3¾r ydx).`xoG€'Q @Cl?{,d0YjT i' ϹV@,D>'OB FV¿ _AVQΐ[) ~102@ԫ[&MD ةb `ρU;$tAvҒO۷oGͭϣ ""$0!xW2002x~"E^Q'+**Acٲeh-1HR0D@5L ρ5Ç ϯ_G `8FED tk.`3 #I… !UV eҥKAQXtApg!9L,l < _߃s-4!##4dD5d= oBB TWbqqq`:@dgF< J@Cх  @q 0*DF̬L> lNΧϮ3Z32rqt1;& H &-THsF0cyyypM^w" (hkkKL } 'ƒ]I@G':`={`Tpr3|~, | HKH`|\v H= ,V^V+*HA< `vY8 P@4P@Z':vrIENDB`apache-log4j-extras1.2-1.2.17/src/site/resources/images/ls-logo.jpg000077500000000000000000001216731252742764200247050ustar00rootroot00000000000000JFIFHH ExifMM*bj(1r2i ' 'Adobe Photoshop CS3 Windows2010:11:04 20:17:36[&(. HHJFIFHH Adobe_CMAdobed            &" ?   3!1AQa"q2B#$Rb34rC%Scs5&DTdE£t6UeuF'Vfv7GWgw5!1AQaq"2B#R3$brCScs4%&5DTdEU6teuFVfv'7GWgw ?z?L 7ΕhS͟66cW5u񗑏JúQV|46?5oƿXz=:kF;}m** "Xfֵ齛K+R @ݗeR=X?u?g]4^inɯ t];fۄgϪvؼߩW]EdCN}JEKJD9N!x* ݃`zfo62^b?YŠxNc$Y;9 =V1:f#rpNֽ=uy ZӞXh(AMn˪ր=Z?7ouv}`qX9׿/RgD̓]~h,&q2Dna/pT[ֺg`]¸lKO,l{[ 3~9t;;sr?m#QX4:=:K~?]O$7:׺@6kٔ꾝xߢg+,H}e6u\J5/e8DPi.fϭ{7R{}g>+cɯ? \({pvkZ6S W[YNM*SդWnP-k֪ wY*gSzoz$&Z{o\籛>?%Jz'Get?6כ=KꝐ?-R?Zkh{sm>4Ww}OO/+IR%}l=~Phvfznm~U܅;quMwR,4ŕ?{7TI%0\[k6k\:LX2𿤰S kCXkms]oMgAtKcYv qֹ%q(ɈqBF@" W{/u(`qճO9בc@/]#`e;ˏp2Wl,:k7=cF_Wpt;-66W`:>O*5cIc*p߯~gmG`?g.9 s]FokJ\LHw[/s3@@tn.w[SͷHev5~rnNxQKcHk7^4$ik?șL\2\65^=F<8\`xuڿĈoN7M$2\G 5,zOз pvvY='c.X>Ϥl{+nǹC>[p-?N8MRx 5swj]MWC.hu{HpT8qHu' 923#Sӱ>KZ c^:{J~oĽtB#?+BVc-{q"<]SYڹʱn1j%+cɯ? \({pvkZ6S W[YNM*SդWnP-k֪ wY*gSzoz$&Z{o\籛>?%Jz'Get?6כ=KꝐ?-R?Zkh{sm>4Ww}OO/+IR%}l=~Phvfznm~U܅;quMwR,4ŕ?{7TI%0\[k6k\:LX2𿤰S kCXkms]oMgAtKcYv qֹ%q(ɈqBF@" W{/u(`qճO9בc@/]#`e;ˏp2Wl,:k7=cF_Wpt;-66W`:>O*5cIc*p߯~gmG`?g.9 s]FokJ\LHw[/s3@@tn.w[SͷHev5~rnNxQKcHk7^4$ik?șL\2\65^=F<8\`xuڿĈoN7M$2\G 5,zOз pvvY='c.X>Ϥl{+nǹC>[p-?N8MRx 5swj]MWC.hu{HpT8qHu' 923#Sӱ>KZ c^:{J~oĽtB#?+BVc-{q"<]SYڹʱn1j% Adobed@[1    !1Q"2Aaq# 35BrC$DUbd%&V'Y !1"AQaq2B#Rb r3$sCScUTt% ?73W9~nq*qVmP'1RidݥlċB+c%D;N9Vmƥ{3)#4pg@4H E%1ld'lkkҗFafrGҵQzXt.(E)y,  \/~eyd-qITC1)o5JY-(I4d%xaLp%9F{/"]G[1x h,|\hNz*@1c{~?`5l(Q,E\\?e*7$Un]7^H܊܂2&UE(_Fo^ɍܬm -c܀Mp>$5sZaJ`Dn  "L]LЩr j2MJ>9xvY1"$6[ngxVӅ037 <8&4+IkƯARs˗X܃|gl""G!"brl o0ێGKBxD`)d/g[ 7,9ˆx@,HGt ~wZȚdʇq 7nhǫС:PaXzN *dà">m<4idd`-ka$Z bO@C0[_f|yFQL0ABJ{} ؋\ 訦fh搒YԎ:vD "aKtșKb~":rَ eLc@p_J[B:V \*/"ad @B黲) IwZrCb#07pۨ:;D TW%lX;( BJUA,Mp_Lu$cS.no&Kk43,}d"-IcP]U#M#&l 9PD@zGo<}or!.rn [@,TkVq3|˖Gll[$uSnde-1Bgg3d>#Fea&\~7hBHXěDCJVl x؎HݛBD7A  w`m,HBlSю;;x܊;Nz^7ņ$go1`uد4qpCqO4s_,Z+?Y6JՀelw,=<,X,R)$uKRR?Q[-:G`ܽ^?#98~ſ3d[4HqK{bH?mcũ`@':Oܕ^˟9o/)Hy(*Wfi-kȱIۥ*{XB{k#c oqԉeQ&f/uL\$Qś`Fu6CI~|}>6LyvfyQKgT(k)5ͦuSpv'qbKA5UnnǾD9(b%pԧ/;<,{t`$2 VM 92LX`~lG몋^SJSJSJSJWMQlIɼk8E&,"wݻvlѳtu9B" #+-9ZJ>b-@8Ǎ=n"%=h͜$&(Q !iJt444RkGfUR\jf3n25IrM^ș ( \IJۭ^wM0PV+$6!^;7hl#h&ý+[ 0p8 hc`\xW):n1n\RRRMGnH }RNY3;Yg-#( (B}U:VZ.=Դܔ|<[wrod +;zD[7H `qҕb&rqȵn.v'hGm:ܴrB5c0JiJiJiJiJiJiJJSJW*1R)rb)bS >Rƍx~dB*`{4f+ "ԓj<!JX#m"}:o,C5gA{)5$PO.lOBE7`q|ml.GMiItu,`+D[G0\xLZYE(DIH<)F:jE$bId7!:bS)*}{rqnRC)($]YMͮBORzuA[?'q3//wʍїG:$iC:c%,bPvB1DTj 3&d̂htC""x)} <9.qMB7$غpJJ|yxNɺV70G |A~b"/N݌ 7RMN(::%3sKAAT7(Cǒɉ"1Ii C:;6./6(^&u\FPqfV5S-v%ԒQ5;PY餪 UP}/Wt;N_l>O|ZMJh{ee5_N}=X HChbA,{\u:.]f Έl9t(zS:/WUezV]P#p3~qqf<ۊ|<1\ JXkb@'IפÑ7JtmO0/)t*$Glԍ9*3@Dv˟#:# Ax\@G[~>!\q+"#D" TpY1A+v+ޝ(dڪ #ؕTev"݈, AsS؅b'~'CV遑 s4uKAR7[|+`<黬 Ȋ!= zbZEO=`)&{S1?e&"4L#=Ln"sޢP"~tE7Ye }S?O@ W#?i7}LUŌ0-Y%[c"|D$t"C cQ>bD7`ڦ)K ֒C7BVְRMoVψ9[tS33h.-6kʎO֖R"Y$]FNE:%LVAD s@ oO)nrX v$wnױ62=)i1b߼Qm ʰAM,,ՖmnqV،dZRT$EZk" ?𥝳TYU$رO !q` `($Ȁ5w&NGp5 y|؜{qobq37I1d(*JTEƑFRq//&18ǒX2j.MѵƌdK~~vpUDTݜ{أJ^)LW:&DzF.XݗHr 8Ʀݲ<=oL̞U!Ɇ&#e, ߎ|p\=;Q9<<D?4 nƠ]ch*>ӂ4oNMqi#cp, oq:1!zFs0XsgJYqe U`]a.hA3G++)sHM,R--H)#3s3V@a)>ۯc0]ەǏ!6dGOZ[(|9XUC H:5#0apmb J,}TFSܡ숪&jchhUDz$*".\Sqiѝ4 ۅY.YGGCԚ3ohH[\?5r"xvD+k9BțVbsH%&VX*WEpc})X2^AXֱH2f1[d]>.Y*?TZG+G<Eu.L -֕}8eš9<\kŐi#5B@G 3IF&W#tFI0:WBXj*O;,yv nvy!.L.BfVYؘ*K E%DO#ZU'""sVr.ZZpOVxWfhQ3D#rS-dMȓiOfo~*VYy: ɜOX0cJMΉ{WlVFVZ(|="BIUR1Q/o߈AkRͼdm}-XSgt[O <C~3Y+[di[8 v5S\OaWlϭ%Y< pC b9i&"y_,&7KPbC33/0y-U1ܢe=dqU1).J*Iyw&JyIIY &6R HM:)cT^,kK[RX@Q(xg&QE_hIz~TQ'auCp!"2B֛/[.9aV 'Y: ڧ %;Ft$d_CEJ0%ۀ<A2MM돱lBWkq*AlR?! ;@"1جw 6l~ɝ2"2vi<,5bj~/6]n*ণ$%ʢ`LU#Hۧǵ*m/d%U0O( 6[>K!1}Zy*"y-;BD\7uFtE[;@E?ʍJ&r0x,jؒ.ЉaJLWjBjF$JBT{kԈA_Hߔ均!r: 7b?((n<=:i5g/w$aLȃwtXZ*r3-Q\PBo֫R" $= Ƴ]X~ؠb"z÷zV49Gi<|`ȑkVO$(D06*lBJ`e!X~5Uu\^IoW \H NWYa2tvX|<ʼnrm)S= FU'S%V/Juki goh^0R#nz^n;y VaKc\T:cNX+z^ Ya&$HeASr)ʋ\Uy'99rٍluYyfYS*7*hNfYU,`21[}0*5fxVl /vT ++UĘ'5IF=tzHҎgnEveF2z,Cw+)}uɼzɹ#1zc$3շ-Fu%NW̓`sqd2ñojۉ:Ddy=x8[^S!P]i,&Z*T\b2LU2(#NA7H$t48ykb#ɗ-yW0cl#xɒl<Dk\M.Oe$f D1=%#iWBrQF}|VXP=N;aEZ)O)vuI nRua-WW0oG/ͯ-s_JSJSJSJTvR!f U];fJ^F5& HB@$˳IeR& N]nO&>F6TDUP2I}:߭süμ$y&Fr~8Ɖ!skjh&Y!f/X@G:/ ?W,vFL@ly(4U2 RO\C;|ԫ íeծ,+g"vt:BR{G6Td zT} I#>Ox{%WBuYu\e vtPNx.%y^>2M ]lyP$dl:9)Cfu)w 31o*e혭UMSLṄV 뙸JK( ӿR 6cu:7Vo+fm~*eh$xLDqȥV̾=Wp9bSX$*[wT3Ÿ]E孓 fxk`tgU~41Շ,ˉ#1b'㗑c/ 1%]E6:pDID*C&"F0L_I1Ϻdz=['/q߶mQHS Rчd :$[˓ g9Lx^5[ZA@g ! if6+1n`8pv@"N?y1"^VŗFw'JɎ5U?b:PV7㙻;qK4VITmF[`,^"jngI9QitEA2.ط&82@7(`a%͇ɲ%&=y 2cS^&T\߸0|_>q,ˉs}2(IJB#'iJ˨Z>NsG)MFL dU @M- (rvouyV,qr123X6V@@a+< !f?9c9Q{Vi,Xb44۵8 Lw(ódPT_&&OcV ] 7b~(#lmi3SFX6'{h|ox,ظ%ŏgF8*di@6:~8ʭW4h aE+)vD$L Tɩ*űZ 1LuESJa7YzX7wquT=sXˀu5=ETXGԶưixGo\iTʪHt'庱\դYyM[lzӊn֒hܥtҸ'JlJe%^GP@Rp6ۄxzw׌ tGE=$ #gq̎1gq(x#{I7ҏj݂vV8c,L^v .r}GDIT$5k! %NdbĘ˺oQ0?lz|?6N $:!Ac/j<~G g}`+pKG`OFMH @cS|mVUO,(Rx^-n{mHU#3w5驻­M̉k&P+ H577ʗpvc2_[@3(%L%jH\T^X*ē.: SJyߺFIە,v&%d93Ǝ,]lv;ƾzKlFەJP$<#nQIN e ߲lo1?]yki!ޟd>%dN&s2={j8TPlS|]}oޟplUorhB3& )l*6&(2vtݿCJ} =jwYQR kos̞|TXnC۫I(c7ٸA2 Hz N}~[w5Ȼψ6#uٛM&Wa7lDZ !S P1ҟҭc\%*ax舖CXW/5]@|~A5[41'ROB/䛘Ռk1~jŕWXBAemλw7H.ؓW\]0:Pl ]رfJK/U'-0 FUB7! 3*k*'\guM7*鬊^%`Y gSû4ߧJCaWl\!)W7d?~Ez8IoҥURP0Gwv"SoGB[3R o#[U}v&q7 G"n&fS~VFMrGwVۮoJSJSJSJSJSJWT]5Y2(2j@P)P)b+#(E=A"Y/.bDJbύ"]"1jլWpEd&Jb·pM˽`ʂ%A^- #$T#/ls^?ɕ<;3Ǐ#(;c:O Cl]1uK,t[r\=+/2Vrt۷"u~`dWh}Z|R*wQ] Y2r963>ӓXrj*${$LSYYVׂ<38adI߅p53&XUCjXS "+XZ!V8'SAVTKV NPʶ;6r-M}7yxe|y"M7PF{`Ӗ @}:古v,v-*"O\iVXKJ/>+H3ȲJUɨ$-LİYF Z8#!'0cK2l`7_ZȉP8u(kÍ9Γ3ovݒ=1OoؑR4E})n[^>v ~4|5ilc oE:Ӵ^1![`FǬvp& %l jƠtAu7@}ιLhr;FdFJ6_I^ ҹl\g{o"q܍&CeBL7LB>3=3u ڷ=(5pe.EUZ~iJ9̐) f6>EASDS3u7Yb{d7.4 >垹xQd&)*=X[80@X%4hv}?axbQiYS,Fò62J7mv.HMԆg=,'q)&~_&[o-$N3^,Y* J6iIzwqL}M!D^5;"b&,NٰdA*x5vF+ȬmyLV:0+q-Z퇡l*2B%8kDUE$) &yƌ21V{^=;.KKf)`c kv&o J *֬`F /x5zv^j\d{0gPH)6L/wx6ex TZҨ {d|k}X%RX(I^16&/w*?PJ9(~qR]#T??t}t~Lr71P+LGվ@@+e'PR*Њa+$Yc eym "~1ITG;HAUH"U '໶>G%݄eU񄌫ie$ݙnUa9|(g? &F{_QGc{7b KJE,( CG'jT,'8dL;ovܳ^3{?d\xebPn/ڦ!VHA㱃WLGJJd!0 G"1`JJW1'Xa ;_6J J^~J>بr(g$F=E*8]cweM˄vSCD={8RAU r)|ǘبا'wm (]ą@%@ ?^@hX],fOXȽdb&ԉZRbE&J 0 iM'f&(9P,0t4}U],e™)0j])6S؏Yc~t5NrMNK!vկb@-'s塁E~\2[p(pïgM~e*u& A[gɺmn4)̡nӨ/ D TLp7)C|'Bt~Y0'/t~G ?AL4ruOrP~)X7(y 2dL>6nQYѐ^ki-"NYQ1U?#wr仨1g*WM AOY8Y:90#H̏'R雱F4ez}{2-qϫ"SjC$-c@7l=tf6ȑbkvn, pڬ lq%̈&[FvW*5K.=e`:ײEQ3Ôߠ@t d)HiJત )_ PDvҕ0USҕ "vp0@׽:xPh62|>kFkMexJ@lZM'R 0"8Y sXa2'wWFo ,UXF~G*]VRRRJSJSJSJSJSJSJSJVIov"Pkyyձdd*@/H";tK+I~-R[6w0/lɒFL."6EhEzu1wwy˲ q1o'fd3&S¸쉺uNy.h$˴@C"fBrLP¸v܍rڱD~QUf? YٸvV LX#i` 1@֯7r=e +t,뢓Cu vEAd;Y*KS2ɢd\9NՋVfDk< 9d5I HXQ`A:7O7x/aѬoS] BE9ͳ+P6X9\١hI6ڢE> .ZNxYkD K^;ڋK2ݷ,x#o{Ϥ.nSSqb3),֬Gy"2+ϖ&ǰĘs#M5je$:zk2OtDY{!Iحxmqt@t~r=yD*,?謣IsP4_0ͅ!aVoz>͚%2MmYtDXGQryDZcIбb#Boa`K5Uwe5B6/n^țs: ]B n[bgَ~OvǕ5xľRU,Ga\ `ʁ]nn6..9P r+$$kb> v4s|d'十ѻ9e׊_f ĭ0v~iq8v옑Lq7HcǸ؝u!nOy|u9^In)9ry@Hc3.l|o~:*r*MpWlXX:",m[qX4IGfd\+05ə—vyњWbJ:U$J"A1&kc&AiAAVw`Wy`&c5ooQq",k|*[SF<}`&q5w' wAS9+4P2mo y#ͶH^ 1M3J.G:4kWAstJN ιVϲ_YDks9#>v{2FLf4YX) \dzEbTDLnx6܍]cƅ\kgӨA=j61LX9ذC2OPaQTHɼ-.CxiuMugI<6[&`ke=Q/ ۰M„@ jhە8Q X1B#HޒEյn{9XH%ʯzrzȬ~R|"[hJ>e [U@x1LvN2:xnlmg{NE:u 5\^ڔvNi87p?/NLEIXI@QXݾe ݯwkgzPRǖ z䤝q4К,Sx]`d̪+ vN4/"aUFߦZuz/Ǚ+۹6ĸ`(=%WdrJl-Q ]y0KUM GTg+r;՞6O TPzKӍ䜣mޛø{NVWOW{\z)䍫ysq6nd 33ia{}oIF=xQ# URl%9`|UG)M)M)M)_JSJSJSJSJSJSJSJV|9&h 2>MXZQ(u~0[ ح \: JֱLOmcjY2EZ}Xc9\h!s[`+x.2oڪP:* H !鶣N7U>.ѕ4%c'e DU Ubx7G&\HߕuA=49,%|wܦ!1b2sX$SVc8a*B3:c!mܶNgDz" g $nd)5(,E~3yVߴ䤹%3 '}qnQZr&]TP=5ny%*5sEUpU:@P[doܲ06HLXLM Yâ/"~CzD@'Ѳ"׶{\^S#1s) #TVghJ Sz9Y6:Mic)˸>e@Gujf[ `5v%d~͹xհ,۔B] V4G]Dڙ[kv5ko ,Zrn\xCEuTMTpY͛yjALxd~GTõB9Ѻ8#&6OBJ}$j+;9vZZa, J HLC"]d,a LA;a1NJ^''!0uDUYjF}Aֳo?m9<elIb$ukl܍ȴyXS v)\֐A,٪%,T:]1p}\?ٲ۱scќKJ{;0=Uk|&8Llrnbi#u_+ +CX%("^,@Q+lbO" );; ``Tg&(t%^qTgpdFmA"\_YtpI2%YTZFءbE% PRfVp& 7l\?9TUOr˗.C!m&,M_Q5{ɰcnٰů^77m6P!@&T+[e3~.1 ~f#xvÄgY*@@b)tn`6{,c]•_J*[V狰l#EpԷDiBm yb$c%o.mOKC&RYL(Wcj긙/uկCO}j|s`n`(6:^>GFD®Y$nDQ66x1 y,/n^o0j܁1nw2HF_ q<k:TchJ9K2.U>nkI5$EUJ]q;3m}Ԭ vr-ޭwGPMm{ˁV>-fMCN^ ^ ]RFJE 7c$SV,l}wq(b>GT0}l_`]&Z1,-|QI9#%&SPA[bQ6_{b9R.ZMv*0d ^re 1ՙE+ӽqY3A>0rL)\{ kRJz1Է CА~6Ļ&NFDq=KAK{A,n+_짏qG$ZqU_xs4k bXw*{6 [22(Tč $v쒞A &Ѓ{ k><ٸok,cn;K%BBĐzǐ[WѵYË=rbar%r/tP*+9HM`V۳sia*GoW΋+HHU W2wnE)}si,=pu!VqdF1RwSj;qX{"kLQ_KKE)T[\+ ud(|7\WsAHbrA:F-ڃӥb+)¹GڳR0M2/FuT(`@SS1򜉊^b9}Ͷ+h;o^J@+UF$uUNsl}/n{>hO)>X#NJ"}cm+[Va8:"ytM6eBB1*S*#~BXN==·"qnwT7:6|_cٿ[~#7#"3|cYz[s`ue⺜( ʊ MQZ3n.4k VW/̫Џ\7"u9Jbtje\;'p4UĽI7P}mq2ȅ1p?ZA62䰇cI$$&NLP[>Uԙ)8b'#FM˕VIH v$iYLT.1u^ػ3*ģD}oه+'A gXZqOY¤5[ԳD4a}Up&Nx`,͂Ȭ}I%`. F|<ۇmb)"w ctIIlb-«i%W|s4tm GةҀ9(UF`=EM[XBbɶBi?Q .RC  \^׳ZܧEuh$uW+&2.}EPP VX5L_wӫx#b!^~bF1~^"/8HXt́EUwj@OSae8V ʠcjk[_ w5lG> 偹 ) k[G{^vrx[${ e9&1haQtt+2):QAJ zqq͟qu2V  ;6=L>ـ@d+qGT5=A/<1-WBdu$ 0 tX<4Ԣ-RD[QHܹ;6fɻ݈DS#Hu(.]JXZ mnfϝe1"ipbEi KkAb/sMճQ2^ "F(bTЖ! I~ή-ع<[FEA?e529ˆǬbDѨI_B  7%g=*'dmot'f={T$td=D ԉY۝-]'uvK#jK>nlwlj48qY oQ]M$bĵ39G["Fv:MY J8 ;0,9\ŲKr!mroo4B6Jf ]$\EȾ`vq?vhDq݆X#61~qPČ_quGNn@R Xu$N.?mD"gC֘VQA1ڂ +c l't  "å;ԸOOooRu2[EB@{uҢ}N#䰘V$^S!Ļd@AVw]9ߑ(BeS6]sՔ+OS `nz-*A33jU;rISHJ=*@ab;vgNEBkҘ<~qvgo"Y \VjaMER/9Ӊ 9 \u;?m$ jagvN]qy.n~\y,j1bpѳu$:vzo?ZmWW3Zq9$$RUk7[v ER Kt%9x)ڳ ,T ^m=bXnLC^hpdZn6X8GVUU]g3D]\6:C*P}F#wnnf=-*mrBl[/y%)^u~quXd%HU]656(j(vdڔ0gpi16ueզֿzn^(wg8?/T~Ϣ5{>I+^,aG4n̦iQ?a%*%xq} <{\\d5D7NEg 伧dpv2ۯKjħX؅`ZHop101v@ap%Sa&!$\ KґU<ɏ 9^ڊovX )ѼYYc& W"QՇwDv.=rܳIPzϩTXXUeǵn]"#px\nIYtWv* QNvrC65ɇx Ʀh?oV5FKrM1(71׭H~ p#- fa)*QN_&sܮ**}?WV!I`ö. Id21*/sS |.헙dƨ;褷ɹ7aތ92E]d6/4sVv%r2͖Գ0TQ6)IǿƨpT Msk{\בQ_wFܡh\f+#`zNP+ PTCDQ[ըB\5'd,W= +)^GNםGNa,yt:\I4 N۲8_hYS *J`:O:9v/ d`eYc 12 J6H:moo~pV7deR*J?xաص;Adh͌L{fɔVPD@1cp|ÖdrgM**p>=zf?kH~эmb,ıbXI_ʙO'[|fb\G}f:&vr5oTԟy:~1ôǵ$ͨRK {vQ^k}XៗT1$ja,  MC.2cwC*7JQ2%,-JS[$}b{!wUU(6N=bIbb 1:@߰TN|޳vc}1oS >Uy?:7 T&6,y =%JBLEyG&4'̠ $/򔼟hgjc9[!X0Ѐ =QYwߦss3 Ey2vV$  J}dXn_3xҷҕ?JWPiJܬs㖒.b]I8K2~&BReÉzlih4  s&3T.koSyƍdVY6 cbwݟ4ɉm$@?.#]ʞ-|(L^jr(66@M>a '5@M CpL>GUA V @J3N")x(G/.g$%\{34Ib&eIbF/2 5ƔYnW:{_I WN%B:UBt$ki$򣉳DekRT̉'"edDLF5tG[ fH#r%gÌ,{lHZ ۨ"^O9 9tySH+FBe V5xCƑmKe1Ưܝp݆n?Hjp(R:~d-7 0ao5)\!aynPƋ`y""AS:R.0$ǩ$B*n)H&=w̼\mᯡI%^lQ 'v>%9  ~U g1QZHli6 ٪Ƭl@}A+>6>ҕ? |egu IzulRsP5 ˣ#ȩ8IjC t^"Rp"`77fl\%H1TS[k~&46U1LdVKdS X$s\.uWrȤ,AY>}ʽ52J߹驉nT]lpm#Hvϸv:͂Qr@$al RLUXUJ` )\J` )M>RPiJJS`o+>R@4s+4s6ҕRPiJl@}A)}t4444JSJSJSJSJSJSJSJSJSJSJSJSJW}ץ+Sn)}[տ}7ҕ[7o])^XT/^J6o_}[JJiJiJiJ-?ߧRq^_ҕmҕҔҔҔҔҔҔҔҔҔҔҔҔҔҔҔҔҔҔҔҔҔҔҕapache-log4j-extras1.2-1.2.17/src/site/site.xml000066400000000000000000000053521252742764200210260ustar00rootroot00000000000000 Apache Logging Services images/ls-logo.jpg http://logging.apache.org/ Apache log4j images/logo.jpg http://logging.apache.org/log4j apache-log4j-extras1.2-1.2.17/src/test/000077500000000000000000000000001252742764200173465ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/java/000077500000000000000000000000001252742764200202675ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/java/org/000077500000000000000000000000001252742764200210565ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/000077500000000000000000000000001252742764200222775ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/000077500000000000000000000000001252742764200233165ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/LayoutTest.java000066400000000000000000000100551252742764200262770ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j; import junit.framework.TestCase; import org.apache.log4j.spi.LoggingEvent; /** * Tests for Layout. * */ public class LayoutTest extends TestCase { /** * Expected content type. */ private final String contentType; /** * Expected value for ignoresThrowable. */ private final boolean ignoresThrowable; /** * Expected value for header. */ private final String header; /** * Expected value for footer. */ private final String footer; /** * Construct a new instance of LayoutTest. * @param testName test name. */ public LayoutTest(final String testName) { super(testName); contentType = "text/plain"; ignoresThrowable = true; header = null; footer = null; } /** * Constructor for use by derived tests. * @param testName name of test. * @param expectedContentType expected value for getContentType(). * @param expectedIgnoresThrowable expected value for ignoresThrowable(). * @param expectedHeader expected value for getHeader(). * @param expectedFooter expected value for getFooter(). */ protected LayoutTest( final String testName, final String expectedContentType, final boolean expectedIgnoresThrowable, final String expectedHeader, final String expectedFooter) { super(testName); contentType = expectedContentType; ignoresThrowable = expectedIgnoresThrowable; header = expectedHeader; footer = expectedFooter; } /** * Tests Layout.LINE_SEP. */ public void testLineSep() { assertEquals(System.getProperty("line.separator"), Layout.LINE_SEP); } /** * Tests Layout.LINE_SEP. */ public void testLineSepLen() { assertEquals(Layout.LINE_SEP.length(), Layout.LINE_SEP_LEN); } /** * Creates layout for test. * @return new instance of Layout. */ protected Layout createLayout() { return new MockLayout(); } /** * Tests getContentType. */ public void testGetContentType() { assertEquals(contentType, createLayout().getContentType()); } /** * Tests ignoresThrowable. */ public void testIgnoresThrowable() { assertEquals(ignoresThrowable, createLayout().ignoresThrowable()); } /** * Tests getHeader. */ public void testGetHeader() { assertEquals(header, createLayout().getHeader()); } /** * Tests getFooter. */ public void testGetFooter() { assertEquals(footer, createLayout().getFooter()); } /** * Tests format. * @throws Exception derived tests, particular XMLLayoutTest, may throw exceptions. */ public void testFormat() throws Exception { Logger logger = Logger.getLogger("org.apache.log4j.LayoutTest"); LoggingEvent event = new LoggingEvent( "org.apache.log4j.Logger", logger, Level.INFO, "Hello, World", null); String result = createLayout().format(event); assertEquals("Mock", result); } /** * Concrete Layout class for tests. */ private static final class MockLayout extends Layout { /** * @{inheritDoc} */ public String format(final LoggingEvent event) { return "Mock"; } /** * @{inheritDoc} */ public void activateOptions() { } /** * @{inheritDoc} */ public boolean ignoresThrowable() { return true; } } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/LogCapture.java000077500000000000000000000042101252742764200262260ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j; import junit.framework.Assert; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.VectorAppender; import org.apache.log4j.spi.LoggingEvent; import java.util.Vector; /** * Helper class to set up and capture log messages. */ public class LogCapture { /** * Appender. */ private final VectorAppender appender; /** * Expected level. */ private final Level level; /** * Creates new instance of LogCapture. * */ public LogCapture(final Level level) { this.level = level; Logger root = Logger.getRootLogger(); appender = new VectorAppender(); root.addAppender(appender); } /** * Get message. * @return rendered message, null if no logging event captured. */ public String getMessage() { Vector vector = appender.getVector(); String msg = null; switch (vector.size()) { case 0: break; case 1: LoggingEvent event = (LoggingEvent) vector.elementAt(0); Assert.assertNotNull(event); Assert.assertEquals(level, event.getLevel()); msg = event.getRenderedMessage(); break; default: Assert.fail("More than one request captured"); } return msg; } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/VectorAppender.java000077500000000000000000000042471252742764200271140ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j; import org.apache.log4j.Layout; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.helpers.OptionConverter; import org.apache.log4j.helpers.Transform; import org.apache.log4j.spi.LoggingEvent; import java.util.Vector; /** An appender that appends logging events to a vector. */ public class VectorAppender extends AppenderSkeleton { public Vector vector; public VectorAppender() { vector = new Vector(); } /** Does nothing. */ public void activateOptions() { } /** This method is called by the {@link AppenderSkeleton#doAppend} method. */ public void append(LoggingEvent event) { //System.out.println("---Vector appender called with message ["+event.getRenderedMessage()+"]."); //System.out.flush(); try { Thread.currentThread().sleep(100); } catch (Exception e) { } System.out.println("Adding event - timestamp: " + event.getTimeStamp() + ": " + event.getMessage()); vector.addElement(event); } public Vector getVector() { return vector; } public synchronized void close() { if (this.closed) { return; } this.closed = true; } public boolean isClosed() { return closed; } public boolean requiresLayout() { return false; } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/component/000077500000000000000000000000001252742764200253205ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/component/plugins/000077500000000000000000000000001252742764200270015ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/component/plugins/MockReceiver.java000066400000000000000000000047561252742764200322360ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.component.plugins; /** * Mock receiver used by PluginConfiguratorTest. */ public final class MockReceiver extends PluginSkeleton { /** * Is active. */ private boolean active = false; /** * Host name. */ private String host; /** * Port. */ private int port = 0; /** * Create new instance. */ public MockReceiver() { super(); } /** * Shutdown. */ public void shutdown() { active = false; } /** * Is plugin active. * @return true if active. */ public boolean isActive() { return active; } /** * Activate options. */ public void activateOptions() { active = true; } /** Get the remote host to connect to for logging events. @return host */ public String getHost() { return host; } /** * Configures the Host property, this will require activateOptions * to be called for this to take effect. * @param remoteHost address of remote host. */ public void setHost(final String remoteHost) { this.host = remoteHost; } /** Set the remote host to connect to for logging events. Equivalent to setHost. @param remoteHost address of remote host. */ public void setPort(final String remoteHost) { host = remoteHost; } /** Get the remote port to connect to for logging events. @return port */ public int getPort() { return port; } /** Set the remote port to connect to for logging events. @param p port */ public void setPort(final int p) { this.port = p; } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/component/plugins/PluginTestCase.java000066400000000000000000000601711252742764200325430ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.component.plugins; import junit.framework.TestCase; import org.apache.log4j.*; import org.apache.log4j.LoggerRepositoryExImpl; import org.apache.log4j.util.Compare; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.io.IOException; import java.util.HashMap; public class PluginTestCase extends TestCase { static String FILE = "plugins.PluginTestCase"; static String WITNESS = "witness/plugins.PluginTestCase"; private static boolean verbosePluginOutput = true; private static HashMap repositoryMap = new HashMap(); PluginRegistry pluginRegistry; public PluginTestCase(String name) { super(name); } public void setUp() { pluginRegistry = new LoggerRepositoryExImpl( LogManager.getLoggerRepository()).getPluginRegistry(); // delete the output file if they happen to exist new File(getOutputFile("test1")).delete(); } private String getOutputFile(String caseName) { return FILE + "." + caseName + ".txt"; } private String getWitnessFile(String caseName) { return WITNESS + "." + caseName + ".txt"; } private void setupAppender(String caseName) throws IOException { Logger root = Logger.getRootLogger(); root.removeAllAppenders(); // set up appender FileAppender appender = new FileAppender(new SimpleLayout(), getOutputFile(caseName), false); //FileAppender appender = new FileAppender(new PatternLayout("%c{1}: %m%n"), // getOutputFile(caseName), false); root.addAppender(appender); root.setLevel(Level.DEBUG); } // basic test of plugin in standalone mode public void test1() throws Exception { String testName = "test1"; Logger logger = Logger.getLogger(testName); setupAppender(testName); PluginTester plugin1 = new PluginTester1("plugin1", 1); PluginTester plugin2 = new PluginTester1("plugin1", 2); PluginTester plugin3 = new PluginTester2("plugin1", 3); PluginTester plugin4 = new PluginTester2("plugin2", 4); PluginTester retPlugin; repositoryMap.clear(); repositoryMap.put(LogManager.getLoggerRepository(), "default repository"); // test basic starting/stopping logger.info("test 1.1 - basic starting/stopping"); logger.info("starting " + plugin1.getIdentifier()); pluginRegistry.addPlugin(plugin1); logger.info("stopping " + plugin1.getIdentifier() + " using plugin object"); pluginRegistry.stopPlugin(plugin1.getName()); // test restarting and starting when already started logger.info("test 1.2 - restarting and starting when already started"); logger.info("restarting " + plugin1.getIdentifier()); pluginRegistry.addPlugin(plugin1); logger.info("restarting " + plugin1.getIdentifier() + " again"); pluginRegistry.addPlugin(plugin1); // test stopping and stopping when already stopped logger.info("test 1.3- stopping and stopping when already stopped"); logger.info("stopping " + plugin1.getIdentifier()); pluginRegistry.stopPlugin(plugin1.getName()); logger.info("stopping " + plugin1.getIdentifier() + " again"); pluginRegistry.stopPlugin(plugin1.getName()); logger.info("test 1.4 - restarting then stopping by plugin name"); logger.info("starting " + plugin1.getIdentifier()); pluginRegistry.addPlugin(plugin1); logger.info("stopping " + plugin1.getIdentifier() + " using plugin name"); pluginRegistry.stopPlugin(plugin1.getName()); // // test starting of an "equal" plugin // logger.info("test 1.5 - starting of an \"equal\" plugin"); // logger.info("starting " + plugin1.getIdentifier()); // retPlugin = (PluginTester) pluginRegistry.startPlugin(plugin1); // logger.info("returned plugin is " + retPlugin.getIdentifier()); // logger.info("starting " + plugin2.getIdentifier()); // retPlugin = (PluginTester) pluginRegistry.startPlugin(plugin2); // logger.info("returned plugin is " + retPlugin.getIdentifier()); // logger.info("stopping " + retPlugin.getIdentifier()); // pluginRegistry.stopPlugin(retPlugin.getName()); // // // test starting an "equal" plugin after original stopped // logger.info( // "test 1.6 - starting an \"equal\" plugin after original stopped"); // logger.info("starting " + plugin2.getIdentifier()); // retPlugin = (PluginTester) pluginRegistry.startPlugin(plugin2); // logger.info("returned plugin is " + retPlugin.getIdentifier()); // logger.info("stopping " + retPlugin.getIdentifier()); // pluginRegistry.stopPlugin(retPlugin.getName()); // // // test starting of an "unequal" plugin with same name // logger.info( // "test 1.7 - starting of an \"unequal\" plugin with same name"); // logger.info("starting " + plugin1.getIdentifier()); // retPlugin = (PluginTester) pluginRegistry.startPlugin(plugin1); // logger.info("returned plugin is " + retPlugin.getIdentifier()); // logger.info("starting " + plugin3.getIdentifier()); // retPlugin = (PluginTester) pluginRegistry.startPlugin(plugin3); // logger.info("returned plugin is " + retPlugin.getIdentifier()); // logger.info("stopping " + retPlugin.getIdentifier()); // pluginRegistry.stopPlugin(retPlugin.getName()); // // // test starting of multiple plugins and stopAll // logger.info("test 1.8 - starting of multiple plugins and stopAll"); // logger.info("starting " + plugin1.getIdentifier()); // retPlugin = (PluginTester) pluginRegistry.startPlugin(plugin1); // logger.info("returned plugin is " + retPlugin.getIdentifier()); // logger.info("starting " + plugin4.getIdentifier()); // retPlugin = (PluginTester) pluginRegistry.startPlugin(plugin4); // logger.info("returned plugin is " + retPlugin.getIdentifier()); // verbosePluginOutput = false; // logger.info("stopping all plugins"); // pluginRegistry.stopAllPlugins(); // verbosePluginOutput = true; // logger.info(plugin1.getIdentifier() + " is " + // (plugin1.isActive() ? "active" : "inactive")); // logger.info(plugin4.getIdentifier() + " is " + // (plugin4.isActive() ? "active" : "inactive")); // logger.info("stopping all plugins again"); // pluginRegistry.stopAllPlugins(); // // // test starting of multiple plugins and stopAll // logger.info( // "test 1.9 - starting of multiple plugins, stopping, and stopAll"); // logger.info("starting " + plugin1.getIdentifier()); // retPlugin = (PluginTester) pluginRegistry.startPlugin(plugin1); // logger.info("returned plugin is " + retPlugin.getIdentifier()); // logger.info("starting " + plugin4.getIdentifier()); // retPlugin = (PluginTester) pluginRegistry.startPlugin(plugin4); // logger.info("returned plugin is " + retPlugin.getIdentifier()); logger.info("stopping " + plugin1.getIdentifier() + " using plugin object"); pluginRegistry.stopPlugin(plugin1.getName()); verbosePluginOutput = false; logger.info("stopping all plugins"); pluginRegistry.stopAllPlugins(); verbosePluginOutput = true; logger.info(plugin1.getIdentifier() + " is " + (plugin1.isActive() ? "active" : "inactive")); logger.info(plugin4.getIdentifier() + " is " + (plugin4.isActive() ? "active" : "inactive")); logger.info("stopping all plugins again"); // // Warning about removing non-registered LoggerRepositoryEventListener // goes to console on log4j 1.2 instead of log file with log4j 1.3. // pluginRegistry.stopAllPlugins(); assertTrue(Compare.compare(PluginTestCase.class, getOutputFile(testName), getWitnessFile(testName))); } // basic test of plugin with repositories public void test2() throws Exception { // // String testName = "test2"; // Logger logger = Logger.getLogger(testName); // // setupAppender(testName); // // PluginTester plugin1 = new PluginTester1("plugin1", 1); // PluginTester plugin2 = new PluginTester1("plugin2", 2); // PluginTester retPlugin; // LoggerRepository repo1 = new Hierarchy(new RootLogger(Level.DEBUG)); // LoggerRepository repo2 = new Hierarchy(new RootLogger(Level.DEBUG)); // // PluginRegistry pr1 = repo1.getPluginRegistry(); // PluginRegistry pr2 = repo2.getPluginRegistry(); // // repositoryMap.clear(); // repositoryMap.put(repo1, "repository1"); // repositoryMap.put(repo2, "repository2"); // // logger.info("test 2.1 - starting plugins in multiple repositories"); // logger.info("starting " + plugin1.getIdentifier() + " in " + // repositoryMap.get(repo1)); // retPlugin = (PluginTester) pr1.startPlugin(plugin1); // logger.info( // "returned plugin is " + retPlugin.getIdentifier() + " in " + // repositoryMap.get(retPlugin.getLoggerRepository())); // logger.info("starting " + plugin2.getIdentifier() + " in " + // repositoryMap.get(repo2)); // retPlugin = (PluginTester) pr2.startPlugin(plugin2); // logger.info( // "returned plugin is " + retPlugin.getIdentifier() + " in " + // repositoryMap.get(retPlugin.getLoggerRepository())); // // logger.info("test 2.2 - stopping plugins in multiple repositories"); // logger.info("stopping " + plugin1.getIdentifier() + " in " + // repositoryMap.get(plugin1.getLoggerRepository())); // retPlugin = (PluginTester) pr1.stopPlugin(plugin1.getName()); // logger.info( // "returned plugin is " + retPlugin.getIdentifier() + " in " + // repositoryMap.get(retPlugin.getLoggerRepository())); // logger.info("stopping " + plugin2.getIdentifier() + " in " + // repositoryMap.get(plugin2.getLoggerRepository())); // retPlugin = (PluginTester) pr2.stopPlugin(plugin2.getName()); // logger.info( // "returned plugin is " + retPlugin.getIdentifier() + " in " + // repositoryMap.get(retPlugin.getLoggerRepository())); // // logger.info("test 2.3 - restarting plugins in different repositories"); // logger.info("starting " + plugin1.getIdentifier() + " in " + // repositoryMap.get(repo2)); // retPlugin = (PluginTester) pr2.startPlugin(plugin1); // logger.info( // "returned plugin is " + retPlugin.getIdentifier() + " in " + // repositoryMap.get(retPlugin.getLoggerRepository())); // logger.info("starting " + plugin2.getIdentifier() + " in " + // repositoryMap.get(repo1)); // retPlugin = (PluginTester) pr1.startPlugin(plugin2); // logger.info( // "returned plugin is " + retPlugin.getIdentifier() + " in " + // repositoryMap.get(retPlugin.getLoggerRepository())); // // logger.info("test 2.4 - stopping plugins using stopAll"); // logger.info("stopping all plugins in " + repositoryMap.get(repo1)); // pr1.stopAllPlugins(); // logger.info("stopping all plugins in " + repositoryMap.get(repo2)); // pr2.stopAllPlugins(); // // logger.info( // "test 2.5 - starting a plugin already active in another repository"); // logger.info("starting " + plugin1.getIdentifier() + " in " + // repositoryMap.get(repo1)); // retPlugin = (PluginTester) pr1.startPlugin(plugin1); // logger.info( // "returned plugin is " + retPlugin.getIdentifier() + " in " + // repositoryMap.get(retPlugin.getLoggerRepository())); // logger.info("starting " + plugin2.getIdentifier() + " in " + // repositoryMap.get(repo2)); // retPlugin = (PluginTester) pr2.startPlugin(plugin2); // logger.info( // "returned plugin is " + retPlugin.getIdentifier() + " in " + // repositoryMap.get(retPlugin.getLoggerRepository())); // logger.info("restarting " + plugin1.getIdentifier() + " in " + // repositoryMap.get(repo2)); // retPlugin = (PluginTester) pr2.startPlugin(plugin1); // logger.info( // "returned plugin is " + retPlugin.getIdentifier() + " in " + // repositoryMap.get(retPlugin.getLoggerRepository())); // logger.info("restarting " + plugin2.getIdentifier() + " in " + // repositoryMap.get(repo1)); // retPlugin = (PluginTester) pr1.startPlugin(plugin2); // logger.info( // "returned plugin is " + retPlugin.getIdentifier() + " in " + // repositoryMap.get(retPlugin.getLoggerRepository())); // // logger.info("test 2.6 - handle repository reset"); // logger.info("resetting " + repositoryMap.get(repo1)); // repo1.resetConfiguration(); // logger.info("resetting " + repositoryMap.get(repo2)); // repo2.resetConfiguration(); // // logger.info("test 2.7 - handle repository shutdown"); // logger.info("starting " + plugin1.getIdentifier() + " in " + // repositoryMap.get(repo1)); // retPlugin = (PluginTester) pr1.startPlugin(plugin1); // logger.info( // "returned plugin is " + retPlugin.getIdentifier() + " in " + // repositoryMap.get(retPlugin.getLoggerRepository())); // logger.info("starting " + plugin2.getIdentifier() + " in " + // repositoryMap.get(repo2)); // retPlugin = (PluginTester) pr2.startPlugin(plugin2); // logger.info( // "returned plugin is " + retPlugin.getIdentifier() + " in " + // repositoryMap.get(retPlugin.getLoggerRepository())); // logger.info("shutting down " + repositoryMap.get(repo1)); // repo1.shutdown(); // logger.info("shutting down " + repositoryMap.get(repo2)); // repo2.shutdown(); // // assertTrue(Compare.compare(getOutputFile(testName), // getWitnessFile(testName))); } public void testPluginListeners() { Plugin p = new PluginTester1("MyNewPlugin", 1); PluginListenerLatch l = new PluginListenerLatch(); pluginRegistry.stopAllPlugins(); pluginRegistry.addPluginListener(l); pluginRegistry.addPlugin(p); PluginEvent e = l.LastEvent; assertTrue("PluginListener should have been notified of start", l.StartLatch); assertTrue("PluginListener stop latch should not be activated", !l.StopLatch); assertTrue("PluginListener should be given reference to Plugin", e.getPlugin() == p); l.reset(); pluginRegistry.stopAllPlugins(); assertTrue("PluginListener should have been notified of stop", l.StopLatch); assertTrue("PluginListener should not have been notified of start", !l.StartLatch); assertTrue("PluginListener should be given reference to Plugin", l.LastEvent.getPlugin() == p); assertTrue( "PluginListener should have received a distinct event object", l.LastEvent != e); } public void testPropertyChangeListeners() { Plugin plugin = new PluginTester1("PluginTest1", 1); final PropertyChangeListenerLatch l = new PropertyChangeListenerLatch(); plugin.addPropertyChangeListener(l); /** * Test the basic properties and ensure they get latched by notification */ plugin.setName("NewName"); assertTrue("PropertyChange latch should have been detected", l.isLatched()); assertTrue("Old value unexpected: '" + l.getLastEvent().getOldValue() + "'", l.getLastEvent().getOldValue().equals("PluginTest1")); assertTrue("New value unexpected: '" + l.getLastEvent().getNewValue() + "'", l.getLastEvent().getNewValue().equals("NewName")); l.reset(); plugin.removePropertyChangeListener(l); plugin.setName("SecondNewName"); assertTrue("Should not have been notified/latched", !l.isLatched()); l.reset(); /** * Test when only listening for specific property */ plugin.addPropertyChangeListener("name", l); plugin.setName("NewName2"); assertTrue("PropertyChange latch should have been detected", l.isLatched()); assertTrue("Old value unexpected: '" + l.getLastEvent().getOldValue() + "'", l.getLastEvent().getOldValue().equals("SecondNewName")); assertTrue("New value unexpected: '" + l.getLastEvent().getNewValue() + "'", l.getLastEvent().getNewValue().equals("NewName2")); plugin.removePropertyChangeListener("name", l); l.reset(); /** * setup some assertions before continuing testing to make sure the test code isn't broken */ assertTrue("Plugin should not be active just yet", !plugin.isActive()); assertTrue("Latch should not be latched", !l.isLatched()); plugin.addPropertyChangeListener("active", l); pluginRegistry.addPlugin(plugin); /* assertTrue( "Should have been notified of activation when pluginRegistry.start(plugin)", l.isLatched()); assertTrue("Active old value should have been false", l.getLastEvent().getOldValue().equals(Boolean.FALSE)); assertTrue("Active New value should have been true", l.getLastEvent().getNewValue().equals(Boolean.TRUE)); pluginRegistry.stopAllPlugins(); l.reset(); assertTrue("Latch should have been reset", !l.isLatched()); */ /** * start afresh */ /* plugin = new PluginTester1("LoggerRepositoryProperty", 2); LoggerRepository oldValue = plugin.getLoggerRepository(); plugin.addPropertyChangeListener("loggerRepository", l); LoggerRepository rep = new Hierarchy(new RootLogger(Level.DEBUG)); plugin.setLoggerRepository(rep); assertTrue("Should be notified of LoggerRepository property change", l.isLatched()); assertTrue("LoggerRepository Old value mismatch", l.getLastEvent().getOldValue() == oldValue); assertTrue("LoggerRepository New vale mismatch", l.getLastEvent().getNewValue() == rep); */ } private static class PluginListenerLatch implements PluginListener { private boolean StartLatch; private boolean StopLatch; private PluginEvent LastEvent; /* (non-Javadoc) * @see org.apache.log4j.plugins.PluginListener#pluginStarted(org.apache.log4j.plugins.PluginEvent) */ public void pluginStarted(PluginEvent e) { StartLatch = true; LastEvent = e; } /* (non-Javadoc) * @see org.apache.log4j.plugins.PluginListener#pluginStopped(org.apache.log4j.plugins.PluginEvent) */ public void pluginStopped(PluginEvent e) { StopLatch = true; LastEvent = e; } void reset() { StartLatch = false; StopLatch = false; LastEvent = null; } } private static class PropertyChangeListenerLatch implements PropertyChangeListener { boolean latch = false; PropertyChangeEvent lastEvent = null; /* (non-Javadoc) * @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent) */ public void propertyChange(PropertyChangeEvent evt) { latch = true; lastEvent = evt; } boolean isLatched() { return latch; } void reset() { latch = false; lastEvent = null; } PropertyChangeEvent getLastEvent() { return lastEvent; } } /** Class to test the Plugin and PluginRegistry functionality. */ private static class PluginTester extends PluginSkeleton { protected Logger logger; private boolean active = false; public int id; public synchronized boolean isActive() { logger.debug(this.getIdentifier() + " is " + (active ? "active" : "inactive")); return active; } private synchronized boolean setActive(boolean _active) { boolean oldValue = active; if (active != _active) { active = _active; firePropertyChange("active", oldValue, active); return true; } else { return false; } } public String getIdentifier() { if (verbosePluginOutput) { return this.getName() + "-id" + id; } else { return "plugin in " + repositoryMap.get(this.getLoggerRepository()); } } public void activateOptions() { if (setActive(true)) { logger.debug(this.getIdentifier() + " activated"); } else { logger.debug(this.getIdentifier() + " already activated"); } } public void shutdown() { if (setActive(false)) { logger.debug(this.getIdentifier() + " shutdown"); } else { logger.debug(this.getIdentifier() + " already shutdown"); } } /* (non-Javadoc) * @see org.apache.log4j.plugins.Plugin#isEquivalent(org.apache.log4j.plugins.Plugin) */ public boolean isEquivalent(Plugin testPlugin) { boolean equiv = super.isEquivalent(testPlugin); if (equiv) { logger.debug("plugin equal"); } else if (!(testPlugin.getClass() == this.getClass())) { logger.debug( "plugin not equal, different class: " + this.getClass().getName() + " != " + testPlugin.getClass().getName()); } else if (!this.getName().equals(testPlugin.getName())) { logger.debug( "plugin not equal, different name: " + this.getName() + " != " + testPlugin.getName()); } else if (!this.getLoggerRepository().equals( testPlugin.getLoggerRepository())) { logger.debug( "plugin not equal, different repository: " + repositoryMap.get(this.getLoggerRepository()) + " != " + repositoryMap.get(testPlugin.getLoggerRepository())); } return equiv; } } /** Class to test the Plugin and PluginRegistry functionality. */ private static class PluginTester1 extends PluginTester { public PluginTester1(String _name, int _id) { logger = Logger.getLogger(this.getClass()); setName(_name); id = _id; } } /** Class to test the Plugin and PluginRegistry functionality. */ private static class PluginTester2 extends PluginTester { public PluginTester2(String _name, int _id) { logger = Logger.getLogger(this.getClass()); setName(_name); id = _id; } } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/component/util/000077500000000000000000000000001252742764200262755ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/component/util/Compare.java000066400000000000000000000075111252742764200305320ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.component.util; import java.io.*; public class Compare { static final int B1_NULL = -1; static final int B2_NULL = -2; private static final InputStream open( final Class testClass, final String fileName) throws IOException { String resourceName = fileName; if (fileName.startsWith("witness/")) { resourceName = fileName.substring(fileName.lastIndexOf('/') + 1); } InputStream is = testClass.getResourceAsStream(resourceName); if (is == null) { File file = new File(fileName); if (file.exists()) { is = new FileInputStream(file); } else { throw new FileNotFoundException("Resource " + resourceName + " not found"); } } return is; } public static boolean compare(Class testClass, final String file1, final String file2) throws IOException { BufferedReader in1 = new BufferedReader(new FileReader(file1)); BufferedReader in2 = new BufferedReader(new InputStreamReader( open(testClass, file2))); try { return compare(testClass, file1, file2, in1, in2); } finally { in1.close(); in2.close(); } } public static boolean compare( Class testClass, String file1, String file2, BufferedReader in1, BufferedReader in2) throws IOException { String s1; int lineCounter = 0; while ((s1 = in1.readLine()) != null) { lineCounter++; String s2 = in2.readLine(); if (!s1.equals(s2)) { System.out.println( "Files [" + file1 + "] and [" + file2 + "] differ on line " + lineCounter); System.out.println("One reads: [" + s1 + "]."); System.out.println("Other reads:[" + s2 + "]."); outputFile(testClass, file1); outputFile(testClass, file2); return false; } } // the second file is longer if (in2.read() != -1) { System.out.println( "File [" + file2 + "] longer than file [" + file1 + "]."); outputFile(testClass, file1); outputFile(testClass, file2); return false; } return true; } /** * * Prints file on the console. * */ private static void outputFile(Class testClass, String file) throws IOException { InputStream is = open(testClass, file); BufferedReader in1 = new BufferedReader(new InputStreamReader(is)); String s1; int lineCounter = 0; System.out.println("--------------------------------"); System.out.println("Contents of " + file + ":"); while ((s1 = in1.readLine()) != null) { lineCounter++; System.out.print(lineCounter); if (lineCounter < 10) { System.out.print(" : "); } else if (lineCounter < 100) { System.out.print(" : "); } else if (lineCounter < 1000) { System.out.print(" : "); } else { System.out.print(": "); } System.out.println(s1); } in1.close(); } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/filter/000077500000000000000000000000001252742764200246035ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/filter/AndFilterTest.java000066400000000000000000000127661252742764200301720ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.filter; import junit.framework.TestCase; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.spi.Filter; import org.apache.log4j.spi.LoggingEvent; /** * Unit tests for AndFilter. */ public class AndFilterTest extends TestCase { /** * Create new test instance. * * @param name test name. */ public AndFilterTest(final String name) { super(name); } /** * Check that AndFilter.decide() returns Filter.ACCEPT if no filters added. */ public void test1() { LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getLogger(AndFilterTest.class), System.currentTimeMillis(), Level.INFO, "Hello, World", null); Filter filter = new AndFilter(); filter.activateOptions(); assertEquals(Filter.ACCEPT, filter.decide(event)); } /** * Check that AndFilter.decide() returns Filter.ACCEPT if * only nested filter returns Filter.ACCEPT. */ public void test2() { LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getLogger(AndFilterTest.class), System.currentTimeMillis(), Level.INFO, "Hello, World", null); AndFilter filter = new AndFilter(); LevelMatchFilter filter1 = new LevelMatchFilter(); filter1.setLevelToMatch("info"); filter1.activateOptions(); filter.addFilter(filter1); filter.activateOptions(); assertEquals(Filter.ACCEPT, filter.decide(event)); } /** * Check that AndFilter.decide() returns Filter.ACCEPT if * two nested filters return Filter.ACCEPT. */ public void test3() { LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getLogger(AndFilterTest.class), System.currentTimeMillis(), Level.INFO, "Hello, World", null); AndFilter filter = new AndFilter(); LevelMatchFilter filter1 = new LevelMatchFilter(); filter1.setLevelToMatch("info"); filter1.activateOptions(); filter.addFilter(filter1); LevelMatchFilter filter2 = new LevelMatchFilter(); filter2.setLevelToMatch("info"); filter2.activateOptions(); filter.addFilter(filter2); filter.activateOptions(); assertEquals(Filter.ACCEPT, filter.decide(event)); } /** * Check that AndFilter.decide() returns Filter.DENY if * only nested filter returns Filter.ACCEPT * and acceptOnMatch is false. */ public void test4() { LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getLogger(AndFilterTest.class), System.currentTimeMillis(), Level.INFO, "Hello, World", null); AndFilter filter = new AndFilter(); LevelMatchFilter filter1 = new LevelMatchFilter(); filter1.setLevelToMatch("info"); filter1.activateOptions(); filter.addFilter(filter1); filter.setAcceptOnMatch(false); filter.activateOptions(); assertEquals(Filter.DENY, filter.decide(event)); } /** * Check that AndFilter.decide() returns Filter.NEUTRAL if * nested filters return Filter.ACCEPT and Filter.DENY. */ public void test5() { LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getLogger(AndFilterTest.class), System.currentTimeMillis(), Level.INFO, "Hello, World", null); AndFilter filter = new AndFilter(); LevelMatchFilter filter1 = new LevelMatchFilter(); filter1.setLevelToMatch("info"); filter1.activateOptions(); filter.addFilter(filter1); Filter filter2 = new DenyAllFilter(); filter2.activateOptions(); filter.addFilter(filter2); filter.activateOptions(); assertEquals(Filter.NEUTRAL, filter.decide(event)); } /** * Check that AndFilter.decide() returns Filter.NEUTRAL if * nested filters return Filter.ACCEPT and Filter.NEUTRAL. */ public void test6() { LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getLogger(AndFilterTest.class), System.currentTimeMillis(), Level.INFO, "Hello, World", null); AndFilter filter = new AndFilter(); LevelMatchFilter filter1 = new LevelMatchFilter(); filter1.setLevelToMatch("info"); filter1.activateOptions(); filter.addFilter(filter1); Filter filter2 = new StringMatchFilter(); filter2.activateOptions(); filter.addFilter(filter2); filter.activateOptions(); assertEquals(Filter.NEUTRAL, filter.decide(event)); } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/filter/DenyAllFilterTest.java000066400000000000000000000033021252742764200310020ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.filter; import junit.framework.TestCase; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.spi.Filter; import org.apache.log4j.spi.LoggingEvent; /** * Unit tests for DenyAllFilter. */ public class DenyAllFilterTest extends TestCase { /** * Create new test instance. * * @param name test name. */ public DenyAllFilterTest(final String name) { super(name); } /** * Check that DenyAllFilter.decide() returns Filter.DENY. */ public void test1() { LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getLogger(DenyAllFilterTest.class), System.currentTimeMillis(), Level.INFO, "Hello, World", null); Filter filter = new DenyAllFilter(); filter.activateOptions(); assertEquals(Filter.DENY, filter.decide(event)); } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/filter/LevelMatchFilterTest.java000066400000000000000000000100261252742764200314770ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.filter; import junit.framework.TestCase; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.spi.Filter; import org.apache.log4j.spi.LoggingEvent; /** * Unit tests for LevelMatchFilter. */ public class LevelMatchFilterTest extends TestCase { /** * Create new test instance. * * @param name test name. */ public LevelMatchFilterTest(final String name) { super(name); } /** * Check that LevelMatchFilter.decide() returns Filter.ACCEPT when level matches. */ public void test1() { LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getLogger(LevelMatchFilterTest.class), System.currentTimeMillis(), Level.INFO, "Hello, World", null); LevelMatchFilter filter = new LevelMatchFilter(); filter.setLevelToMatch("info"); filter.activateOptions(); assertEquals(Filter.ACCEPT, filter.decide(event)); } /** * Check that LevelMatchFilter.decide() returns Filter.DENY * when level matches and acceptOnMatch = false. */ public void test2() { LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getLogger(LevelMatchFilterTest.class), System.currentTimeMillis(), Level.INFO, "Hello, World", null); LevelMatchFilter filter = new LevelMatchFilter(); filter.setLevelToMatch("info"); filter.setAcceptOnMatch(false); filter.activateOptions(); assertEquals(Filter.DENY, filter.decide(event)); } /** * Check that LevelMatchFilter.decide() returns Filter.NEUTRAL * when levelToMatch is unspecified. */ public void test3() { LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getLogger(LevelMatchFilterTest.class), System.currentTimeMillis(), Level.INFO, "Hello, World", null); LevelMatchFilter filter = new LevelMatchFilter(); filter.activateOptions(); assertEquals(Filter.NEUTRAL, filter.decide(event)); } /** * Check that LevelMatchFilter.decide() returns Filter.NEUTRAL * when event level is higher than level to match. */ public void test4() { LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getLogger(LevelMatchFilterTest.class), System.currentTimeMillis(), Level.INFO, "Hello, World", null); LevelMatchFilter filter = new LevelMatchFilter(); filter.setLevelToMatch("debug"); filter.activateOptions(); assertEquals(Filter.NEUTRAL, filter.decide(event)); } /** * Check that LevelMatchFilter.decide() returns Filter.NEUTRAL * when event level is lower than level to match. */ public void test5() { LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getLogger(LevelMatchFilterTest.class), System.currentTimeMillis(), Level.INFO, "Hello, World", null); LevelMatchFilter filter = new LevelMatchFilter(); filter.setLevelToMatch("warn"); filter.activateOptions(); assertEquals(Filter.NEUTRAL, filter.decide(event)); } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/filter/LevelRangeFilterTest.java000066400000000000000000000113241252742764200315010ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.filter; import junit.framework.TestCase; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.spi.Filter; import org.apache.log4j.spi.LoggingEvent; /** * Unit tests for LevelRangeFilter. */ public class LevelRangeFilterTest extends TestCase { /** * Create new test instance. * * @param name test name. */ public LevelRangeFilterTest(final String name) { super(name); } /** * Check that LevelRangeFilter.decide() returns Filter.DENY * when event level is below min level. */ public void test1() { LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getLogger(LevelRangeFilterTest.class), System.currentTimeMillis(), Level.INFO, "Hello, World", null); LevelRangeFilter filter = new LevelRangeFilter(); filter.setLevelMin(Level.WARN); filter.activateOptions(); assertEquals(Filter.DENY, filter.decide(event)); } /** * Check that LevelRangeFilter.decide() returns Filter.DENY * when event level is above max level. */ public void test2() { LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getLogger(LevelRangeFilterTest.class), System.currentTimeMillis(), Level.INFO, "Hello, World", null); LevelRangeFilter filter = new LevelRangeFilter(); filter.setLevelMax(Level.DEBUG); filter.activateOptions(); assertEquals(Filter.DENY, filter.decide(event)); } /** * Check that LevelRangeFilter.decide() returns Filter.ACCEPT * when event level is above min level. */ public void test3() { LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getLogger(LevelRangeFilterTest.class), System.currentTimeMillis(), Level.INFO, "Hello, World", null); LevelRangeFilter filter = new LevelRangeFilter(); filter.setLevelMin(Level.DEBUG); filter.setAcceptOnMatch(true); filter.activateOptions(); assertEquals(Filter.ACCEPT, filter.decide(event)); } /** * Check that LevelRangeFilter.decide() returns Filter.ACCEPT * when event level is below max level. */ public void test4() { LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getLogger(LevelRangeFilterTest.class), System.currentTimeMillis(), Level.INFO, "Hello, World", null); LevelRangeFilter filter = new LevelRangeFilter(); filter.setLevelMax(Level.ERROR); filter.setAcceptOnMatch(true); filter.activateOptions(); assertEquals(Filter.ACCEPT, filter.decide(event)); } /** * Check that LevelRangeFilter.decide() returns Filter.NEUTRAL * when event level is above min level and accept on match is false. */ public void test5() { LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getLogger(LevelRangeFilterTest.class), System.currentTimeMillis(), Level.INFO, "Hello, World", null); LevelRangeFilter filter = new LevelRangeFilter(); filter.setLevelMin(Level.DEBUG); filter.activateOptions(); assertEquals(Filter.NEUTRAL, filter.decide(event)); } /** * Check that LevelRangeFilter.decide() returns Filter.NEUTRAL * when event level is below max level and accept on match is false. */ public void test6() { LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getLogger(LevelRangeFilterTest.class), System.currentTimeMillis(), Level.INFO, "Hello, World", null); LevelRangeFilter filter = new LevelRangeFilter(); filter.setLevelMax(Level.ERROR); filter.activateOptions(); assertEquals(Filter.NEUTRAL, filter.decide(event)); } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/filter/LoggerMatchFilterTest.java000066400000000000000000000067071252742764200316620ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.filter; import junit.framework.TestCase; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.spi.Filter; import org.apache.log4j.spi.LoggingEvent; /** * Unit tests for LoggerMatchFilter. */ public class LoggerMatchFilterTest extends TestCase { /** * Create new test instance. * * @param name test name. */ public LoggerMatchFilterTest(final String name) { super(name); } /** * Check that LoggerMatchFilter.decide() with unspecified level * returns Filter.ACCEPT for root logger. */ public void test1() { LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), System.currentTimeMillis(), Level.INFO, "Hello, World", null); Filter filter = new LoggerMatchFilter(); filter.activateOptions(); assertEquals(Filter.ACCEPT, filter.decide(event)); } /** * Check that LoggerMatchFilter.decide() with unspecified level * returns Filter.DENY for root logger when accept on match is false. */ public void test2() { LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), System.currentTimeMillis(), Level.INFO, "Hello, World", null); LoggerMatchFilter filter = new LoggerMatchFilter(); filter.setAcceptOnMatch(false); filter.activateOptions(); assertEquals(Filter.DENY, filter.decide(event)); } /** * Check that LoggerMatchFilter.decide() with unspecified level * returns Filter.NEUTRAL for non-root logger. */ public void test3() { LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getLogger("org.apache.log4j.filter.LoggerMatchFilterTest"), System.currentTimeMillis(), Level.INFO, "Hello, World", null); Filter filter = new LoggerMatchFilter(); filter.activateOptions(); assertEquals(Filter.NEUTRAL, filter.decide(event)); } /** * Check that LoggerMatchFilter.decide() * returns Filter.ACCEPT for matching logger. */ public void test4() { LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getLogger("org.apache.log4j.filter.LoggerMatchFilterTest"), System.currentTimeMillis(), Level.INFO, "Hello, World", null); LoggerMatchFilter filter = new LoggerMatchFilter(); filter.setLoggerToMatch("org.apache.log4j.filter.LoggerMatchFilterTest"); filter.activateOptions(); assertEquals(Filter.ACCEPT, filter.decide(event)); } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/filter/SimpleFilterTest.java000066400000000000000000000167571252742764200307250ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.filter; import junit.framework.TestCase; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.util.Compare; import org.apache.log4j.util.ControlFilter; import org.apache.log4j.util.Filter; import org.apache.log4j.util.JunitTestRunnerFilter; import org.apache.log4j.util.LineNumberFilter; import org.apache.log4j.util.SunReflectFilter; import org.apache.log4j.util.Transformer; import org.apache.log4j.extras.DOMConfigurator; import org.apache.log4j.xml.Log4jEntityResolver; import org.w3c.dom.Document; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.FileNotFoundException; import java.io.InputStream; /** * Various tests verifying that filters work properly and that * JoranConfigurator can effectively parse config files containing them. * * @author Ceki Gulcu * */ public class SimpleFilterTest extends TestCase { Logger root; Logger logger; public final static String FILTERED = "target/filtered"; public final static String TEMP = "target/temp"; static String TEST1_PAT = "(DEBUG|INFO|WARN|ERROR|FATAL) - Message \\d"; static String TEST8_PAT = "WARN org.apache.log4j.filter.SimpleFilterTest - Message \\d"; static String EXCEPTION1 = "java.lang.Exception: Just testing"; static String EXCEPTION2 = "\\s*at .*\\(.*:\\d{1,4}\\)"; static String EXCEPTION3 = "\\s*at .*\\(Native Method\\)"; public SimpleFilterTest(String name) { super(name); } public void setUp() { root = Logger.getRootLogger(); logger = Logger.getLogger(SimpleFilterTest.class); } public void tearDown() { root.getLoggerRepository().resetConfiguration(); } private final void configure(final String resourceName) throws Exception { InputStream is = getClass().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException( "Could not find resource " + resourceName); } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setEntityResolver(new Log4jEntityResolver()); Document doc = builder.parse(is); DOMConfigurator.configure(doc.getDocumentElement()); } public void test1() throws Exception { configure("simpleFilter1.xml"); common(); ControlFilter cf = new ControlFilter(new String[]{TEST1_PAT, EXCEPTION1, EXCEPTION2, EXCEPTION3}); Transformer.transform(TEMP, FILTERED, new Filter[] {cf, new LineNumberFilter(), new SunReflectFilter(), new JunitTestRunnerFilter()}); assertTrue(Compare.compare(SimpleFilterTest.class, FILTERED, "witness/filter/simpleFilter.1")); } public void test6() throws Exception { configure("simpleFilter6.xml"); common(); ControlFilter cf = new ControlFilter(new String[]{TEST1_PAT, EXCEPTION1, EXCEPTION2, EXCEPTION3}); Transformer.transform(TEMP, FILTERED, new Filter[] {cf, new LineNumberFilter(), new SunReflectFilter(), new JunitTestRunnerFilter()}); assertTrue(Compare.compare(SimpleFilterTest.class, FILTERED, "witness/filter/simpleFilter.6")); } public void test7() throws Exception { configure("simpleFilter7.xml"); common(); ControlFilter cf = new ControlFilter(new String[]{TEST1_PAT, EXCEPTION1, EXCEPTION2, EXCEPTION3}); Transformer.transform(TEMP, FILTERED, new Filter[] {cf, new LineNumberFilter(), new SunReflectFilter(), new JunitTestRunnerFilter()}); assertTrue(Compare.compare(SimpleFilterTest.class, FILTERED, "witness/filter/simpleFilter.7")); } public void test8() throws Exception { configure("simpleFilter8.xml"); common(); ControlFilter cf = new ControlFilter(new String[]{TEST8_PAT, EXCEPTION1, EXCEPTION2, EXCEPTION3}); Transformer.transform(TEMP, FILTERED, new Filter[] {cf, new LineNumberFilter(), new SunReflectFilter(), new JunitTestRunnerFilter()}); assertTrue(Compare.compare(SimpleFilterTest.class, FILTERED, "witness/filter/simpleFilter.8")); } public void test9() throws Exception { configure("simpleFilter9.xml"); common(); ControlFilter cf = new ControlFilter(new String[]{TEST1_PAT, EXCEPTION1, EXCEPTION2, EXCEPTION3}); Transformer.transform(TEMP, FILTERED, new Filter[] {cf, new LineNumberFilter(), new SunReflectFilter(), new JunitTestRunnerFilter()}); assertTrue(Compare.compare(SimpleFilterTest.class, FILTERED, "witness/filter/simpleFilter.1")); } public void test10() throws Exception { configure("simpleFilter10.xml"); common(); ControlFilter cf = new ControlFilter(new String[]{TEST1_PAT, EXCEPTION1, EXCEPTION2, EXCEPTION3}); Transformer.transform(TEMP, FILTERED, new Filter[] {cf, new LineNumberFilter(), new SunReflectFilter(), new JunitTestRunnerFilter()}); assertTrue(Compare.compare(SimpleFilterTest.class, FILTERED, "witness/filter/simpleFilter.6")); } public void test11() throws Exception { configure("simpleFilter11.xml"); common(); ControlFilter cf = new ControlFilter(new String[]{TEST1_PAT, EXCEPTION1, EXCEPTION2, EXCEPTION3}); Transformer.transform(TEMP, FILTERED, new Filter[] {cf, new LineNumberFilter(), new SunReflectFilter(), new JunitTestRunnerFilter()}); assertTrue(Compare.compare(SimpleFilterTest.class, FILTERED, "witness/filter/simpleFilter.11")); } public void test12() throws Exception { configure("simpleFilter12.xml"); common(); ControlFilter cf = new ControlFilter(new String[]{TEST8_PAT, EXCEPTION1, EXCEPTION2, EXCEPTION3}); Transformer.transform(TEMP, FILTERED, new Filter[] {cf, new LineNumberFilter(), new SunReflectFilter(), new JunitTestRunnerFilter()}); assertTrue(Compare.compare(SimpleFilterTest.class, FILTERED, "witness/filter/simpleFilter.8")); } void common() { int i = -1; logger.debug("Message " + ++i); root.debug("Message " + i); logger.info ("Message " + ++i); root.info("Message " + i); logger.warn ("Message " + ++i); root.warn("Message " + i); logger.error("Message " + ++i); root.error("Message " + i); logger.log(Level.FATAL, "Message " + ++i); root.log(Level.FATAL, "Message " + i); Exception e = new Exception("Just testing"); logger.debug("Message " + ++i, e); root.debug("Message " + i, e); logger.error("Message " + ++i, e); root.error("Message " + i, e); } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/filter/StringMatchFilterTest.java000066400000000000000000000102031252742764200316730ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.filter; import junit.framework.TestCase; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.spi.Filter; import org.apache.log4j.spi.LoggingEvent; /** * Unit tests for StringMatchFilter. */ public class StringMatchFilterTest extends TestCase { /** * Create new test instance. * * @param name test name. */ public StringMatchFilterTest(final String name) { super(name); } /** * Check that StringMatchFilter.decide() returns Filter.NEUTRAL * when string to match is unspecified. */ public void test1() { LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getLogger(StringMatchFilterTest.class), System.currentTimeMillis(), Level.INFO, "Hello, World", null); Filter filter = new StringMatchFilter(); filter.activateOptions(); assertEquals(Filter.NEUTRAL, filter.decide(event)); } /** * Check that StringMatchFilter.decide() returns Filter.NEUTRAL * when string to match does not appear in message. */ public void test2() { LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getLogger(StringMatchFilterTest.class), System.currentTimeMillis(), Level.INFO, "Hello, World", null); StringMatchFilter filter = new StringMatchFilter(); filter.setStringToMatch("Monde"); filter.activateOptions(); assertEquals(Filter.NEUTRAL, filter.decide(event)); } /** * Check that StringMatchFilter.decide() returns Filter.ACCEPT * when string to match does appear in message. */ public void test3() { LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getLogger(StringMatchFilterTest.class), System.currentTimeMillis(), Level.INFO, "Hello, World", null); StringMatchFilter filter = new StringMatchFilter(); filter.setStringToMatch("World"); filter.activateOptions(); assertEquals(Filter.ACCEPT, filter.decide(event)); } /** * Check that StringMatchFilter.decide() returns Filter.DENY * when string to match does appear in message and * accept on match is false. */ public void test4() { LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getLogger(StringMatchFilterTest.class), System.currentTimeMillis(), Level.INFO, "Hello, World", null); StringMatchFilter filter = new StringMatchFilter(); filter.setStringToMatch("World"); filter.setAcceptOnMatch(false); filter.activateOptions(); assertEquals(Filter.DENY, filter.decide(event)); } /** * Check that StringMatchFilter.decide() returns Filter.NEUTRAL * when string to match does appear in message but differs in case. */ public void test5() { LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getLogger(StringMatchFilterTest.class), System.currentTimeMillis(), Level.INFO, "Hello, World", null); StringMatchFilter filter = new StringMatchFilter(); filter.setStringToMatch("world"); filter.activateOptions(); assertEquals(Filter.NEUTRAL, filter.decide(event)); } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/filter/TimeFilterTest.java000066400000000000000000000205041252742764200303530ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.filter; import junit.framework.TestCase; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.extras.DOMConfigurator; import org.apache.log4j.spi.Filter; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.util.Compare; import org.apache.log4j.xml.Log4jEntityResolver; import org.w3c.dom.Document; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.Calendar; import java.util.TimeZone; /** * Tests for TimeFilter. * */ public class TimeFilterTest extends TestCase { /** * Construct new instance. * @param testName test name. */ public TimeFilterTest(final String testName) { super(testName); } /** * Configure log4j from resource. * @param resourceName resource name. * @throws Exception if IO or other error. */ private final void configure(final String resourceName) throws Exception { Logger.getRootLogger().getLoggerRepository().resetConfiguration(); InputStream is = getClass().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException( "Could not find resource " + resourceName); } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setEntityResolver(new Log4jEntityResolver()); Document doc = builder.parse(is); DOMConfigurator.configure(doc.getDocumentElement()); } /** * Test 2 AM events against a 2 AM - 3 AM filter. * @param tz time zone, may be null. * @param dayIncrement days in advance of current date. */ private void common2AM(String tz, int dayIncrement) { TimeFilter timeFilter = new TimeFilter(); timeFilter.setStart("02:00:00"); timeFilter.setEnd("03:00:00"); if (tz != null) { timeFilter.setTimeZone(tz); } timeFilter.activateOptions(); Calendar cal; if (tz == null) { cal = Calendar.getInstance(); } else { cal = Calendar.getInstance(TimeZone.getTimeZone(tz)); } cal.set(Calendar.HOUR_OF_DAY, 2); if (dayIncrement != 0) { cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR) + dayIncrement); } LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getLogger(TimeFilterTest.class), cal.getTimeInMillis(), Level.INFO, "Hello, world.", null); assertEquals(Filter.ACCEPT, timeFilter.decide(event)); timeFilter.setAcceptOnMatch(false); assertEquals(Filter.DENY, timeFilter.decide(event)); } /** * Test 3 AM events against a 2 AM - 3 AM filter. * @param tz time zone, may be null. * @param dayIncrement days in advance of current date. */ private void common3AM(String tz, int dayIncrement) { TimeFilter timeFilter = new TimeFilter(); timeFilter.setStart("02:00:00"); timeFilter.setEnd("03:00:00"); if (tz != null) { timeFilter.setTimeZone(tz); } timeFilter.activateOptions(); Calendar cal; if (tz == null) { cal = Calendar.getInstance(); } else { cal = Calendar.getInstance(TimeZone.getTimeZone(tz)); } cal.set(Calendar.HOUR_OF_DAY, 3); if (dayIncrement != 0) { cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR) + dayIncrement); } LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getLogger(TimeFilterTest.class), cal.getTimeInMillis(), Level.INFO, "Hello, world.", null); assertEquals(Filter.NEUTRAL, timeFilter.decide(event)); timeFilter.setAcceptOnMatch(false); assertEquals(Filter.NEUTRAL, timeFilter.decide(event)); timeFilter.setAcceptOnMatch(true); } /** * Test 2 AM local today event against 2 AM - 3 AM local time filter. */ public void test2AMLocal() { common2AM(null, 0); } /** * Test 2 AM local yesterday event against 2 AM - 3 AM local time filter. */ public void test2AMLocalYesterday() { common2AM(null, -1); } /** * Test 2 AM local tomorrow event against 2 AM - 3 AM local time filter. */ public void test2AMLocalTomorrow() { common2AM(null, 1); } /** * Test 2 AM local last week event against 2 AM - 3 AM local time filter. */ public void test2AMLocalLastWeek() { common2AM(null, -7); } /** * Test 2 AM local next week event against 2 AM - 3 AM local time filter. */ public void test2AMLocalNextWeek() { common2AM(null, 7); } /** * Test 3 AM local today event against 2 AM - 3 AM local time filter. */ public void test3AMLocal() { common3AM(null, 0); } /** * Test 3 AM local yesterday event against 2 AM - 3 AM local time filter. */ public void test3AMLocalYesterday() { common3AM(null, -1); } /** * Test 3 AM local tomorrow event against 2 AM - 3 AM local time filter. */ public void test3AMLocalTomorrow() { common3AM(null, 1); } /** * Test 3 AM local last week event against 2 AM - 3 AM local time filter. */ public void test3AMLocalLastWeek() { common3AM(null, -7); } /** * Test 3 AM local next week event against 2 AM - 3 AM local time filter. */ public void test3AMLocalNextWeek() { common3AM(null, 7); } /** * Test 2 AM UTC today event against 2 AM - 3 AM GMT filter. */ public void test2AMGMT() { common2AM("GMT", 0); } /** * Test 3 AM UTC today event against 2 AM - 3 AM GMT filter. */ public void test3AMGMT() { common3AM("GMT", 0); } /** * Log events every 15 minutes from midnight to midnight in * using specified calendar. * @param cal calendar. */ private void common(Calendar cal) { Logger logger = Logger.getLogger(TimeFilterTest.class); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); for (int hour = 0; hour < 24; hour++) { for (int minute = 0; minute < 60; minute += 15) { cal.set(Calendar.HOUR_OF_DAY, hour); cal.set(Calendar.MINUTE, minute); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", logger, cal.getTimeInMillis(), Level.INFO, "Hello, world.", null); logger.callAppenders(event); } } } /** * Test 2 AM-3AM local time accept on match filter. * @throws Exception if IO exception. */ public void testConfig1() throws Exception { configure("timeFilter1.xml"); common(Calendar.getInstance()); assertTrue(Compare.compare(TimeFilterTest.class, "target/timeFilter.1", "timeFilter1.log")); } /** * Test 2 AM-3AM UTC reject on match filter. * @throws Exception if IO exception. */ public void testConfig2() throws Exception { configure("timeFilter2.xml"); common(Calendar.getInstance(TimeZone.getTimeZone("GMT"))); assertTrue(Compare.compare(TimeFilterTest.class, "target/timeFilter.2", "timeFilter2.log")); } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/pattern/000077500000000000000000000000001252742764200247735ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/pattern/FormattingInfoTest.java000066400000000000000000000060101252742764200314210ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.pattern; import junit.framework.TestCase; /** * Tests for ExtrasFormattingInfo. * * @author Curt Arnold * */ public class FormattingInfoTest extends TestCase { /** * Create a new instance. * * @param name test name */ public FormattingInfoTest(final String name) { super(name); } /** * Check that getDefault does not return null. * */ public void testGetDefault() { ExtrasFormattingInfo field = ExtrasFormattingInfo.getDefault(); assertNotNull(field); assertEquals(0, field.getMinLength()); assertEquals(Integer.MAX_VALUE, field.getMaxLength()); assertEquals(false, field.isLeftAligned()); } /** * Check constructor * */ public void testConstructor() { ExtrasFormattingInfo field = new ExtrasFormattingInfo(true, false, 3, 6); assertNotNull(field); assertEquals(3, field.getMinLength()); assertEquals(6, field.getMaxLength()); assertEquals(true, field.isLeftAligned()); } /** * Field exceeds maximum width */ public void testTruncate() { StringBuffer buf = new StringBuffer("foobar"); ExtrasFormattingInfo field = new ExtrasFormattingInfo(true, false, 0, 3); field.format(2, buf); assertEquals("fobar", buf.toString()); } /** * Field exceeds maximum width, truncate right. */ public void testRightTruncate() { StringBuffer buf = new StringBuffer("foobar"); ExtrasFormattingInfo field = new ExtrasFormattingInfo(true, true, 0, 3); field.format(2, buf); assertEquals("fooba", buf.toString()); } /** * Add padding to left since field is not minimum width. */ public void testPadLeft() { StringBuffer buf = new StringBuffer("foobar"); ExtrasFormattingInfo field = new ExtrasFormattingInfo(false, false, 5, 10); field.format(2, buf); assertEquals("fo obar", buf.toString()); } /** * Add padding to right since field is not minimum width. */ public void testPadRight() { StringBuffer buf = new StringBuffer("foobar"); ExtrasFormattingInfo field = new ExtrasFormattingInfo(true, false, 5, 10); field.format(2, buf); assertEquals("foobar ", buf.toString()); } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/pattern/PatternParserTest.java000066400000000000000000000124341252742764200312740ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.pattern; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TimeZone; import junit.framework.TestCase; import org.apache.log4j.Layout; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.spi.LoggingEvent; /** Test case for ExtrasPatternParser.java. Tests the various conversion patterns supported by ExtrasPatternParser. This test class tests ExtrasPatternParser via the EnhancedPatternLayout class which uses it. */ public class PatternParserTest extends TestCase { private final Logger logger = Logger.getLogger("org.foobar"); private final LoggingEvent event; public PatternParserTest(String name) { super(name); event = new LoggingEvent("org.apache.log4j.Logger", logger, Level.INFO, "msg 1", null); } private static String convert( String pattern, Map registry, LoggingEvent event) { List converters = new ArrayList(); List fields = new ArrayList(); ExtrasPatternParser.parse(pattern, converters, fields, registry, ExtrasPatternParser.getPatternLayoutRules()); assertEquals(converters.size(), fields.size()); StringBuffer buf = new StringBuffer(); Iterator converterIter = converters.iterator(); Iterator fieldIter = fields.iterator(); while(converterIter.hasNext()) { int fieldStart = buf.length(); ((PatternConverter) converterIter.next()).format(event, buf); ((ExtrasFormattingInfo) fieldIter.next()).format(fieldStart, buf); } return buf.toString(); } public void testBogusWord1() throws Exception { String result = convert("%, foobar", null, event); assertEquals("%, foobar", result); } public void testBogusWord2() throws Exception { String result = convert("xyz %, foobar", null, event); assertEquals("xyz %, foobar", result); } public void testBasic1() throws Exception { String result = convert("hello %-5level - %m%n", null, event); assertEquals("hello INFO - msg 1" + Layout.LINE_SEP, result); } public void testBasic2() throws Exception { String result = convert("%relative %-5level [%thread] %logger - %m%n", null, event); long expectedRelativeTime = event.timeStamp - LoggingEvent.getStartTime(); assertEquals(expectedRelativeTime + " INFO [main] "+logger.getName()+" - msg 1" + Layout.LINE_SEP, result); } public void testMultiOption() throws Exception { String result = convert("%d{HH:mm:ss}{GMT} %d{HH:mm:ss} %c - %m", null, event); SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); String localTime = dateFormat.format(new Date(event.timeStamp)); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); String utcTime = dateFormat.format(new Date(event.timeStamp)); StringBuffer buf = new StringBuffer(utcTime); buf.append(' '); buf.append(localTime); buf.append(" org.foobar - msg 1"); assertEquals(buf.toString(), result); } public void testBogus() throws Exception { String result = convert("%bogus", null, event); assertEquals("%bogus", result); } public void testMore() throws Exception { String result = convert("%more", null, event); assertEquals("msg 1ore", result); } /** * Options with missing close braces will be treated as a literal. * Endless looped with earlier code. * */ public void testMalformedOption() { String result = convert("foo%m{yyyy.MM.dd", null, event); assertEquals("foomsg 1{yyyy.MM.dd", result); } private void assertFactories(Map rules) throws Exception { assertTrue(rules.size() > 0); Iterator iter = rules.values().iterator(); Class[] factorySig = new Class[] { Class.forName("[Ljava.lang.String;") }; Object[] factoryArg = new Object[] { null }; while(iter.hasNext()) { Class ruleClass = (Class) iter.next(); Method factory = ruleClass.getMethod("newInstance", factorySig); Object converter = factory.invoke(null, factoryArg); assertTrue(converter != null); } } public void testPatternLayoutFactories() throws Exception { assertFactories(ExtrasPatternParser.getPatternLayoutRules()); } public void testFileNamePatternFactories() throws Exception { assertFactories(ExtrasPatternParser.getFileNamePatternRules()); } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/receivers/000077500000000000000000000000001252742764200253055ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/receivers/db/000077500000000000000000000000001252742764200256725ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/receivers/db/FullCycleDBTest.java000066400000000000000000000257211252742764200314740ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.db; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.log4j.Hierarchy; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.LoggerRepositoryExImpl; import org.apache.log4j.MDC; import org.apache.log4j.component.helpers.Constants; import org.apache.log4j.VectorAppender; import org.apache.log4j.spi.LocationInfo; import org.apache.log4j.spi.LoggerRepository; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.RootLogger; import org.apache.log4j.xml.DOMConfigurator; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Vector; /** * This test case writes a few events into a databases and reads them * back comparing the event written and read back. * *

    It relies heavily on the proper configuration of its environment * in joran config files as well system properties. *

    * *

    See also the Ant build file in the tests/ directory.

    * * @author Ceki Gülcü */ public class FullCycleDBTest extends TestCase { Vector witnessEvents; Hierarchy lrWrite; LoggerRepository lrRead; String appendConfigFile = null; String readConfigFile = null; /* * @see TestCase#setUp() */ protected void setUp() throws Exception { super.setUp(); appendConfigFile = "append-with-drivermanager1.xml"; readConfigFile = "read-with-drivermanager1.xml"; witnessEvents = new Vector(); lrWrite = new Hierarchy(new RootLogger(Level.DEBUG)); lrRead = new LoggerRepositoryExImpl(new Hierarchy(new RootLogger(Level.DEBUG))); // // attempt to define tables in in-memory database // will throw exception if already defined. // Class.forName("org.hsqldb.jdbcDriver"); Connection connection = DriverManager.getConnection("jdbc:hsqldb:mem:testdb"); try { Statement s = connection.createStatement(); s.executeUpdate("CREATE TABLE logging_event " + "( sequence_number BIGINT NOT NULL, " + " timestamp BIGINT NOT NULL, " + " rendered_message LONGVARCHAR NOT NULL, " + " logger_name VARCHAR NOT NULL, " + " level_string VARCHAR NOT NULL, " + " ndc LONGVARCHAR, " + " thread_name VARCHAR, " + " reference_flag SMALLINT, " + " caller_filename VARCHAR, " + " caller_class VARCHAR, " + " caller_method VARCHAR, " + " caller_line CHAR(4), " + " event_id INT NOT NULL IDENTITY)"); s.executeUpdate("CREATE TABLE logging_event_property " + "( event_id INT NOT NULL, " + " mapped_key VARCHAR(254) NOT NULL, " + " mapped_value LONGVARCHAR, " + " PRIMARY KEY(event_id, mapped_key), " + " FOREIGN KEY (event_id) REFERENCES logging_event(event_id))"); s.executeUpdate("CREATE TABLE logging_event_exception" + " ( event_id INT NOT NULL, " + " i SMALLINT NOT NULL," + " trace_line VARCHAR NOT NULL," + " PRIMARY KEY(event_id, i)," + " FOREIGN KEY (event_id) REFERENCES logging_event(event_id))"); } catch(SQLException ex) { String s = ex.toString(); } finally { connection.close(); } } /* * @see TestCase#tearDown() */ protected void tearDown() throws Exception { super.tearDown(); lrRead.shutdown(); witnessEvents = null; } /** * Constructor for DBReeceiverTest. * @param arg0 */ public FullCycleDBTest(String arg0) { super(arg0); } /** * This test starts by writing a single event to a DB using DBAppender * and then reads it back using DBReceiver. * * DB related information is specified within the configuration files. * @throws Exception */ public void testSingleOutput() throws Exception { DOMConfigurator jc1 = new DOMConfigurator(); InputStream is = FullCycleDBTest.class.getResourceAsStream(appendConfigFile); jc1.doConfigure(is, lrWrite); is.close(); long startTime = System.currentTimeMillis(); System.out.println("***startTime is "+startTime); // Write out just one log message Logger out = lrWrite.getLogger("testSingleOutput.out"); out.debug("some message"+startTime); VectorAppender witnessAppender = (VectorAppender) lrWrite.getRootLogger().getAppender("VECTOR"); witnessEvents = witnessAppender.getVector(); assertEquals(1, witnessEvents.size()); // We have to close all appenders before starting to read lrWrite.shutdown(); // now read it back readBack(readConfigFile, startTime); } /** * This test starts by writing a single event to a DB using DBAppender * and then reads it back using DBReceiver. * * The written event includes MDC and repository properties as well as * exception info. * * DB related information is specified within the configuration files. * @throws Exception */ public void testAllFields() throws IOException { DOMConfigurator jc1 = new DOMConfigurator(); InputStream is = FullCycleDBTest.class.getResourceAsStream(appendConfigFile); jc1.doConfigure(is, lrWrite); is.close(); long startTime = System.currentTimeMillis(); // Write out just one log message MDC.put("key1", "value1-" + startTime); MDC.put("key2", "value2-"+startTime); Map mdcMap = MDC.getContext(); // LogLog.info("**********"+mdcMap.size()); // Write out just one log message Logger out = lrWrite.getLogger("out"+startTime); out.debug("some message"+startTime); MDC.put("key3", "value2-" + startTime); out.error("some error message"+startTime, new Exception("testing")); // we clear the MDC to avoid interference with the events read back from // the db MDC.remove("key1"); MDC.remove("key2"); MDC.remove("key3"); VectorAppender witnessAppender = (VectorAppender) lrWrite.getRootLogger().getAppender("VECTOR"); witnessEvents = witnessAppender.getVector(); assertEquals(2, witnessEvents.size()); // We have to close all appenders just before starting to read lrWrite.shutdown(); readBack(readConfigFile, startTime); } void readBack(String configfile, long startTime) throws IOException { DOMConfigurator jc2 = new DOMConfigurator(); InputStream is = FullCycleDBTest.class.getResourceAsStream(configfile); jc2.doConfigure(is, lrRead); is.close(); // wait a little to allow events to be read try { Thread.sleep(3100); } catch(Exception e) {} VectorAppender va = (VectorAppender) lrRead.getRootLogger().getAppender("VECTOR"); Vector returnedEvents = getRelevantEventsFromVA(va, startTime); compareEvents(witnessEvents, returnedEvents); } void compareEvents(Vector l, Vector r) { assertNotNull("left vector of events should not be null"); assertEquals(l.size(), r.size()); for(int i = 0; i < r.size(); i++) { LoggingEvent le = (LoggingEvent) l.get(i); LoggingEvent re = (LoggingEvent) r.get(i); assertEquals(le.getMessage(), re.getMessage()); assertEquals(le.getLoggerName(), re.getLoggerName()); assertEquals(le.getLevel(), re.getLevel()); assertEquals(le.getThreadName(), re.getThreadName()); if(re.getTimeStamp() < le.getTimeStamp()) { fail("Returned event cannot preceed witness timestamp"); } Map sourceMap = re.getProperties(); Map remap; if (sourceMap == null) { remap = new HashMap(); } else { remap = new HashMap(sourceMap); if (remap.containsKey(Constants.LOG4J_ID_KEY)) { remap.remove(Constants.LOG4J_ID_KEY); } } if(le.getProperties() == null || le.getProperties().size() == 0) { if(remap.size() != 0) { System.out.println("properties are "+remap); fail("Returned event should have been empty"); } } else { assertEquals(le.getProperties(), remap); } comprareStringArrays( le.getThrowableStrRep(), re.getThrowableStrRep()); compareLocationInfo(le, re); } } void comprareStringArrays(String[] la, String[] ra) { if((la == null) && (ra == null)) { return; } assertEquals(la.length, ra.length); for(int i = 0; i < la.length; i++) { assertEquals(la[i], ra[i]); } } void compareLocationInfo(LoggingEvent l, LoggingEvent r) { if(l.locationInformationExists()) { assertEquals(l.getLocationInformation().fullInfo, r.getLocationInformation().fullInfo); } else { assertEquals(LocationInfo.NA_LOCATION_INFO, r.getLocationInformation()); } } Vector getRelevantEventsFromVA(VectorAppender va, long startTime) { assertNotNull(va); Vector v = va.getVector(); Vector r = new Vector(); // remove all elements older than startTime for(Iterator i = v.iterator(); i.hasNext(); ) { LoggingEvent event = (LoggingEvent) i.next(); if(startTime > event.getTimeStamp()) { System.out.println("***Removing event with timestamp "+event.getTimeStamp() + ": " + event.getMessage()); } else { System.out.println("***Keeping event with timestamp "+event.getTimeStamp() + ": " + event.getMessage()); r.add(event); } } return r; } void dump(Vector v) { for(int i = 0; i < v.size(); i++) { LoggingEvent le = (LoggingEvent) v.get(i); System.out.println("---"+le.getLevel()+" "+le.getLoggerName()+" "+le.getMessage()); } } public static Test XXsuite() { TestSuite suite = new TestSuite(); suite.addTest(new FullCycleDBTest("testSingleOutput")); suite.addTest(new FullCycleDBTest("testAllFields")); return suite; } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/receivers/helpers/000077500000000000000000000000001252742764200267475ustar00rootroot00000000000000UtilLoggingLevelTest.java000066400000000000000000000024741252742764200336160ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/receivers/helpers/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.helpers; import junit.framework.TestCase; /** * Unit tests for UtilLoggingLevel. */ public class UtilLoggingLevelTest extends TestCase { /** * Create new instance of test. * * @param testName test name */ public UtilLoggingLevelTest(final String testName) { super(testName); } /** * Test toLevel("fiNeSt"). */ public void testToLevelFINEST() { assertSame(UtilLoggingLevel.FINEST, UtilLoggingLevel.toLevel("fiNeSt")); } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/receivers/rewrite/000077500000000000000000000000001252742764200267665ustar00rootroot00000000000000RewriteAppenderTest.java000066400000000000000000000104651252742764200335200ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/receivers/rewrite/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.rewrite; import junit.framework.TestCase; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.apache.log4j.MDC; import org.apache.log4j.util.Compare; import org.apache.log4j.xml.DOMConfigurator; import org.w3c.dom.Document; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.InputStream; import java.util.Hashtable; import java.util.Map; import java.util.TreeMap; public class RewriteAppenderTest extends TestCase { public RewriteAppenderTest(final String name) { super(name); } public void setUp() { LogManager.getLoggerRepository().resetConfiguration(); Hashtable context = MDC.getContext(); if (context != null) { context.clear(); } } public void tearDown() { LogManager.getLoggerRepository().shutdown(); } public void configure(final String resourceName) throws Exception { InputStream is = RewriteAppenderTest.class.getResourceAsStream(resourceName); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(false); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(is); DOMConfigurator.configure(doc.getDocumentElement()); } public void testMapPolicy() throws Exception { configure("map.xml"); Logger logger = Logger.getLogger(RewriteAppenderTest.class); logger.info("Message 0"); MDC.put("p1", "Hola"); Map msg = new TreeMap(); msg.put("p1", "Hello"); msg.put("p2", "World"); msg.put("x1", "Mundo"); logger.info(msg); msg.put("message", "Message 1"); logger.info(msg); assertTrue(Compare.compare(RewriteAppenderTest.class, "target/temp", "map.log")); } private static class BaseBean { private final Object p2; private final Object x1; public BaseBean(final Object p2, final Object x1) { this.p2 = p2; this.x1 = x1; } public Object getP2() { return p2; } public Object getX1() { return x1; } public String toString() { return "I am bean."; } } private static class MessageBean extends BaseBean { private final Object msg; public MessageBean(final Object msg, final Object p2, final Object x1) { super(p2, x1); this.msg = msg; } public Object getMessage() { return msg; } } public void testReflectionPolicy() throws Exception { configure("reflection.xml"); Logger logger = Logger.getLogger(RewriteAppenderTest.class); logger.info("Message 0"); logger.info(new BaseBean("Hello", "World" )); MDC.put("p1", "Hola"); MDC.put("p2", "p2"); logger.info(new MessageBean("Welcome to The Hub", "Hello", "World" )); assertTrue(Compare.compare(RewriteAppenderTest.class, "target/temp", "reflection.log")); } public void testPropertyPolicy() throws Exception { configure("property.xml"); Logger logger = Logger.getLogger(RewriteAppenderTest.class); logger.info("Message 0"); MDC.put("p1", "Hola"); logger.info("Message 1"); assertTrue(Compare.compare(RewriteAppenderTest.class, "target/temp", "property.log")); } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/receivers/util/000077500000000000000000000000001252742764200262625ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/receivers/util/Compare.java000066400000000000000000000134721252742764200305220ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.util; import java.io.*; import java.util.zip.GZIPInputStream; public class Compare { static final int B1_NULL = -1; static final int B2_NULL = -2; private static final InputStream open( final Class testClass, final String fileName) throws IOException { String resourceName = fileName; if (fileName.startsWith("witness/")) { resourceName = fileName.substring(fileName.lastIndexOf('/') + 1); } InputStream is = testClass.getResourceAsStream(resourceName); if (is == null) { File file = new File(fileName); if (file.exists()) { is = new FileInputStream(file); } else { throw new FileNotFoundException("Resource " + resourceName + " not found"); } } return is; } public static boolean compare(Class testClass, final String file1, final String file2) throws IOException { BufferedReader in1 = new BufferedReader(new FileReader(file1)); BufferedReader in2 = new BufferedReader(new InputStreamReader( open(testClass, file2))); try { return compare(testClass, file1, file2, in1, in2); } finally { in1.close(); in2.close(); } } public static boolean compare( Class testClass, String file1, String file2, BufferedReader in1, BufferedReader in2) throws IOException { String s1; int lineCounter = 0; while ((s1 = in1.readLine()) != null) { lineCounter++; String s2 = in2.readLine(); if (!s1.equals(s2)) { System.out.println( "Files [" + file1 + "] and [" + file2 + "] differ on line " + lineCounter); System.out.println("One reads: [" + s1 + "]."); System.out.println("Other reads:[" + s2 + "]."); outputFile(testClass, file1); outputFile(testClass, file2); return false; } } // the second file is longer if (in2.read() != -1) { System.out.println( "File [" + file2 + "] longer than file [" + file1 + "]."); outputFile(testClass, file1); outputFile(testClass, file2); return false; } return true; } /** * * Prints file on the console. * */ private static void outputFile(Class testClass, String file) throws IOException { InputStream is = open(testClass, file); BufferedReader in1 = new BufferedReader(new InputStreamReader(is)); String s1; int lineCounter = 0; System.out.println("--------------------------------"); System.out.println("Contents of " + file + ":"); while ((s1 = in1.readLine()) != null) { lineCounter++; System.out.print(lineCounter); if (lineCounter < 10) { System.out.print(" : "); } else if (lineCounter < 100) { System.out.print(" : "); } else if (lineCounter < 1000) { System.out.print(" : "); } else { System.out.print(": "); } System.out.println(s1); } in1.close(); } public static boolean gzCompare(final Class testClass, final String actual, final String expected) throws FileNotFoundException, IOException { String resourceName = expected; int lastSlash = expected.lastIndexOf("/"); if (lastSlash >= 0) { resourceName = expected.substring(lastSlash + 1); } InputStream resourceStream = testClass.getResourceAsStream(resourceName); if (resourceStream == null) { throw new FileNotFoundException("Could not locate resource " + resourceName); } BufferedReader in1 = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(actual)))); BufferedReader in2 = new BufferedReader(new InputStreamReader(new GZIPInputStream(resourceStream))); try { return gzCompare(testClass, actual, expected, in1, in2); } finally { in1.close(); in2.close(); } } public static boolean gzCompare(Class testClass, String file1, String file2, BufferedReader in1, BufferedReader in2) throws IOException { String s1; int lineCounter = 0; while ((s1 = in1.readLine()) != null) { lineCounter++; String s2 = in2.readLine(); if (!s1.equals(s2)) { System.out.println( "Files [" + file1 + "] and [" + file2 + "] differ on line " + lineCounter); System.out.println("One reads: [" + s1 + "]."); System.out.println("Other reads:[" + s2 + "]."); outputFile(testClass, file1); outputFile(testClass, file2); return false; } } // the second file is longer if (in2.read() != -1) { System.out.println( "File [" + file2 + "] longer than file [" + file1 + "]."); outputFile(testClass, file1); outputFile(testClass, file2); return false; } return true; } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/receivers/xml/000077500000000000000000000000001252742764200261055ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/receivers/xml/XMLDecoderTest.java000066400000000000000000000056321252742764200315440ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.receivers.xml; import junit.framework.TestCase; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.nio.CharBuffer; import java.util.Vector; /** * Tests for XMLDecoder. * */ public class XMLDecoderTest extends TestCase { /** * Constructor for XMLDecoderTest. * @param arg0 test name. */ public XMLDecoderTest(String arg0) { super(arg0); } public String getStringFromResource(final String resourceName, final int maxSize) throws Exception { InputStream is = XMLDecoderTest.class.getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException(resourceName); } InputStreamReader reader = new InputStreamReader(is, "UTF-8"); CharBuffer cb = CharBuffer.allocate(maxSize); for(int chars = reader.read(cb); chars != -1; chars = reader.read(cb)); cb.flip(); return cb.toString(); } public void testDecodeEventsString1() throws Exception { String xmlStr = getStringFromResource("xmlLayout.1.xml", 10000); XMLDecoder decoder = new XMLDecoder(); Vector events = decoder.decodeEvents(xmlStr); assertEquals(17, events.size()); } public void testDecodeEventsString2() throws Exception { String xmlStr = getStringFromResource("xsltLayout.1.xml", 10000); XMLDecoder decoder = new XMLDecoder(); Vector events = decoder.decodeEvents(xmlStr); assertEquals(15, events.size()); } public void testDecodeEventsURL1() throws Exception { URL resource = XMLDecoderTest.class.getResource("xmlLayout.1.xml"); XMLDecoder decoder = new XMLDecoder(); Vector events = decoder.decode(resource); assertEquals(17, events.size()); } public void testDecodeEventsURL2() throws Exception { URL resource = XMLDecoderTest.class.getResource("xsltLayout.1.xml"); XMLDecoder decoder = new XMLDecoder(); Vector events = decoder.decode(resource); assertEquals(15, events.size()); } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/rolling/000077500000000000000000000000001252742764200247645ustar00rootroot00000000000000CompositeTriggeringPolicyTest.java000066400000000000000000000122311252742764200335530ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/rolling/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rolling; import junit.framework.Assert; import junit.framework.TestCase; import org.apache.log4j.Appender; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.apache.log4j.spi.LoggingEvent; /** * Test CompositeTriggeringPolicy * */ public class CompositeTriggeringPolicyTest extends TestCase { private CompositeTriggeringPolicy composite; private ConsoleAppender appender; private LoggingEvent event; protected void setUp() throws Exception { event = new LoggingEvent("Classname", Logger.getLogger("Logger"), System.currentTimeMillis(), Level.INFO, "msg", null); appender = new ConsoleAppender(new PatternLayout("%d %level %c -%m%n")); composite = new CompositeTriggeringPolicy(); } protected void tearDown() throws Exception { } public void testNoPolicies() { composite.activateOptions(); Assert.assertFalse(composite.isTriggeringEvent(appender, event, "file", 100)); } public void testOneTruePolicy() { composite.addTriggeringPolicy(new TestTriggeringPolicy(true)); composite.activateOptions(); Assert.assertTrue(composite.isTriggeringEvent(appender, event, "file", 100)); } public void testOneFalsePolicy() { composite.addTriggeringPolicy(new TestTriggeringPolicy(false)); composite.activateOptions(); Assert.assertFalse(composite.isTriggeringEvent(appender, event, "file", 100)); } public void testAllFalsePolicies() { composite.addTriggeringPolicy(new TestTriggeringPolicy(false)); composite.addTriggeringPolicy(new TestTriggeringPolicy(false)); composite.addTriggeringPolicy(new TestTriggeringPolicy(false)); composite.activateOptions(); Assert.assertFalse(composite.isTriggeringEvent(appender, event, "file", 100)); } public void testAllTruePolicies() { composite.addTriggeringPolicy(new TestTriggeringPolicy(true)); composite.addTriggeringPolicy(new TestTriggeringPolicy(true)); composite.addTriggeringPolicy(new TestTriggeringPolicy(true)); composite.activateOptions(); Assert.assertTrue(composite.isTriggeringEvent(appender, event, "file", 100)); } public void testTrueAndFalsePolicies() { composite.addTriggeringPolicy(new TestTriggeringPolicy(false)); composite.addTriggeringPolicy(new TestTriggeringPolicy(false)); composite.addTriggeringPolicy(new TestTriggeringPolicy(true)); composite.activateOptions(); Assert.assertTrue(composite.isTriggeringEvent(appender, event, "file", 100)); } public void testActivateOptionsCalledByCompositeActivateOptions() { TestTriggeringPolicy policy1 = new TestTriggeringPolicy(true); TestTriggeringPolicy policy2 = new TestTriggeringPolicy(true); composite.addTriggeringPolicy(policy1); composite.addTriggeringPolicy(policy2); composite.activateOptions(); Assert.assertTrue(policy1.activateOptionsCalled()); Assert.assertTrue(policy2.activateOptionsCalled()); } public void testActivateOptionsNotCalledByAddTriggeringPolicy() { TestTriggeringPolicy policy1 = new TestTriggeringPolicy(true); TestTriggeringPolicy policy2 = new TestTriggeringPolicy(true); composite.addTriggeringPolicy(policy1); composite.addTriggeringPolicy(policy2); Assert.assertFalse(policy1.activateOptionsCalled()); Assert.assertFalse(policy2.activateOptionsCalled()); } class TestTriggeringPolicy implements TriggeringPolicy { private final boolean result; private boolean activateOptionsCalled = false; public TestTriggeringPolicy(boolean result) { this.result = result; } public boolean activateOptionsCalled() { return activateOptionsCalled; } public boolean isTriggeringEvent(Appender appender, LoggingEvent event, String filename, long fileLength) { return result; } public void activateOptions() { activateOptionsCalled = true; } } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/rolling/FilterBasedRollingTest.java000066400000000000000000000112051252742764200322010ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rolling; import junit.framework.TestCase; import org.apache.log4j.Appender; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.apache.log4j.filter.LevelRangeFilter; import org.apache.log4j.util.Compare; import org.apache.log4j.extras.DOMConfigurator; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; /** * * Tests of rolling file appender with a filter based triggering policy. * * @author Curt Arnold * */ public class FilterBasedRollingTest extends TestCase { public FilterBasedRollingTest(String name) { super(name); } public void setUp() { Appender ca = new ConsoleAppender(new PatternLayout("%d %level %c -%m%n")); ca.setName("CONSOLE"); Logger.getRootLogger().addAppender(ca); } public void tearDown() { LogManager.getLoggerRepository().resetConfiguration(); } private static void configure(final String configName) throws IOException { String resourceName = configName; int lastSlash = resourceName.lastIndexOf("/"); if (lastSlash >= 0) { resourceName = resourceName.substring(lastSlash + 1); } InputStream is = TimeBasedRollingTest.class.getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Could not find resource " + resourceName); } DOMConfigurator configurator = new DOMConfigurator(); configurator.doConfigure(is, LogManager.getLoggerRepository()); } /** * Test basic rolling functionality using configuration file. */ public void test1() throws Exception { configure("filter1.xml"); common("target/filterBased-test1"); } /** * Test basic rolling functionality using explicit configuration. * Test fails when run immediately after test1. */ public void test2() throws Exception { PatternLayout layout = new PatternLayout("%m\n"); RollingFileAppender rfa = new RollingFileAppender(); rfa.setName("ROLLING"); rfa.setLayout(layout); FixedWindowRollingPolicy swrp = new FixedWindowRollingPolicy(); FilterBasedTriggeringPolicy fbtp = new FilterBasedTriggeringPolicy(); LevelRangeFilter rf = new LevelRangeFilter(); rf.setLevelMin(Level.INFO); fbtp.addFilter(rf); fbtp.activateOptions(); swrp.setMinIndex(0); rfa.setFile("target/filterBased-test2.log"); rfa.setAppend(false); swrp.setFileNamePattern("target/filterBased-test2.%i"); swrp.activateOptions(); rfa.setRollingPolicy(swrp); rfa.setTriggeringPolicy(fbtp); rfa.activateOptions(); Logger.getRootLogger().addAppender(rfa); Logger.getRootLogger().setLevel(Level.DEBUG); common("target/filterBased-test2"); } /** * Common aspects of test1 and test2 */ private void common(String baseName) throws Exception { Logger logger = Logger.getLogger(FilterBasedRollingTest.class); // Write exactly 10 bytes with each log for (int i = 0; i < 25; i++) { Thread.sleep(100); if (i < 10) { logger.debug("Hello---" + i); } else if (i < 100) { if ((i % 10) == 0) { // on the 10th and 20th request, raise the severity logger.warn("Hello--" + i); } else { logger.debug("Hello--" + i); } } } // // test was constructed to mimic SizeBasedRollingTest.test2 // assertTrue( Compare.compare(FilterBasedRollingTest.class, baseName + ".log", "witness/rolling/sbr-test2.log")); assertTrue( Compare.compare(FilterBasedRollingTest.class, baseName + ".0", "witness/rolling/sbr-test2.0")); assertTrue( Compare.compare(FilterBasedRollingTest.class, baseName + ".1", "witness/rolling/sbr-test2.1")); } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/rolling/RenamingTest.java000066400000000000000000000063571252742764200302420ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rolling; import junit.framework.TestCase; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.apache.log4j.util.Compare; import java.io.File; import java.text.SimpleDateFormat; import java.util.Calendar; /** * * This test case aims to unit test/reproduce problems encountered while * renaming the log file under windows. * * @author Ceki * */ public class RenamingTest extends TestCase { Logger logger = Logger.getLogger(RenamingTest.class); Logger root; PatternLayout layout; public RenamingTest(String arg0) { super(arg0); } protected void setUp() throws Exception { super.setUp(); root = Logger.getRootLogger(); layout = new PatternLayout("%c{1} - %m%n"); root.addAppender(new ConsoleAppender(new PatternLayout())); } protected void tearDown() throws Exception { super.tearDown(); } public void testRename() throws Exception { RollingFileAppender rfa = new RollingFileAppender(); rfa.setLayout(layout); rfa.setAppend(false); // rollover by the second String datePattern = "yyyy-MM-dd_HH_mm_ss"; SimpleDateFormat sdf = new SimpleDateFormat(datePattern); TimeBasedRollingPolicy tbrp = new TimeBasedRollingPolicy(); tbrp.setFileNamePattern("target/test-%d{" + datePattern + "}"); rfa.setFile("target/test.log"); tbrp.activateOptions(); rfa.setRollingPolicy(tbrp); rfa.activateOptions(); Calendar cal = Calendar.getInstance(); root.addAppender(rfa); logger.debug("Hello " + 0); Thread.sleep(5000); logger.debug("Hello " + 1); String rolledFile = "target/test-" + sdf.format(cal.getTime()); // // if the rolled file exists // either the test wasn't run from the Ant script // which opens test.log in another process or // the test is running on a platform that allows open files to be renamed if (new File(rolledFile).exists()) { assertTrue(Compare.compare(RenamingTest.class, rolledFile, "witness/rolling/renaming.0")); assertTrue(Compare.compare(RenamingTest.class, "target/test.log", "witness/rolling/renaming.1")); } else { // // otherwise the rollover should have been blocked // assertTrue(Compare.compare(RenamingTest.class, "target/test.log", "witness/rolling/renaming.2")); } } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/rolling/SizeBasedRollingTest.java000066400000000000000000000305501252742764200316720ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rolling; import junit.framework.TestCase; import org.apache.log4j.Appender; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.apache.log4j.util.Compare; import java.io.File; import java.io.FileOutputStream; /** * * Do not forget to call activateOptions when configuring programatically. * * @author Ceki Gülcü * */ public class SizeBasedRollingTest extends TestCase { Logger logger = Logger.getLogger(SizeBasedRollingTest.class); Logger root = Logger.getRootLogger(); public SizeBasedRollingTest(String name) { super(name); } public void setUp() { Appender ca = new ConsoleAppender(new PatternLayout("%d %level %c -%m%n")); ca.setName("CONSOLE"); root.addAppender(ca); } public void tearDown() { LogManager.shutdown(); } /** * Tests that the lack of an explicit active file will use the * low index as the active file. * */ public void test1() throws Exception { PatternLayout layout = new PatternLayout("%m\n"); RollingFileAppender rfa = new RollingFileAppender(); rfa.setName("ROLLING"); rfa.setAppend(false); rfa.setLayout(layout); FixedWindowRollingPolicy swrp = new FixedWindowRollingPolicy(); SizeBasedTriggeringPolicy sbtp = new SizeBasedTriggeringPolicy(); sbtp.setMaxFileSize(100); swrp.setMinIndex(0); swrp.setFileNamePattern("target/sizeBased-test1.%i"); swrp.activateOptions(); rfa.setRollingPolicy(swrp); rfa.setTriggeringPolicy(sbtp); rfa.activateOptions(); root.addAppender(rfa); // Write exactly 10 bytes with each log for (int i = 0; i < 25; i++) { if (i < 10) { logger.debug("Hello---" + i); } else if (i < 100) { logger.debug("Hello--" + i); } } assertTrue(new File("target/sizeBased-test1.0").exists()); assertTrue(new File("target/sizeBased-test1.1").exists()); assertTrue(new File("target/sizeBased-test1.2").exists()); assertTrue(Compare.compare(SizeBasedRollingTest.class, "target/sizeBased-test1.0", "witness/rolling/sbr-test2.log")); assertTrue(Compare.compare(SizeBasedRollingTest.class, "target/sizeBased-test1.1", "witness/rolling/sbr-test2.0")); assertTrue(Compare.compare(SizeBasedRollingTest.class, "target/sizeBased-test1.2", "witness/rolling/sbr-test2.1")); } /** * Test basic rolling functionality with explicit setting of FileAppender.file. */ public void test2() throws Exception { PatternLayout layout = new PatternLayout("%m\n"); RollingFileAppender rfa = new RollingFileAppender(); rfa.setName("ROLLING"); rfa.setAppend(false); rfa.setLayout(layout); rfa.setFile("target/sizeBased-test2.log"); FixedWindowRollingPolicy swrp = new FixedWindowRollingPolicy(); SizeBasedTriggeringPolicy sbtp = new SizeBasedTriggeringPolicy(); sbtp.setMaxFileSize(100); swrp.setMinIndex(0); swrp.setFileNamePattern("target/sizeBased-test2.%i"); swrp.activateOptions(); rfa.setRollingPolicy(swrp); rfa.setTriggeringPolicy(sbtp); rfa.activateOptions(); root.addAppender(rfa); // Write exactly 10 bytes with each log for (int i = 0; i < 25; i++) { if (i < 10) { logger.debug("Hello---" + i); } else if (i < 100) { logger.debug("Hello--" + i); } } assertTrue(new File("target/sizeBased-test2.log").exists()); assertTrue(new File("target/sizeBased-test2.0").exists()); assertTrue(new File("target/sizeBased-test2.1").exists()); assertTrue(Compare.compare(SizeBasedRollingTest.class, "target/sizeBased-test2.log", "witness/rolling/sbr-test2.log")); assertTrue(Compare.compare(SizeBasedRollingTest.class, "target/sizeBased-test2.0", "witness/rolling/sbr-test2.0")); assertTrue(Compare.compare(SizeBasedRollingTest.class, "target/sizeBased-test2.1", "witness/rolling/sbr-test2.1")); } /** * Same as testBasic but also with GZ compression. */ public void test3() throws Exception { PatternLayout layout = new PatternLayout("%m\n"); RollingFileAppender rfa = new RollingFileAppender(); rfa.setAppend(false); rfa.setLayout(layout); FixedWindowRollingPolicy fwrp = new FixedWindowRollingPolicy(); SizeBasedTriggeringPolicy sbtp = new SizeBasedTriggeringPolicy(); sbtp.setMaxFileSize(100); fwrp.setMinIndex(0); rfa.setFile("target/sbr-test3.log"); fwrp.setFileNamePattern("target/sbr-test3.%i.gz"); fwrp.activateOptions(); rfa.setRollingPolicy(fwrp); rfa.setTriggeringPolicy(sbtp); rfa.activateOptions(); root.addAppender(rfa); // Write exactly 10 bytes with each log for (int i = 0; i < 25; i++) { Thread.sleep(100); if (i < 10) { logger.debug("Hello---" + i); } else if (i < 100) { logger.debug("Hello--" + i); } } assertTrue(new File("target/sbr-test3.log").exists()); assertTrue(new File("target/sbr-test3.0.gz").exists()); assertTrue(new File("target/sbr-test3.1.gz").exists()); assertTrue(Compare.compare(SizeBasedRollingTest.class, "target/sbr-test3.log", "witness/rolling/sbr-test3.log")); assertTrue(Compare.gzCompare(SizeBasedRollingTest.class, "target/sbr-test3.0.gz", "witness/rolling/sbr-test3.0.gz")); assertTrue(Compare.gzCompare(SizeBasedRollingTest.class, "target/sbr-test3.1.gz", "witness/rolling/sbr-test3.1.gz")); } /** * Test basic rolling functionality with bogus path in file name pattern. */ public void test4() throws Exception { PatternLayout layout = new PatternLayout("%m\n"); RollingFileAppender rfa = new RollingFileAppender(); rfa.setName("ROLLING"); rfa.setAppend(false); rfa.setLayout(layout); rfa.setFile("target/sizeBased-test4.log"); FixedWindowRollingPolicy swrp = new FixedWindowRollingPolicy(); SizeBasedTriggeringPolicy sbtp = new SizeBasedTriggeringPolicy(); sbtp.setMaxFileSize(100); swrp.setMinIndex(0); // // test4 directory should not exists. Should cause all rollover attempts to fail. // swrp.setFileNamePattern("target/test4/sizeBased-test4.%i"); swrp.activateOptions(); rfa.setRollingPolicy(swrp); rfa.setTriggeringPolicy(sbtp); rfa.activateOptions(); root.addAppender(rfa); // Write exactly 10 bytes with each log for (int i = 0; i < 25; i++) { if (i < 10) { logger.debug("Hello---" + i); } else if (i < 100) { logger.debug("Hello--" + i); } } assertTrue(new File("target/sizeBased-test4.log").exists()); assertTrue(Compare.compare(SizeBasedRollingTest.class, "target/sizeBased-test4.log", "witness/rolling/sbr-test4.log")); } /** * Checking handling of rename failures due to other access * to the indexed files. */ public void test5() throws Exception { // // delete any stray files that might confuse test new File("target/sizeBased-test5.2").delete(); new File("target/sizeBased-test5.3").delete(); PatternLayout layout = new PatternLayout("%m\n"); RollingFileAppender rfa = new RollingFileAppender(); rfa.setName("ROLLING"); rfa.setAppend(false); rfa.setLayout(layout); rfa.setFile("target/sizeBased-test5.log"); FixedWindowRollingPolicy swrp = new FixedWindowRollingPolicy(); SizeBasedTriggeringPolicy sbtp = new SizeBasedTriggeringPolicy(); sbtp.setMaxFileSize(100); swrp.setMinIndex(0); swrp.setFileNamePattern("target/sizeBased-test5.%i"); swrp.activateOptions(); rfa.setRollingPolicy(swrp); rfa.setTriggeringPolicy(sbtp); rfa.activateOptions(); root.addAppender(rfa); // // put stray file above locked file FileOutputStream os1 = new FileOutputStream("target/sizeBased-test5.1"); os1.close(); FileOutputStream os0 = new FileOutputStream("target/sizeBased-test5.0"); // Write exactly 10 bytes with each log for (int i = 0; i < 25; i++) { if (i < 10) { logger.debug("Hello---" + i); } else if (i < 100) { logger.debug("Hello--" + i); } } os0.close(); if (new File("target/sizeBased-test5.3").exists()) { // // looks like platform where open files can be renamed // assertTrue(new File("target/sizeBased-test5.log").exists()); assertTrue(new File("target/sizeBased-test5.0").exists()); assertTrue(new File("target/sizeBased-test5.1").exists()); assertTrue(new File("target/sizeBased-test5.2").exists()); assertTrue(new File("target/sizeBased-test5.3").exists()); assertTrue(Compare.compare( SizeBasedRollingTest.class, "target/sizeBased-test5.log", "witness/rolling/sbr-test2.log")); assertTrue(Compare.compare(SizeBasedRollingTest.class, "target/sizeBased-test5.0", "witness/rolling/sbr-test2.0")); assertTrue(Compare.compare(SizeBasedRollingTest.class, "target/sizeBased-test5.1", "witness/rolling/sbr-test2.1")); } else { // // rollover attempts should all fail // so initial log file should have all log content // open file should be unaffected // stray file should have only been moved one slot. assertTrue(new File("target/sizeBased-test5.log").exists()); assertTrue(new File("target/sizeBased-test5.0").exists()); assertTrue(new File("target/sizeBased-test5.2").exists()); assertTrue(Compare.compare( SizeBasedRollingTest.class,"target/sizeBased-test5.log", "witness/rolling/sbr-test4.log")); } } /** * Test basic rolling functionality with explicit setting of * obsolete FixedWindowRollingPolicy.activeFileName. * @deprecated Tests deprecated method */ public void test6() throws Exception { PatternLayout layout = new PatternLayout("%m\n"); RollingFileAppender rfa = new RollingFileAppender(); rfa.setName("ROLLING"); rfa.setAppend(false); rfa.setLayout(layout); FixedWindowRollingPolicy swrp = new FixedWindowRollingPolicy(); SizeBasedTriggeringPolicy sbtp = new SizeBasedTriggeringPolicy(); sbtp.setMaxFileSize(100); swrp.setMinIndex(0); swrp.setActiveFileName("target/sizeBased-test6.log"); swrp.setFileNamePattern("target/sizeBased-test6.%i"); swrp.activateOptions(); rfa.setRollingPolicy(swrp); rfa.setTriggeringPolicy(sbtp); rfa.activateOptions(); root.addAppender(rfa); // Write exactly 10 bytes with each log for (int i = 0; i < 25; i++) { if (i < 10) { logger.debug("Hello---" + i); } else if (i < 100) { logger.debug("Hello--" + i); } } assertTrue(new File("target/sizeBased-test6.log").exists()); assertTrue(new File("target/sizeBased-test6.0").exists()); assertTrue(new File("target/sizeBased-test6.1").exists()); assertTrue(Compare.compare(SizeBasedRollingTest.class, "target/sizeBased-test6.log", "witness/rolling/sbr-test2.log")); assertTrue(Compare.compare(SizeBasedRollingTest.class, "target/sizeBased-test6.0", "witness/rolling/sbr-test2.0")); assertTrue(Compare.compare(SizeBasedRollingTest.class, "target/sizeBased-test6.1", "witness/rolling/sbr-test2.1")); } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/rolling/TimeBasedRollingTest.java000066400000000000000000000346541252742764200316670ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rolling; import junit.framework.TestCase; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.apache.log4j.util.Compare; import org.apache.log4j.extras.DOMConfigurator; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; /** * A rather exhaustive set of tests. Tests include leaving the ActiveFileName * argument blank, or setting it, with and without compression, and tests * with or without stopping/restarting the RollingFileAppender. * * The regression tests log a few times using a RollingFileAppender. Then, * they predict the names of the files which sould be generated and compare * them with witness files. * *
             Compression    ActiveFileName  Stop/Restart 
     Test1      NO              BLANK          NO
     Test2      NO              BLANK          YES
     Test3      YES             BLANK          NO
     Test4      NO                SET          YES 
     Test5      NO                SET          NO
     Test6      YES               SET          NO
     * 
    * @author Ceki Gülcü */ public class TimeBasedRollingTest extends TestCase { Logger logger = Logger.getLogger(TimeBasedRollingTest.class); public TimeBasedRollingTest(String name) { super(name); } public void setUp() { Logger root = Logger.getRootLogger(); root.addAppender( new ConsoleAppender(new PatternLayout("%d{ABSOLUTE} [%t] %level %c{2}#%M:%L - %m%n"))); } public void tearDown() { LogManager.shutdown(); } private static boolean compare(final String actual, final String expected) throws IOException { return Compare.compare(TimeBasedRollingTest.class, actual, expected); } private static boolean gzCompare(final String actual, final String expected) throws IOException { return Compare.gzCompare(TimeBasedRollingTest.class, actual, expected); } private static void configure(final String configName) throws IOException { String resourceName = configName; int lastSlash = resourceName.lastIndexOf("/"); if (lastSlash >= 0) { resourceName = resourceName.substring(lastSlash + 1); } InputStream is = TimeBasedRollingTest.class.getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Could not find resource " + resourceName); } DOMConfigurator configurator = new DOMConfigurator(); configurator.doConfigure(is, LogManager.getLoggerRepository()); } /** * Test rolling without compression, activeFileName left blank, no stop/start */ public void test1() throws Exception { PatternLayout layout = new PatternLayout("%c{1} - %m%n"); RollingFileAppender rfa = new RollingFileAppender(); rfa.setLayout(layout); String datePattern = "yyyy-MM-dd_HH_mm_ss"; TimeBasedRollingPolicy tbrp = new TimeBasedRollingPolicy(); tbrp.setFileNamePattern("target/test-tbr-1-%d{" + datePattern + "}"); tbrp.activateOptions(); rfa.setRollingPolicy(tbrp); rfa.activateOptions(); logger.addAppender(rfa); SimpleDateFormat sdf = new SimpleDateFormat(datePattern); String[] filenames = new String[4]; Calendar cal = Calendar.getInstance(); for (int i = 0; i < 4; i++) { filenames[i] = "target/test-tbr-1-" + sdf.format(cal.getTime()); cal.add(Calendar.SECOND, 1); } System.out.println("Waiting until next second and 100 millis."); delayUntilNextSecond(100); System.out.println("Done waiting."); for (int i = 0; i < 5; i++) { logger.debug("Hello---" + i); Thread.sleep(500); } for (int i = 0; i < 4; i++) { assertTrue(compare(filenames[i], "witness/rolling/tbr-test1." + i)); } } /** * No compression, with stop/restart, activeFileName left blank */ public void test2() throws Exception { String datePattern = "yyyy-MM-dd_HH_mm_ss"; PatternLayout layout1 = new PatternLayout("%c{1} - %m%n"); RollingFileAppender rfa1 = new RollingFileAppender(); rfa1.setLayout(layout1); TimeBasedRollingPolicy tbrp1 = new TimeBasedRollingPolicy(); tbrp1.setFileNamePattern("target/test2-%d{" + datePattern + "}"); tbrp1.activateOptions(); rfa1.setRollingPolicy(tbrp1); rfa1.activateOptions(); logger.addAppender(rfa1); SimpleDateFormat sdf = new SimpleDateFormat(datePattern); String[] filenames = new String[4]; Calendar cal = Calendar.getInstance(); for (int i = 0; i < 4; i++) { filenames[i] = "target/test2-" + sdf.format(cal.getTime()); cal.add(Calendar.SECOND, 1); } System.out.println("Waiting until next second and 100 millis."); delayUntilNextSecond(100); System.out.println("Done waiting."); for (int i = 0; i <= 2; i++) { logger.debug("Hello---" + i); Thread.sleep(500); } logger.removeAppender(rfa1); rfa1.close(); PatternLayout layout2 = new PatternLayout("%c{1} - %m%n"); RollingFileAppender rfa2 = new RollingFileAppender(); rfa2.setLayout(layout2); TimeBasedRollingPolicy tbrp2 = new TimeBasedRollingPolicy(); tbrp2.setFileNamePattern("target/test2-%d{" + datePattern + "}"); tbrp2.activateOptions(); rfa2.setRollingPolicy(tbrp2); rfa2.activateOptions(); logger.addAppender(rfa2); for (int i = 3; i <= 4; i++) { logger.debug("Hello---" + i); Thread.sleep(500); } rfa2.close(); for (int i = 0; i < 4; i++) { assertTrue(compare(filenames[i], "witness/rolling/tbr-test2." + i)); } } /** * With compression, activeFileName left blank, no stop/restart */ public void test3() throws Exception { PatternLayout layout = new PatternLayout("%c{1} - %m%n"); RollingFileAppender rfa = new RollingFileAppender(); rfa.setLayout(layout); String datePattern = "yyyy-MM-dd_HH_mm_ss"; TimeBasedRollingPolicy tbrp = new TimeBasedRollingPolicy(); tbrp.setFileNamePattern("target/test3-%d{" + datePattern + "}.gz"); tbrp.activateOptions(); rfa.setRollingPolicy(tbrp); rfa.activateOptions(); logger.addAppender(rfa); SimpleDateFormat sdf = new SimpleDateFormat(datePattern); String[] filenames = new String[4]; Calendar cal = Calendar.getInstance(); for (int i = 0; i < 3; i++) { filenames[i] = "target/test3-" + sdf.format(cal.getTime()) + ".gz"; cal.add(Calendar.SECOND, 1); } filenames[3] = "target/test3-" + sdf.format(cal.getTime()); System.out.println("Waiting until next second and 100 millis."); delayUntilNextSecond(100); System.out.println("Done waiting."); for (int i = 0; i < 5; i++) { logger.debug("Hello---" + i); Thread.sleep(500); } rfa.close(); for (int i = 0; i < 3; i++) { assertTrue(gzCompare(filenames[i], "witness/rolling/tbr-test3." + i + ".gz")); } assertTrue(compare(filenames[3], "witness/rolling/tbr-test3.3")); } /** * Without compression, activeFileName set, with stop/restart */ public void test4() throws Exception { String datePattern = "yyyy-MM-dd_HH_mm_ss"; PatternLayout layout1 = new PatternLayout("%c{1} - %m%n"); RollingFileAppender rfa1 = new RollingFileAppender(); rfa1.setLayout(layout1); TimeBasedRollingPolicy tbrp1 = new TimeBasedRollingPolicy(); rfa1.setFile("target/test4.log"); tbrp1.setFileNamePattern("target/test4-%d{" + datePattern + "}"); tbrp1.activateOptions(); rfa1.setRollingPolicy(tbrp1); rfa1.setAppend(false); rfa1.activateOptions(); logger.addAppender(rfa1); SimpleDateFormat sdf = new SimpleDateFormat(datePattern); String[] filenames = new String[4]; Calendar cal = Calendar.getInstance(); for (int i = 0; i < 3; i++) { filenames[i] = "target/test4-" + sdf.format(cal.getTime()); cal.add(Calendar.SECOND, 1); } filenames[3] = "target/test4.log"; System.out.println("Waiting until next second and 100 millis."); delayUntilNextSecond(100); System.out.println("Done waiting."); for (int i = 0; i <= 2; i++) { logger.debug("Hello---" + i); Thread.sleep(500); } logger.removeAppender(rfa1); rfa1.close(); PatternLayout layout2 = new PatternLayout("%c{1} - %m%n"); RollingFileAppender rfa2 = new RollingFileAppender(); rfa2.setLayout(layout2); TimeBasedRollingPolicy tbrp2 = new TimeBasedRollingPolicy(); tbrp2.setFileNamePattern("target/test4-%d{" + datePattern + "}"); rfa2.setFile("target/test4.log"); tbrp2.activateOptions(); rfa2.setRollingPolicy(tbrp2); rfa2.activateOptions(); logger.addAppender(rfa2); for (int i = 3; i <= 4; i++) { logger.debug("Hello---" + i); Thread.sleep(500); } rfa2.close(); for (int i = 0; i < 4; i++) { assertTrue(compare(filenames[i], "witness/rolling/tbr-test4." + i)); } } /** * No compression, activeFileName set, without stop/restart */ public void test5() throws Exception { PatternLayout layout = new PatternLayout("%c{1} - %m%n"); RollingFileAppender rfa = new RollingFileAppender(); rfa.setLayout(layout); String datePattern = "yyyy-MM-dd_HH_mm_ss"; TimeBasedRollingPolicy tbrp = new TimeBasedRollingPolicy(); tbrp.setFileNamePattern("target/test5-%d{" + datePattern + "}"); rfa.setFile("target/test5.log"); tbrp.activateOptions(); rfa.setRollingPolicy(tbrp); rfa.setAppend(false); rfa.activateOptions(); logger.addAppender(rfa); SimpleDateFormat sdf = new SimpleDateFormat(datePattern); String[] filenames = new String[4]; Calendar cal = Calendar.getInstance(); for (int i = 0; i < 3; i++) { filenames[i] = "target/test5-" + sdf.format(cal.getTime()); cal.add(Calendar.SECOND, 1); } filenames[3] = "target/test5.log"; System.out.println("Waiting until next second and 100 millis."); delayUntilNextSecond(100); System.out.println("Done waiting."); for (int i = 0; i < 5; i++) { logger.debug("Hello---" + i); Thread.sleep(500); } for (int i = 0; i < 4; i++) { assertTrue(compare(filenames[i], "witness/rolling/tbr-test5." + i)); } } /** * With compression, activeFileName set, no stop/restart, */ public void test6() throws Exception { PatternLayout layout = new PatternLayout("%c{1} - %m%n"); RollingFileAppender rfa = new RollingFileAppender(); rfa.setLayout(layout); String datePattern = "yyyy-MM-dd_HH_mm_ss"; TimeBasedRollingPolicy tbrp = new TimeBasedRollingPolicy(); tbrp.setFileNamePattern("target/test6-%d{" + datePattern + "}.gz"); rfa.setFile("target/test6.log"); tbrp.activateOptions(); rfa.setRollingPolicy(tbrp); rfa.setAppend(false); rfa.activateOptions(); logger.addAppender(rfa); SimpleDateFormat sdf = new SimpleDateFormat(datePattern); String[] filenames = new String[4]; Calendar cal = Calendar.getInstance(); for (int i = 0; i < 3; i++) { filenames[i] = "target/test6-" + sdf.format(cal.getTime()) + ".gz"; cal.add(Calendar.SECOND, 1); } filenames[3] = "target/test6.log"; System.out.println("Waiting until next second and 100 millis."); delayUntilNextSecond(100); System.out.println("Done waiting."); for (int i = 0; i < 5; i++) { logger.debug("Hello---" + i); Thread.sleep(500); } rfa.close(); for (int i = 0; i < 3; i++) { assertTrue(gzCompare(filenames[i], "witness/rolling/tbr-test6." + i + ".gz")); } assertTrue(compare(filenames[3], "witness/rolling/tbr-test6.3")); } public void testWithJoran1() throws Exception { configure("./input/rolling/time1.xml"); String datePattern = "yyyy-MM-dd_HH_mm_ss"; SimpleDateFormat sdf = new SimpleDateFormat(datePattern); String[] filenames = new String[4]; Calendar cal = Calendar.getInstance(); for (int i = 0; i < 4; i++) { filenames[i] = "target/test1-" + sdf.format(cal.getTime()); cal.add(Calendar.SECOND, 1); } System.out.println("Waiting until next second and 100 millis."); delayUntilNextSecond(100); System.out.println("Done waiting."); for (int i = 0; i < 5; i++) { logger.debug("Hello---" + i); Thread.sleep(500); } for (int i = 0; i < 4; i++) { assertTrue(compare(filenames[i], "witness/rolling/tbr-test1." + i)); } } public void XXXtestWithJoran10() throws Exception { configure("./input/rolling/time2.xml"); String datePattern = "yyyy-MM-dd"; SimpleDateFormat sdf = new SimpleDateFormat(datePattern); String[] filenames = new String[0]; Calendar cal = Calendar.getInstance(); filenames[0] = "target/test1-" + sdf.format(cal.getTime()); for (int i = 0; i < 5; i++) { logger.debug("Hello---" + i); Thread.sleep(500); } for (int i = 0; i < 1; i++) { assertTrue(compare(filenames[i], "witness/rolling/tbr-test10." + i)); } } void delayUntilNextSecond(int millis) { long now = System.currentTimeMillis(); Calendar cal = Calendar.getInstance(); cal.setTime(new Date(now)); cal.set(Calendar.MILLISECOND, millis); cal.add(Calendar.SECOND, 1); long next = cal.getTime().getTime(); try { Thread.sleep(next - now); } catch (Exception e) { } } void delayUntilNextMinute(int seconds) { long now = System.currentTimeMillis(); Calendar cal = Calendar.getInstance(); cal.setTime(new Date(now)); cal.set(Calendar.SECOND, seconds); cal.add(Calendar.MINUTE, 1); long next = cal.getTime().getTime(); try { Thread.sleep(next - now); } catch (Exception e) { } } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/rolling/helper/000077500000000000000000000000001252742764200262435ustar00rootroot00000000000000FileNamePatternTestCase.java000066400000000000000000000112501252742764200335000ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/rolling/helper/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rolling.helper; import junit.framework.TestCase; import org.apache.log4j.rolling.RollingPolicyBase; import org.apache.log4j.rolling.RolloverDescription; import java.util.Calendar; /** * Tests for FileNamePattern. * * @author Ceki * @author Curt Arnold * */ public final class FileNamePatternTestCase extends TestCase { /** * Construct new test. * @param name test name */ public FileNamePatternTestCase(final String name) { super(name); } private static class FileNameTestRollingPolicy extends RollingPolicyBase { public FileNameTestRollingPolicy(final String pattern) { setFileNamePattern(pattern); parseFileNamePattern(); } public void activateOptions() { } public RolloverDescription initialize(final String activeName, final boolean append) { return null; } public RolloverDescription rollover(final String activeName) { return null; } public String format(Object obj) { StringBuffer buf = new StringBuffer(); formatFileName(obj, buf); return buf.toString(); } } private void assertDatePattern(final String pattern, final int year, final int month, final int day, final int hour, final int min, final String expected) { Calendar cal = Calendar.getInstance(); cal.set(year, month, day, hour, min); FileNameTestRollingPolicy policy = new FileNameTestRollingPolicy(pattern); assertEquals(expected, policy.format(cal.getTime())); } private void assertIntegerPattern(final String pattern, final int value, final String expected) { FileNameTestRollingPolicy policy = new FileNameTestRollingPolicy(pattern); assertEquals(expected, policy.format(new Integer(value))); } public void testFormatInteger1() { assertIntegerPattern("t", 3, "t"); } public void testFormatInteger2() { assertIntegerPattern("foo", 3, "foo"); } public void testFormatInteger3() { assertIntegerPattern("foo%", 3, "foo%"); } public void testFormatInteger4() { assertIntegerPattern("%ifoo", 3, "3foo"); } public void testFormatInteger5() { assertIntegerPattern("foo%ixixo", 3, "foo3xixo"); } public void testFormatInteger6() { assertIntegerPattern("foo%i.log", 3, "foo3.log"); } public void testFormatInteger7() { assertIntegerPattern("foo.%i.log", 3, "foo.3.log"); } public void testFormatInteger8() { assertIntegerPattern("%ifoo%", 3, "3foo%"); } public void testFormatInteger9() { assertIntegerPattern("%ifoo%%", 3, "3foo%"); } public void testFormatInteger10() { assertIntegerPattern("%%foo", 3, "%foo"); } public void testFormatInteger11() { assertIntegerPattern("foo%ibar%i", 3, "foo3bar3"); } public void testFormatDate1() { assertDatePattern("foo%d{yyyy.MM.dd}", 2003, 4, 20, 17, 55, "foo2003.05.20"); } public void testFormatDate2() { assertDatePattern("foo%d{yyyy.MM.dd HH:mm}", 2003, 4, 20, 17, 55, "foo2003.05.20 17:55"); } public void testFormatDate3() { assertDatePattern("%d{yyyy.MM.dd HH:mm} foo", 2003, 4, 20, 17, 55, "2003.05.20 17:55 foo"); } /** * A %d is treated as %d{yyyy-MM-dd} if followed by a malformed format specifier. * */ public void testFormatDate4() { assertDatePattern("foo%dyyyy.MM.dd}", 2003, 4, 20, 17, 55, "foo2003-05-20yyyy.MM.dd}"); } /** * A %d is treated as %d{yyyy-MM-dd} if followed by a malformed format specifier. * */ public void testFormatDate5() { assertDatePattern("foo%d{yyyy.MM.dd", 2003, 4, 20, 17, 55, "foo2003-05-20{yyyy.MM.dd"); } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/rule/000077500000000000000000000000001252742764200242655ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/rule/AndRuleTest.java000066400000000000000000000127721252742764200273330ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rule; import junit.framework.TestCase; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.util.SerializationTestHelper; import java.io.IOException; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Stack; /** * Test for AndRule. */ public class AndRuleTest extends TestCase { /** * Create new test. * * @param testName test name. */ public AndRuleTest(final String testName) { super(testName); } /** * AndRule.getRule(Stack) throws exception if only one rule provided. */ public void test1() { Stack stack = new Stack(); stack.push(LevelEqualsRule.getRule("INFO")); try { AndRule.getRule(stack); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException ex) { } } /** * AndRule.getRule(Stack) throws exception if non-rules are provided. */ public void test2() { Stack stack = new Stack(); stack.push("Hello"); stack.push("World"); try { AndRule.getRule(stack); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException ex) { } } /** * Test And of Level and Time. */ public void test3() { Stack stack = new Stack(); stack.push(LevelEqualsRule.getRule("INFO")); stack.push(TimestampInequalityRule.getRule(">=", "2008/05/21 00:44:45")); Rule rule = AndRule.getRule(stack); assertEquals(0, stack.size()); Calendar cal = new GregorianCalendar(2008, 04, 21, 00, 45, 44); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), cal.getTimeInMillis(), Level.INFO, "Hello, World", null); assertTrue(rule.evaluate(event, null)); } /** * Test And of Level and Time when Level does not match. */ public void test4() { Stack stack = new Stack(); stack.push(LevelEqualsRule.getRule("INFO")); stack.push(TimestampInequalityRule.getRule(">=", "2008/05/21 00:44:45")); Rule rule = AndRule.getRule(stack); assertEquals(0, stack.size()); Calendar cal = new GregorianCalendar(2008, 04, 21, 00, 45, 44); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), cal.getTimeInMillis(), Level.WARN, "Hello, World", null); assertFalse(rule.evaluate(event, null)); } /** * Test And of Level and Time when Time does not match. */ public void test5() { Stack stack = new Stack(); stack.push(LevelEqualsRule.getRule("INFO")); stack.push(TimestampInequalityRule.getRule(">=", "2009/05/21 00:44:45")); Rule rule = AndRule.getRule(stack); assertEquals(0, stack.size()); Calendar cal = new GregorianCalendar(2008, 04, 21, 00, 45, 44); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), cal.getTimeInMillis(), Level.INFO, "Hello, World", null); assertFalse(rule.evaluate(event, null)); } /** * Test deserialized And. */ public void test6() throws IOException, ClassNotFoundException { Stack stack = new Stack(); stack.push(LevelEqualsRule.getRule("INFO")); stack.push(TimestampInequalityRule.getRule(">=", "2008/05/21 00:44:45")); Rule rule = (Rule) SerializationTestHelper.serializeClone(AndRule.getRule(stack)); assertEquals(0, stack.size()); Calendar cal = new GregorianCalendar(2008, 04, 21, 00, 45, 44); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), cal.getTimeInMillis(), Level.INFO, "Hello, World", null); assertTrue(rule.evaluate(event, null)); } /** * Test deserialized And when Level doesn't match. */ public void test7() throws IOException, ClassNotFoundException { Stack stack = new Stack(); stack.push(LevelEqualsRule.getRule("INFO")); stack.push(TimestampInequalityRule.getRule(">=", "2008/05/21 00:44:45")); Rule rule = (Rule) SerializationTestHelper.serializeClone(AndRule.getRule(stack)); assertEquals(0, stack.size()); Calendar cal = new GregorianCalendar(2008, 04, 21, 00, 45, 44); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), cal.getTimeInMillis(), Level.WARN, "Hello, World", null); assertFalse(rule.evaluate(event, null)); } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/rule/EqualsRuleTest.java000066400000000000000000000117541252742764200300620ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rule; import junit.framework.TestCase; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.util.SerializationTestHelper; import java.io.IOException; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Stack; /** * Test for EqualsRule. */ public class EqualsRuleTest extends TestCase { /** * Create new test. * * @param testName test name. */ public EqualsRuleTest(final String testName) { super(testName); } /** * getRule() with only one entry on stack should throw IllegalArgumentException. */ public void test1() { Stack stack = new Stack(); stack.push("Hello"); try { EqualsRule.getRule(stack); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException ex) { } } /** * getRule() with bad field name should throw IllegalArgumentException. */ public void test2() { Stack stack = new Stack(); stack.push("Hello"); stack.push("World"); try { EqualsRule.getRule(stack); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException ex) { } } /** * getRule with "level" and "info" should return a LevelEqualsRule. */ public void test3() { Stack stack = new Stack(); stack.push("level"); stack.push("info"); Rule rule = EqualsRule.getRule(stack); assertEquals(0, stack.size()); assertTrue(rule instanceof LevelEqualsRule); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), System.currentTimeMillis(), Level.INFO, "Hello, World", null); assertTrue(rule.evaluate(event, null)); } /** * getRule with "timestamp" and time should return a TimestampEqualsRule. */ public void test4() { Stack stack = new Stack(); stack.push("timestamp"); stack.push("2008/05/21 00:45:44"); Rule rule = EqualsRule.getRule(stack); assertEquals(0, stack.size()); assertTrue(rule instanceof TimestampEqualsRule); Calendar cal = new GregorianCalendar(2008, 04, 21, 00, 45, 44); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), cal.getTimeInMillis(), Level.INFO, "Hello, World", null); assertTrue(rule.evaluate(event, null)); } /** * getRule with "msg" should return an EqualsRule. */ public void test5() { Stack stack = new Stack(); stack.push("msg"); stack.push("Hello, World"); Rule rule = EqualsRule.getRule(stack); assertEquals(0, stack.size()); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), System.currentTimeMillis(), Level.INFO, "Hello, World", null); assertTrue(rule.evaluate(event, null)); } /** * getRule with "msg" should return an EqualsRule. */ public void test6() { Stack stack = new Stack(); stack.push("msg"); stack.push("Bonjour, Monde"); Rule rule = EqualsRule.getRule(stack); assertEquals(0, stack.size()); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), System.currentTimeMillis(), Level.INFO, "Hello, World", null); assertFalse(rule.evaluate(event, null)); } /** * Check EqualsRule serialization. */ public void test7() throws IOException, ClassNotFoundException { Stack stack = new Stack(); stack.push("msg"); stack.push("Hello, World"); Rule rule = (Rule) SerializationTestHelper.serializeClone(EqualsRule.getRule(stack)); assertEquals(0, stack.size()); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), System.currentTimeMillis(), Level.INFO, "Hello, World", null); assertTrue(rule.evaluate(event, null)); } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/rule/ExistsRuleTest.java000066400000000000000000000066571252742764200301150ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rule; import junit.framework.TestCase; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.util.SerializationTestHelper; import java.io.IOException; import java.util.Stack; /** * Test for ExistsRule. */ public class ExistsRuleTest extends TestCase { /** * Create new test. * * @param testName test name. */ public ExistsRuleTest(final String testName) { super(testName); } /** * getRule() with no entry on stack should throw IllegalArgumentException. */ public void test1() { Stack stack = new Stack(); try { ExistsRule.getRule(stack); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException ex) { } } /** * getRule() with bad field name should throw IllegalArgumentException. */ public void test2() { Stack stack = new Stack(); stack.push("Hello"); try { ExistsRule.getRule(stack); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException ex) { } } /** * getRule with "msg". */ public void test3() { Stack stack = new Stack(); stack.push("msg"); Rule rule = ExistsRule.getRule(stack); assertEquals(0, stack.size()); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), System.currentTimeMillis(), Level.INFO, "Hello, World", null); assertTrue(rule.evaluate(event, null)); } /** * getRule with "msg". */ public void test4() { Stack stack = new Stack(); stack.push("msg"); Rule rule = ExistsRule.getRule(stack); assertEquals(0, stack.size()); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), System.currentTimeMillis(), Level.INFO, "", null); assertFalse(rule.evaluate(event, null)); } /** * getRule with "msg". */ public void test5() throws IOException, ClassNotFoundException { Stack stack = new Stack(); stack.push("msg"); Rule rule = (Rule) SerializationTestHelper.serializeClone(ExistsRule.getRule(stack)); assertEquals(0, stack.size()); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), System.currentTimeMillis(), Level.INFO, "Hello, World", null); assertTrue(rule.evaluate(event, null)); } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/rule/LevelEqualsRuleTest.java000066400000000000000000000123271252742764200310470ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rule; import junit.framework.TestCase; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.helpers.UtilLoggingLevel; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.util.SerializationTestHelper; import java.io.IOException; /** * Test for LevelEqualsRule. */ public class LevelEqualsRuleTest extends TestCase { /** * Create new test. * * @param testName test name. */ public LevelEqualsRuleTest(final String testName) { super(testName); } /** * Tests evaluate when levels are equal. */ public void test1() { LevelEqualsRule rule = (LevelEqualsRule) LevelEqualsRule.getRule("info"); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), System.currentTimeMillis(), Level.INFO, "Hello, World", null); assertTrue(rule.evaluate(event, null)); } /** * Tests evaluate when levels are not equal. */ public void test2() { LevelEqualsRule rule = (LevelEqualsRule) LevelEqualsRule.getRule("info"); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), System.currentTimeMillis(), Level.WARN, "Hello, World", null); assertFalse(rule.evaluate(event, null)); } /** * Tests evaluate of a deserialized clone when levels are equal. */ public void test3() throws IOException, ClassNotFoundException { LevelEqualsRule rule = (LevelEqualsRule) SerializationTestHelper.serializeClone(LevelEqualsRule.getRule("info")); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), System.currentTimeMillis(), Level.INFO, "Hello, World", null); assertTrue(rule.evaluate(event, null)); } /** * Tests evaluate of a deserialized clone when levels are not equal. */ public void test4() throws IOException, ClassNotFoundException { LevelEqualsRule rule = (LevelEqualsRule) SerializationTestHelper.serializeClone(LevelEqualsRule.getRule("info")); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), System.currentTimeMillis(), Level.WARN, "Hello, World", null); assertFalse(rule.evaluate(event, null)); } /** * Tests evaluate when levels are JDK 1.4 levels and equal. */ public void test5() { LevelEqualsRule rule = (LevelEqualsRule) LevelEqualsRule.getRule("finer"); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), System.currentTimeMillis(), UtilLoggingLevel.FINER, "Hello, World", null); assertTrue(rule.evaluate(event, null)); } /** * Tests evaluate when levels are JDK 1.4 levels and not equal. */ public void test6() { LevelEqualsRule rule = (LevelEqualsRule) LevelEqualsRule.getRule("finer"); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), System.currentTimeMillis(), UtilLoggingLevel.FINE, "Hello, World", null); assertFalse(rule.evaluate(event, null)); } /** * Tests evaluate of a deserialized clone when levels are JDK 1.4 levels and equal. */ public void test7() throws IOException, ClassNotFoundException { LevelEqualsRule rule = (LevelEqualsRule) SerializationTestHelper.serializeClone(LevelEqualsRule.getRule("finer")); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), System.currentTimeMillis(), UtilLoggingLevel.FINER, "Hello, World", null); assertTrue(rule.evaluate(event, null)); } /** * Tests evaluate of a deserialized clone when levels are JDK 1.4 levels and not equal. */ public void test8() throws IOException, ClassNotFoundException { LevelEqualsRule rule = (LevelEqualsRule) SerializationTestHelper.serializeClone(LevelEqualsRule.getRule("finer")); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), System.currentTimeMillis(), UtilLoggingLevel.FINE, "Hello, World", null); assertFalse(rule.evaluate(event, null)); } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/rule/LevelInequalityRuleTest.java000066400000000000000000000115161252742764200317400ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rule; import junit.framework.TestCase; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.helpers.UtilLoggingLevel; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.util.SerializationTestHelper; import java.io.IOException; /** * Test for LevelInequalityRule. */ public class LevelInequalityRuleTest extends TestCase { /** * Create new test. * * @param testName test name. */ public LevelInequalityRuleTest(final String testName) { super(testName); } /** * Test construction when level is unrecognized. */ public void test1() { try { LevelInequalityRule.getRule(">", "emergency"); fail("Expected IllegalArgumentException"); } catch(IllegalArgumentException ex) { } } /** * Tests construction when operator is unrecognized. */ public void test2() { Rule rule = LevelInequalityRule.getRule("~", "iNfO"); assertNull(rule); } /** * Tests evaluate of a deserialized clone when level satisfies rule. */ public void test3() throws IOException, ClassNotFoundException { Rule rule = (Rule) SerializationTestHelper.serializeClone(LevelInequalityRule.getRule(">=", "info")); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), System.currentTimeMillis(), Level.INFO, "Hello, World", null); assertTrue(rule.evaluate(event, null)); } /** * Tests evaluate of a deserialized clone when level does not satisfy rule. */ public void test4() throws IOException, ClassNotFoundException { Rule rule = (Rule) SerializationTestHelper.serializeClone(LevelInequalityRule.getRule("<", "info")); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), System.currentTimeMillis(), Level.INFO, "Hello, World", null); assertFalse(rule.evaluate(event, null)); } /** * Tests evaluate when levels are JDK 1.4 levels and satisified. */ public void test5() { Rule rule = (Rule) LevelInequalityRule.getRule(">=", "finer"); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), System.currentTimeMillis(), UtilLoggingLevel.FINER, "Hello, World", null); assertTrue(rule.evaluate(event, null)); } /** * Tests evaluate when levels are JDK 1.4 levels and not equal. */ public void test6() { Rule rule = (Rule) LevelInequalityRule.getRule("<", "finer"); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), System.currentTimeMillis(), UtilLoggingLevel.FINER, "Hello, World", null); assertFalse(rule.evaluate(event, null)); } /** * Tests evaluate of a deserialized clone when levels are JDK 1.4 levels and satisified. */ public void test7() throws IOException, ClassNotFoundException { Rule rule = (Rule) SerializationTestHelper.serializeClone(LevelInequalityRule.getRule(">=", "finer")); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), System.currentTimeMillis(), UtilLoggingLevel.FINER, "Hello, World", null); assertTrue(rule.evaluate(event, null)); } /** * Tests evaluate of a deserialized clone when levels are JDK 1.4 levels and not satified. */ public void test8() throws IOException, ClassNotFoundException { Rule rule = (Rule) SerializationTestHelper.serializeClone(LevelInequalityRule.getRule("<", "finer")); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), System.currentTimeMillis(), UtilLoggingLevel.FINER, "Hello, World", null); assertFalse(rule.evaluate(event, null)); } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/rule/NotEqualsRuleTest.java000066400000000000000000000114441252742764200305370ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rule; import junit.framework.TestCase; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.util.SerializationTestHelper; import java.io.IOException; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Stack; /** * Test for NotEqualsRule. */ public class NotEqualsRuleTest extends TestCase { /** * Create new test. * * @param testName test name. */ public NotEqualsRuleTest(final String testName) { super(testName); } /** * getRule() with only one entry on stack should throw IllegalArgumentException. */ public void test1() { Stack stack = new Stack(); stack.push("Hello"); try { NotEqualsRule.getRule(stack); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException ex) { } } /** * getRule() with bad field name should throw IllegalArgumentException. */ public void test2() { Stack stack = new Stack(); stack.push("Hello"); stack.push("World"); try { NotEqualsRule.getRule(stack); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException ex) { } } /** * getRule with "level" and "info". */ public void test3() { Stack stack = new Stack(); stack.push("level"); stack.push("info"); Rule rule = NotEqualsRule.getRule(stack); assertEquals(0, stack.size()); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), System.currentTimeMillis(), Level.WARN, "Hello, World", null); assertTrue(rule.evaluate(event, null)); } /** * getRule with "timestamp" and time. */ public void test4() { Stack stack = new Stack(); stack.push("timestamp"); stack.push("2008/05/21 00:45:44"); Rule rule = NotEqualsRule.getRule(stack); assertEquals(0, stack.size()); Calendar cal = new GregorianCalendar(2009, 04, 21, 00, 45, 44); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), cal.getTimeInMillis(), Level.INFO, "Hello, World", null); assertTrue(rule.evaluate(event, null)); } /** * getRule with "msg". */ public void test5() { Stack stack = new Stack(); stack.push("msg"); stack.push("Hello, World"); Rule rule = NotEqualsRule.getRule(stack); assertEquals(0, stack.size()); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), System.currentTimeMillis(), Level.INFO, "Hello, World", null); assertFalse(rule.evaluate(event, null)); } /** * getRule with "msg". */ public void test6() { Stack stack = new Stack(); stack.push("msg"); stack.push("Bonjour, Monde"); Rule rule = NotEqualsRule.getRule(stack); assertEquals(0, stack.size()); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), System.currentTimeMillis(), Level.INFO, "Hello, World", null); assertTrue(rule.evaluate(event, null)); } /** * Check NotEqualsRule serialization. */ public void test7() throws IOException, ClassNotFoundException { Stack stack = new Stack(); stack.push("msg"); stack.push("Hello, World"); Rule rule = (Rule) SerializationTestHelper.serializeClone(NotEqualsRule.getRule(stack)); assertEquals(0, stack.size()); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), System.currentTimeMillis(), Level.INFO, "Hello, World", null); assertFalse(rule.evaluate(event, null)); } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/rule/NotRuleTest.java000066400000000000000000000106411252742764200273620ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rule; import junit.framework.TestCase; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.util.SerializationTestHelper; import java.io.IOException; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Stack; /** * Test for NotRule. */ public class NotRuleTest extends TestCase { /** * Create new test. * * @param testName test name. */ public NotRuleTest(final String testName) { super(testName); } /** * NotRule.getRule(Stack) throws exception if only one rule provided. */ public void test1() { Stack stack = new Stack(); try { NotRule.getRule(stack); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException ex) { } } /** * NotRule.getRule(Stack) throws exception if non-rules are provided. */ public void test2() { Stack stack = new Stack(); stack.push("Hello"); try { NotRule.getRule(stack); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException ex) { } } /** * Test Not of LevelEqualsRule. */ public void test3() { Stack stack = new Stack(); stack.push(LevelEqualsRule.getRule("INFO")); Rule rule = NotRule.getRule(stack); assertEquals(0, stack.size()); Calendar cal = new GregorianCalendar(2008, 04, 21, 00, 45, 44); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), cal.getTimeInMillis(), Level.INFO, "Hello, World", null); assertFalse(rule.evaluate(event, null)); } /** * Test Not of Level when Level does not match. */ public void test4() { Stack stack = new Stack(); stack.push(LevelEqualsRule.getRule("INFO")); Rule rule = NotRule.getRule(stack); assertEquals(0, stack.size()); Calendar cal = new GregorianCalendar(2008, 04, 21, 00, 45, 44); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), cal.getTimeInMillis(), Level.WARN, "Hello, World", null); assertTrue(rule.evaluate(event, null)); } /** * Test deserialized Not. */ public void test5() throws IOException, ClassNotFoundException { Stack stack = new Stack(); stack.push(LevelEqualsRule.getRule("INFO")); Rule rule = (Rule) SerializationTestHelper.serializeClone(NotRule.getRule(stack)); assertEquals(0, stack.size()); Calendar cal = new GregorianCalendar(2008, 04, 21, 00, 45, 44); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), cal.getTimeInMillis(), Level.INFO, "Hello, World", null); assertFalse(rule.evaluate(event, null)); } /** * Test deserialized Not. */ public void test6() throws IOException, ClassNotFoundException { Stack stack = new Stack(); stack.push(LevelEqualsRule.getRule("INFO")); Rule rule = (Rule) SerializationTestHelper.serializeClone(NotRule.getRule(stack)); assertEquals(0, stack.size()); Calendar cal = new GregorianCalendar(2008, 04, 21, 00, 45, 44); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), cal.getTimeInMillis(), Level.WARN, "Hello, World", null); assertTrue(rule.evaluate(event, null)); } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/rule/OrRuleTest.java000066400000000000000000000142121252742764200272000ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rule; import junit.framework.TestCase; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.util.SerializationTestHelper; import java.io.IOException; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Stack; /** * Test for OrRule. */ public class OrRuleTest extends TestCase { /** * Create new test. * * @param testName test name. */ public OrRuleTest(final String testName) { super(testName); } /** * OrRule.getRule(Stack) throws exception if only one rule provided. */ public void test1() { Stack stack = new Stack(); stack.push(LevelEqualsRule.getRule("INFO")); try { OrRule.getRule(stack); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException ex) { } } /** * OrRule.getRule(Stack) throws exception if non-rules are provided. */ public void test2() { Stack stack = new Stack(); stack.push("Hello"); stack.push("World"); try { OrRule.getRule(stack); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException ex) { } } /** * Test Or of Level and Time. */ public void test3() { Stack stack = new Stack(); stack.push(LevelEqualsRule.getRule("INFO")); stack.push(TimestampInequalityRule.getRule(">=", "2008/05/21 00:44:45")); Rule rule = OrRule.getRule(stack); assertEquals(0, stack.size()); Calendar cal = new GregorianCalendar(2008, 04, 21, 00, 45, 44); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), cal.getTimeInMillis(), Level.INFO, "Hello, World", null); assertTrue(rule.evaluate(event, null)); } /** * Test Or of Level and Time when Level does not match. */ public void test4() { Stack stack = new Stack(); stack.push(LevelEqualsRule.getRule("INFO")); stack.push(TimestampInequalityRule.getRule(">=", "2008/05/21 00:44:45")); Rule rule = OrRule.getRule(stack); assertEquals(0, stack.size()); Calendar cal = new GregorianCalendar(2008, 04, 21, 00, 45, 44); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), cal.getTimeInMillis(), Level.WARN, "Hello, World", null); assertTrue(rule.evaluate(event, null)); } /** * Test Or of Level and Time when Time does not match. */ public void test5() { Stack stack = new Stack(); stack.push(LevelEqualsRule.getRule("INFO")); stack.push(TimestampInequalityRule.getRule(">=", "2009/05/21 00:44:45")); Rule rule = OrRule.getRule(stack); assertEquals(0, stack.size()); Calendar cal = new GregorianCalendar(2008, 04, 21, 00, 45, 44); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), cal.getTimeInMillis(), Level.INFO, "Hello, World", null); assertTrue(rule.evaluate(event, null)); } /** * Test Or of Level and Time when Time and Level do not match. */ public void test6() { Stack stack = new Stack(); stack.push(LevelEqualsRule.getRule("INFO")); stack.push(TimestampInequalityRule.getRule(">=", "2009/05/21 00:44:45")); Rule rule = OrRule.getRule(stack); assertEquals(0, stack.size()); Calendar cal = new GregorianCalendar(2008, 04, 21, 00, 45, 44); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), cal.getTimeInMillis(), Level.WARN, "Hello, World", null); assertFalse(rule.evaluate(event, null)); } /** * Test deserialized Or. */ public void test7() throws IOException, ClassNotFoundException { Stack stack = new Stack(); stack.push(LevelEqualsRule.getRule("INFO")); stack.push(TimestampInequalityRule.getRule(">=", "2008/05/21 00:44:45")); Rule rule = (Rule) SerializationTestHelper.serializeClone(OrRule.getRule(stack)); assertEquals(0, stack.size()); Calendar cal = new GregorianCalendar(2008, 04, 21, 00, 45, 44); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), cal.getTimeInMillis(), Level.INFO, "Hello, World", null); assertTrue(rule.evaluate(event, null)); } /** * Test deserialized Or when neither rule match. */ public void test8() throws IOException, ClassNotFoundException { Stack stack = new Stack(); stack.push(LevelEqualsRule.getRule("INFO")); stack.push(TimestampInequalityRule.getRule(">=", "2009/05/21 00:44:45")); Rule rule = (Rule) SerializationTestHelper.serializeClone(OrRule.getRule(stack)); assertEquals(0, stack.size()); Calendar cal = new GregorianCalendar(2008, 04, 21, 00, 45, 44); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), cal.getTimeInMillis(), Level.WARN, "Hello, World", null); assertFalse(rule.evaluate(event, null)); } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/rule/PartialTextMatchRuleTest.java000066400000000000000000000103461252742764200320420ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rule; import junit.framework.TestCase; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.util.SerializationTestHelper; import java.io.IOException; import java.util.Stack; /** * Test for PartialTextMatchRule. */ public class PartialTextMatchRuleTest extends TestCase { /** * Create new test. * * @param testName test name. */ public PartialTextMatchRuleTest(final String testName) { super(testName); } /** * getRule() with only one entry on stack should throw IllegalArgumentException. */ public void test1() { Stack stack = new Stack(); stack.push("Hello"); try { PartialTextMatchRule.getRule(stack); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException ex) { } } /** * getRule() with bad field name should throw IllegalArgumentException. */ public void test2() { Stack stack = new Stack(); stack.push("Hello"); stack.push("World"); try { PartialTextMatchRule.getRule(stack); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException ex) { } } /** * getRule with "level" and "nfo" should return a LevelEqualsRule. */ public void test3() { Stack stack = new Stack(); stack.push("level"); stack.push("nfo"); Rule rule = PartialTextMatchRule.getRule(stack); assertEquals(0, stack.size()); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), System.currentTimeMillis(), Level.INFO, "Hello, World", null); assertTrue(rule.evaluate(event, null)); } /** * getRule with "msg". */ public void test4() { Stack stack = new Stack(); stack.push("msg"); stack.push("World"); Rule rule = PartialTextMatchRule.getRule(stack); assertEquals(0, stack.size()); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), System.currentTimeMillis(), Level.INFO, "Hello, World", null); assertTrue(rule.evaluate(event, null)); } /** * getRule with "msg". */ public void test5() { Stack stack = new Stack(); stack.push("msg"); stack.push("Bonjour, Monde"); Rule rule = PartialTextMatchRule.getRule(stack); assertEquals(0, stack.size()); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), System.currentTimeMillis(), Level.INFO, "Hello, World", null); assertFalse(rule.evaluate(event, null)); } /** * Check PartailTextMatchRule serialization. */ public void test6() throws IOException, ClassNotFoundException { Stack stack = new Stack(); stack.push("msg"); stack.push("World"); Rule rule = (Rule) SerializationTestHelper.serializeClone(PartialTextMatchRule.getRule(stack)); assertEquals(0, stack.size()); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), System.currentTimeMillis(), Level.INFO, "Hello, World", null); assertTrue(rule.evaluate(event, null)); } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/rule/TimestampEqualsRuleTest.java000066400000000000000000000076251252742764200317500ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rule; import junit.framework.TestCase; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.util.SerializationTestHelper; import java.io.IOException; import java.util.Calendar; import java.util.GregorianCalendar; /** * Test for TimestampEqualsRule. */ public class TimestampEqualsRuleTest extends TestCase { /** * Create new test. * * @param testName test name. */ public TimestampEqualsRuleTest(final String testName) { super(testName); } /** * Tests evaluate when timestamps are equal. */ public void test1() { TimestampEqualsRule rule = (TimestampEqualsRule) TimestampEqualsRule.getRule("2008/05/21 00:45:44"); Calendar cal = new GregorianCalendar(2008,04,21,00,45,44); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), cal.getTimeInMillis(), Level.INFO, "Hello, World", null); assertTrue(rule.evaluate(event, null)); } /** * Tests evaluate when levels are not equal. */ public void test2() { TimestampEqualsRule rule = (TimestampEqualsRule) TimestampEqualsRule.getRule("2008/05/21 00:45:44"); Calendar cal = new GregorianCalendar(2008,04,21,00,46,44); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), cal.getTimeInMillis(), Level.WARN, "Hello, World", null); assertFalse(rule.evaluate(event, null)); } /** * Tests evaluate of a deserialized clone when timestamps are equal. */ public void test3() throws IOException, ClassNotFoundException { TimestampEqualsRule rule = (TimestampEqualsRule) SerializationTestHelper.serializeClone(TimestampEqualsRule.getRule("2008/05/21 00:45:44")); Calendar cal = new GregorianCalendar(2008,04,21,00,45,44); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), cal.getTimeInMillis(), Level.INFO, "Hello, World", null); assertTrue(rule.evaluate(event, null)); } /** * Tests evaluate of a deserialized clone when timestamps are not equal. */ public void test4() throws IOException, ClassNotFoundException { TimestampEqualsRule rule = (TimestampEqualsRule) SerializationTestHelper.serializeClone(TimestampEqualsRule.getRule("2008/05/21 00:45:44")); Calendar cal = new GregorianCalendar(2008,04,21,00,46,44); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), cal.getTimeInMillis(), Level.INFO, "Hello, World", null); assertFalse(rule.evaluate(event, null)); } /** * Tests constructor will badly formed time specification. */ public void test5() { try { TimestampEqualsRule.getRule("2008/May/21"); fail("IllegalArgumentException expected to be thrown"); } catch(IllegalArgumentException ex) { } } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/rule/TimestampInequalityRuleTest.java000066400000000000000000000062201252742764200326300ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.rule; import junit.framework.TestCase; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.util.SerializationTestHelper; import java.io.IOException; import java.util.Calendar; import java.util.GregorianCalendar; /** * Test for TimestampInequalityRule. */ public class TimestampInequalityRuleTest extends TestCase { /** * Create new test. * * @param testName test name. */ public TimestampInequalityRuleTest(final String testName) { super(testName); } /** * Test construction when timestamp is unrecognized. */ public void test1() { try { TimestampInequalityRule.getRule(">", "now"); fail("Expected IllegalArgumentException"); } catch(IllegalArgumentException ex) { } } /** * Tests construction when operator is unrecognized. */ public void test2() { // // unlike LevelInequalityRule, does not throw exception. Resulting rule never satisified. // TimestampInequalityRule.getRule("~", "2008/05/21 00:45:46"); } /** * Tests evaluate of a deserialized clone when rule is satisified. */ public void test3() throws IOException, ClassNotFoundException { Rule rule = (Rule) SerializationTestHelper.serializeClone(TimestampInequalityRule.getRule(">=", "2008/05/21 00:44:45")); Calendar cal = new GregorianCalendar(2008,04,21,00,45,44); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), cal.getTimeInMillis(), Level.INFO, "Hello, World", null); assertTrue(rule.evaluate(event, null)); } /** * Tests evaluate of a deserialized clone when rule is not satisfied. */ public void test4() throws IOException, ClassNotFoundException { Rule rule = (Rule) SerializationTestHelper.serializeClone(TimestampInequalityRule.getRule("<", "2008/05/21 00:44:44")); Calendar cal = new GregorianCalendar(2008,04,21,00,45,44); LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", Logger.getRootLogger(), cal.getTimeInMillis(), Level.WARN, "Hello, World", null); assertFalse(rule.evaluate(event, null)); } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/util/000077500000000000000000000000001252742764200242735ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/util/AbsoluteDateAndTimeFilter.java000066400000000000000000000023351252742764200321250ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.util; import java.util.regex.Pattern; public class AbsoluteDateAndTimeFilter implements Filter { private final Pattern pattern; public AbsoluteDateAndTimeFilter() { pattern = Pattern.compile(Filter.ABSOLUTE_DATE_AND_TIME_PAT); } public String filter(String in) { if (pattern.matcher(in).find()) { return pattern.matcher(in).replaceAll(""); } else { return in; } } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/util/AbsoluteTimeFilter.java000066400000000000000000000023161252742764200307030ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.util; import java.util.regex.Matcher; import java.util.regex.Pattern; public class AbsoluteTimeFilter implements Filter { public String filter(String in) { String pat = Filter.ABSOLUTE_TIME_PAT; Pattern pattern = Pattern.compile(pat); Matcher matcher = pattern.matcher(in); if (matcher.find()) { return matcher.replaceAll(""); } else { return in; } } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/util/Compare.java000066400000000000000000000140151252742764200265250ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.util; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.zip.GZIPInputStream; public class Compare { static final int B1_NULL = -1; static final int B2_NULL = -2; private static final InputStream open( final Class testClass, final String fileName) throws IOException { String resourceName = fileName; if (fileName.startsWith("witness/")) { resourceName = fileName.substring(fileName.lastIndexOf('/') + 1); } InputStream is = testClass.getResourceAsStream(resourceName); if (is == null) { File file = new File(fileName); if (file.exists()) { is = new FileInputStream(file); } else { throw new FileNotFoundException("Resource " + resourceName + " not found"); } } return is; } public static boolean compare(Class testClass, final String file1, final String file2) throws IOException { BufferedReader in1 = new BufferedReader(new FileReader(file1)); BufferedReader in2 = new BufferedReader(new InputStreamReader( open(testClass, file2))); try { return compare(testClass, file1, file2, in1, in2); } finally { in1.close(); in2.close(); } } public static boolean compare( Class testClass, String file1, String file2, BufferedReader in1, BufferedReader in2) throws IOException { String s1; int lineCounter = 0; while ((s1 = in1.readLine()) != null) { lineCounter++; String s2 = in2.readLine(); if (!s1.equals(s2)) { System.out.println( "Files [" + file1 + "] and [" + file2 + "] differ on line " + lineCounter); System.out.println("One reads: [" + s1 + "]."); System.out.println("Other reads:[" + s2 + "]."); outputFile(testClass, file1); outputFile(testClass, file2); return false; } } // the second file is longer if (in2.read() != -1) { System.out.println( "File [" + file2 + "] longer than file [" + file1 + "]."); outputFile(testClass, file1); outputFile(testClass, file2); return false; } return true; } /** * * Prints file on the console. * */ private static void outputFile(Class testClass, String file) throws IOException { InputStream is = open(testClass, file); BufferedReader in1 = new BufferedReader(new InputStreamReader(is)); String s1; int lineCounter = 0; System.out.println("--------------------------------"); System.out.println("Contents of " + file + ":"); while ((s1 = in1.readLine()) != null) { lineCounter++; System.out.print(lineCounter); if (lineCounter < 10) { System.out.print(" : "); } else if (lineCounter < 100) { System.out.print(" : "); } else if (lineCounter < 1000) { System.out.print(" : "); } else { System.out.print(": "); } System.out.println(s1); } in1.close(); } public static boolean gzCompare(final Class testClass, final String actual, final String expected) throws FileNotFoundException, IOException { String resourceName = expected; int lastSlash = expected.lastIndexOf("/"); if (lastSlash >= 0) { resourceName = expected.substring(lastSlash + 1); } InputStream resourceStream = testClass.getResourceAsStream(resourceName); if (resourceStream == null) { throw new FileNotFoundException("Could not locate resource " + resourceName); } BufferedReader in1 = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(actual)))); BufferedReader in2 = new BufferedReader(new InputStreamReader(new GZIPInputStream(resourceStream))); try { return gzCompare(testClass, actual, expected, in1, in2); } finally { in1.close(); in2.close(); } } public static boolean gzCompare(Class testClass, String file1, String file2, BufferedReader in1, BufferedReader in2) throws IOException { String s1; int lineCounter = 0; while ((s1 = in1.readLine()) != null) { lineCounter++; String s2 = in2.readLine(); if (!s1.equals(s2)) { System.out.println( "Files [" + file1 + "] and [" + file2 + "] differ on line " + lineCounter); System.out.println("One reads: [" + s1 + "]."); System.out.println("Other reads:[" + s2 + "]."); outputFile(testClass, file1); outputFile(testClass, file2); return false; } } // the second file is longer if (in2.read() != -1) { System.out.println( "File [" + file2 + "] longer than file [" + file1 + "]."); outputFile(testClass, file1); outputFile(testClass, file2); return false; } return true; } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/util/ControlFilter.java000066400000000000000000000025171252742764200277310ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.util; import java.util.regex.Pattern; public class ControlFilter implements Filter { String[] allowedPatterns; public ControlFilter(String[] allowedPatterns) { this.allowedPatterns = allowedPatterns; } public String filter(String in) throws UnexpectedFormatException { int len = allowedPatterns.length; for (int i = 0; i < len; i++) { if (Pattern.compile(allowedPatterns[i]).matcher(in).find()) { return in; } } throw new UnexpectedFormatException("[" + in + "]"); } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/util/Filter.java000066400000000000000000000031001252742764200263550ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.util; public interface Filter { // 06 avr. 2002 18:36:32,036 // 18 fevr. 2002 20:05:36,222 public static final String ABSOLUTE_DATE_AND_TIME_PAT = "^\\d{1,2} .{2,6}\\.? 2\\d\\d\\d \\d{2}:\\d{2}:\\d{2},\\d{3}"; // 18:54:19,201 public static final String ABSOLUTE_TIME_PAT = "^\\d{2}:\\d{2}:\\d{2},\\d{3}"; public static final String RELATIVE_TIME_PAT = "^\\d{1,10}"; final String BASIC_PAT = "\\[main\\] (FATAL|ERROR|WARN|INFO|DEBUG)"; final String ISO8601_PAT = "^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3}"; /** * This filter transforms the input string and returns the results as * output. If the input should be ignored, this method returns null. * */ String filter(String in) throws UnexpectedFormatException; } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/util/ISO8601Filter.java000066400000000000000000000022461252742764200272610ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.util; import java.util.regex.*; public class ISO8601Filter implements Filter { private final Pattern pattern; public ISO8601Filter() { pattern = Pattern.compile(ISO8601_PAT); } public String filter(String in) { if (pattern.matcher(in).find()) { return pattern.matcher(in).replaceAll(""); } else { return in; } } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/util/JunitTestRunnerFilter.java000066400000000000000000000042111252742764200314250ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.util; import java.util.regex.Pattern; public class JunitTestRunnerFilter implements Filter { private static final String[] PATTERNS = { "at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner", "at org.apache.tools.ant", "at junit.textui.TestRunner", "at com.intellij", "at java.lang.reflect.Method.invoke", "at org.apache.maven.", "at org.codehaus.", "at org.junit.internal.runners.", "at junit.framework.TestSuite", "at junit.framework.TestResult" }; private final Pattern[] patterns; public JunitTestRunnerFilter() { patterns = new Pattern[PATTERNS.length]; for (int i = 0; i < PATTERNS.length; i++) { patterns[i] = Pattern.compile(PATTERNS[i]); } } /** * Filter out stack trace lines coming from the various JUnit TestRunners. */ public String filter(String in) { if (in == null) { return null; } // // restore the one instance of Method.invoke that we actually want // if (in.indexOf("at junit.framework.TestCase.runTest") != -1) { return "\tat java.lang.reflect.Method.invoke(X)\n" + in; } for (int i = 0; i < patterns.length; i++) { if(patterns[i].matcher(in).find()) { return null; } } return in; } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/util/LineNumberFilter.java000066400000000000000000000026361252742764200303530ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.util; import java.util.regex.Pattern; public class LineNumberFilter implements Filter { private Pattern linePattern; private Pattern nativePattern; public LineNumberFilter() { linePattern = Pattern.compile("\\(.*:\\d{1,4}\\)"); nativePattern = Pattern.compile("\\(Native Method\\)"); } public String filter(final String in) { if (linePattern.matcher(in).find()) { return linePattern.matcher(in).replaceAll("(X)"); } else if (nativePattern.matcher(in).find()) { return nativePattern.matcher(in).replaceAll("(X)"); } else { return in; } } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/util/MDCOrderFilter.java000066400000000000000000000036531252742764200277120ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.util; /** * This class switches MDC values into the order * (unreasonably) expected by the witness files. */ public class MDCOrderFilter implements Filter { /** * Unexpected orders of keys. * Note expected values are "va-one-one" and "va-one-two". */ private static final String[] patterns = new String[] { "{key2,va12}{key1,va11}", "{key2,value2}{key1,value1}" }; /** * Replacement values. */ private static final String[] replacements = new String[] { "{key1,va11}{key2,va12}", "{key1,value1}{key2,value2}" }; /** * Switch order of MDC keys when not in expected order. */ public String filter(final String in) { if (in == null) { return null; } for(int i = 0; i < patterns.length; i++) { int ipos = in.indexOf(patterns[i]); if (ipos >= 1) { return in.substring(0, ipos) + replacements[i] + in.substring(ipos + patterns[i].length()); } } return in; } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/util/RelativeTimeFilter.java000066400000000000000000000023451252742764200307020ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.util; import java.util.regex.Pattern; public class RelativeTimeFilter implements Filter { private final Pattern relativePattern; public RelativeTimeFilter() { relativePattern = Pattern.compile(Filter.RELATIVE_TIME_PAT); } public String filter(String in) { if (relativePattern.matcher(in).find()) { return relativePattern.matcher(in).replaceAll(""); } else { return in; } } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/util/SerializationTestHelper.java000066400000000000000000000114601252742764200317550ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.util; import junit.framework.TestCase; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; /** * Utiities for serialization tests. * * @author Curt Arnold */ public class SerializationTestHelper { /** * Private constructor. */ private SerializationTestHelper() { } /** * Creates a clone by serializing object and * deserializing byte stream. * @param obj object to serialize and deserialize. * @return clone * @throws IOException on IO error. * @throws ClassNotFoundException if class not found. */ public static Object serializeClone(final Object obj) throws IOException, ClassNotFoundException { ByteArrayOutputStream memOut = new ByteArrayOutputStream(); ObjectOutputStream objOut = new ObjectOutputStream(memOut); objOut.writeObject(obj); objOut.close(); ByteArrayInputStream src = new ByteArrayInputStream(memOut.toByteArray()); ObjectInputStream objIs = new ObjectInputStream(src); return objIs.readObject(); } /** * Deserializes a specified file. * @param witness serialization file, may not be null. * @return deserialized object. * @throws Exception thrown on IO or deserialization exception. */ public static Object deserializeStream(final String witness) throws Exception { FileInputStream fileIs = new FileInputStream(witness); ObjectInputStream objIs = new ObjectInputStream(fileIs); return objIs.readObject(); } /** * Checks the serialization of an object against an file * containing the expected serialization. * * @param witness name of file containing expected serialization. * @param obj object to be serialized. * @param skip positions in serialized stream that should not be compared. * @param endCompare position to stop comparison. * @throws Exception thrown on IO or serialization exception. */ public static void assertSerializationEquals( final String witness, final Object obj, final int[] skip, final int endCompare) throws Exception { ByteArrayOutputStream memOut = new ByteArrayOutputStream(); ObjectOutputStream objOut = new ObjectOutputStream(memOut); objOut.writeObject(obj); objOut.close(); assertStreamEquals(witness, memOut.toByteArray(), skip, endCompare); } /** * Asserts the serialized form of an object. * @param witness file name of expected serialization. * @param actual byte array of actual serialization. * @param skip positions to skip comparison. * @param endCompare position to stop comparison. * @throws IOException thrown on IO or serialization exception. */ public static void assertStreamEquals( final String witness, final byte[] actual, final int[] skip, final int endCompare) throws IOException { File witnessFile = new File(witness); if (witnessFile.exists()) { int skipIndex = 0; byte[] expected = new byte[actual.length]; FileInputStream is = new FileInputStream(witnessFile); int bytesRead = is.read(expected); is.close(); if(bytesRead < endCompare) { TestCase.assertEquals(bytesRead, actual.length); } int endScan = actual.length; if (endScan > endCompare) { endScan = endCompare; } for (int i = 0; i < endScan; i++) { if ((skipIndex < skip.length) && (skip[skipIndex] == i)) { skipIndex++; } else { if (expected[i] != actual[i]) { TestCase.assertEquals( "Difference at offset " + i, expected[i], actual[i]); } } } } else { // // if the file doesn't exist then // assume that we are setting up and need to write it FileOutputStream os = new FileOutputStream(witnessFile); os.write(actual); os.close(); TestCase.fail("Writing witness file " + witness); } } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/util/SunReflectFilter.java000066400000000000000000000022201252742764200303520ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.util; /** * The sun.reflect.* lines are not present in all JDKs. * * @author Ceki Gulcu */ public class SunReflectFilter implements Filter { public String filter(String in) { if(in == null) { return null; } if (in.indexOf("at sun.reflect") != -1) { return null; } else { return in; } } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/util/Transformer.java000066400000000000000000000050231252742764200274400ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.util; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; public class Transformer { public static void transform(String in, String out, Filter[] filters) throws FileNotFoundException, IOException, UnexpectedFormatException { String line; BufferedReader input = new BufferedReader(new FileReader(in)); PrintStream output = new PrintStream(new FileOutputStream(out, false)); try { // Initialization of input and output omitted while ((line = input.readLine()) != null) { // apply all filters for (int i = 0; i < filters.length; i++) { line = filters[i].filter(line); } if (line != null) { output.println(line); } } } finally { input.close(); output.close(); } } public static void transform(String in, String out, Filter filter) throws FileNotFoundException, IOException, UnexpectedFormatException { String line; BufferedReader input = new BufferedReader(new FileReader(in)); PrintStream output = new PrintStream(new FileOutputStream(out)); try { // Initialization of input and output omitted while((line = input.readLine()) != null) { line = filter.filter(line); output.println(line); } } finally { input.close(); output.close(); } } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/util/UnexpectedFormatException.java000066400000000000000000000017111252742764200322720ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.util; public class UnexpectedFormatException extends Exception { public UnexpectedFormatException(String msg) { super(msg); } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/util/XMLDateFilter.java000066400000000000000000000025231252742764200275440ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.util; import java.util.regex.Pattern; public class XMLDateFilter implements Filter { private final static String PATTERN = "\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}.\\d{3}"; private final Pattern pattern; public XMLDateFilter() { pattern = Pattern.compile(PATTERN); } public String filter(final String in) { if (in != null && pattern.matcher(in).find()) { return pattern.matcher(in).replaceAll("yyyy-MM-ddTHH:mm:ss.SSS"); } else { return in; } } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/util/XMLLineAttributeFilter.java000066400000000000000000000025041252742764200314410ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.util; import java.util.regex.Pattern; public class XMLLineAttributeFilter implements Filter { public String filter(final String in) { if(in == null) { return null; } if (Pattern.compile("line=\"\\d{1,3}\"").matcher(in).find()) { return Pattern.compile("line=\"\\d{1,3}\"").matcher(in).replaceAll("line=\"X\""); } else if (Pattern.compile("line=\"?\"").matcher(in).find()) { return Pattern.compile("line=\"?\"").matcher(in).replaceAll("line=\"X\""); } return in; } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/util/XMLTimestampFilter.java000066400000000000000000000023711252742764200306330ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.util; import java.util.regex.Matcher; import java.util.regex.Pattern; public class XMLTimestampFilter implements Filter { public String filter(String in) { if(in == null) { return null; } Pattern pattern = Pattern.compile("timestamp=\"\\d{10,13}\""); Matcher matcher = pattern.matcher(in); if (matcher.find()) { return matcher.replaceAll("timestamp=\"XXX\""); } else { return in; } } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/xml/000077500000000000000000000000001252742764200241165ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/xml/XSLTLayoutTest.java000066400000000000000000000336711252742764200276230ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.xml; import org.apache.log4j.Layout; import org.apache.log4j.LayoutTest; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.NDC; import org.apache.log4j.MDC; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.util.Transformer; import org.apache.log4j.util.Filter; import org.apache.log4j.util.LineNumberFilter; import org.apache.log4j.util.JunitTestRunnerFilter; import org.apache.log4j.util.XMLTimestampFilter; import org.apache.log4j.util.Compare; import org.apache.log4j.util.XMLDateFilter; import org.apache.log4j.helpers.MDCKeySetExtractor; import org.apache.log4j.spi.LoggingEvent; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import java.io.Reader; import java.io.StringReader; import java.io.InputStream; import java.io.FileNotFoundException; import java.util.Set; import java.util.Iterator; import java.util.Properties; import java.util.Hashtable; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; /** * Test for XSLTLayout. * */ public class XSLTLayoutTest extends LayoutTest { /** * Construct new instance of XSLTLayoutTest. * * @param testName test name. */ public XSLTLayoutTest(final String testName) { super(testName, "text/plain", false, null, null); } /** * @{inheritDoc} */ protected Layout createLayout() { return new XSLTLayout(); } /** * Parses the string as the body of an XML document and returns the document element. * @param source source string. * @return document element. * @throws Exception if parser can not be constructed or source is not a valid XML document. */ private Element parse(final String source) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(false); factory.setCoalescing(true); DocumentBuilder builder = factory.newDocumentBuilder(); Reader reader = new StringReader(source); Document doc = builder.parse(new InputSource(reader)); return doc.getDocumentElement(); } /** * Checks a log4j:event element against expectations. * @param element element, may not be null. * @param event event, may not be null. */ private void checkEventElement( final Element element, final LoggingEvent event) { assertEquals("log4j:event", element.getTagName()); assertEquals( "org.apache.log4j.xml.XSLTLayoutTest", element.getAttribute("logger")); assertEquals( Long.toString(event.timeStamp), element.getAttribute("timestamp")); assertEquals("INFO", element.getAttribute("level")); assertEquals(event.getThreadName(), element.getAttribute("thread")); } /** * Checks a log4j:message element against expectations. * @param element element, may not be null. * @param message expected message. */ private void checkMessageElement( final Element element, final String message) { assertEquals("log4j:message", element.getTagName()); Node messageNode = element.getFirstChild(); assertNotNull(messageNode); assertEquals(Node.TEXT_NODE, messageNode.getNodeType()); assertEquals(message, messageNode.getNodeValue()); assertNull(messageNode.getNextSibling()); } /** * Checks a log4j:message element against expectations. * @param element element, may not be null. * @param message expected message. */ private void checkNDCElement(final Element element, final String message) { assertEquals("log4j:NDC", element.getTagName()); Node messageNode = element.getFirstChild(); assertNotNull(messageNode); assertEquals(Node.TEXT_NODE, messageNode.getNodeType()); assertEquals(message, messageNode.getNodeValue()); assertNull(messageNode.getNextSibling()); } /** * Checks a log4j:throwable element against expectations. * @param element element, may not be null. * @param ex exception, may not be null. */ private void checkThrowableElement( final Element element, final Exception ex) { assertEquals("log4j:throwable", element.getTagName()); Node messageNode = element.getFirstChild(); assertNotNull(messageNode); assertEquals(Node.TEXT_NODE, messageNode.getNodeType()); String msg = ex.toString(); assertEquals("Got " + messageNode.getNodeValue(), msg, messageNode.getNodeValue().substring(0, msg.length())); assertNull(messageNode.getNextSibling()); } /** * Tests formatted results. * @throws Exception if parser can not be constructed or source is not a valid XML document. */ public void testFormat() throws Exception { clearMDC(); NDC.clear(); Logger logger = Logger.getLogger("org.apache.log4j.xml.XSLTLayoutTest"); LoggingEvent event = new LoggingEvent( "org.apache.log4j.Logger", logger, Level.INFO, "Hello, World", null); XSLTLayout layout = (XSLTLayout) createLayout(); String result = layout.format(event); Element parsedResult = parse(result); checkEventElement(parsedResult, event); int childElementCount = 0; for ( Node node = parsedResult.getFirstChild(); node != null; node = node.getNextSibling()) { switch (node.getNodeType()) { case Node.ELEMENT_NODE: childElementCount++; checkMessageElement((Element) node, "Hello, World"); break; case Node.COMMENT_NODE: break; case Node.TEXT_NODE: // should only be whitespace break; default: fail("Unexpected node type"); break; } } assertEquals(1, childElementCount); } /** * Tests formatted results with an exception. * @throws Exception if parser can not be constructed or source is not a valid XML document. */ public void testFormatWithException() throws Exception { clearMDC(); NDC.clear(); Logger logger = Logger.getLogger("org.apache.log4j.xml.XSLTLayoutTest"); Exception ex = new IllegalArgumentException("'foo' is not a valid name"); LoggingEvent event = new LoggingEvent( "org.apache.log4j.Logger", logger, Level.INFO, "Hello, World", ex); XSLTLayout layout = (XSLTLayout) createLayout(); String result = layout.format(event); Element parsedResult = parse(result); checkEventElement(parsedResult, event); int childElementCount = 0; for ( Node node = parsedResult.getFirstChild(); node != null; node = node.getNextSibling()) { switch (node.getNodeType()) { case Node.ELEMENT_NODE: childElementCount++; if (childElementCount == 1) { checkMessageElement((Element) node, "Hello, World"); } else { checkThrowableElement((Element) node, ex); } break; case Node.COMMENT_NODE: break; case Node.TEXT_NODE: // should only be whitespace break; default: fail("Unexpected node type"); break; } } assertEquals(2, childElementCount); } /** * Tests formatted results with an exception. * @throws Exception if parser can not be constructed or source is not a valid XML document. */ public void testFormatWithNDC() throws Exception { clearMDC(); NDC.clear(); Logger logger = Logger.getLogger("org.apache.log4j.xml.XSLTLayoutTest"); NDC.push("NDC goes here"); LoggingEvent event = new LoggingEvent( "org.apache.log4j.Logger", logger, Level.INFO, "Hello, World", null); XSLTLayout layout = (XSLTLayout) createLayout(); String result = layout.format(event); NDC.pop(); Element parsedResult = parse(result); checkEventElement(parsedResult, event); int childElementCount = 0; for ( Node node = parsedResult.getFirstChild(); node != null; node = node.getNextSibling()) { switch (node.getNodeType()) { case Node.ELEMENT_NODE: childElementCount++; if (childElementCount == 1) { checkMessageElement((Element) node, "Hello, World"); } else { checkNDCElement((Element) node, "NDC goes here"); } break; case Node.COMMENT_NODE: break; case Node.TEXT_NODE: // should only be whitespace break; default: fail("Unexpected node type"); break; } } assertEquals(2, childElementCount); } /** * Tests getLocationInfo and setLocationInfo. */ public void testGetSetLocationInfo() { XSLTLayout layout = new XSLTLayout(); assertEquals(false, layout.getLocationInfo()); layout.setLocationInfo(true); assertEquals(true, layout.getLocationInfo()); layout.setLocationInfo(false); assertEquals(false, layout.getLocationInfo()); } /** * Tests activateOptions(). */ public void testActivateOptions() { XSLTLayout layout = new XSLTLayout(); layout.activateOptions(); } /** * Tests XML configuration and atom layout. */ public void testAtom() throws Exception { InputStream is = XSLTLayoutTest.class.getResourceAsStream("xsltLayout4.xml"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(false); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(is); org.apache.log4j.extras.DOMConfigurator.configure( doc.getDocumentElement()); Logger logger = Logger.getLogger("org.apache.log4j.xml.XSLTLayoutTest"); logger.debug("DEBUG message"); logger.info("INFO message"); Transformer.transform( "target/temp", "target/filtered", new Filter[] { new LineNumberFilter(), new JunitTestRunnerFilter(), new XMLTimestampFilter(), new XMLDateFilter()}); assertTrue(Compare.compare(XSLTLayoutTest.class, "target/filtered", "witness/xml/xsltLayout.4")); } /** * Tests XML configuration and atom layout. */ public void testAtomNS() throws Exception { InputStream is = XSLTLayoutTest.class.getResourceAsStream("xsltLayout4.xml"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(is); org.apache.log4j.extras.DOMConfigurator.configure( doc.getDocumentElement()); Logger logger = Logger.getLogger("org.apache.log4j.xml.XSLTLayoutTest"); logger.debug("DEBUG message"); logger.info("INFO message"); Transformer.transform( "target/temp", "target/filtered", new Filter[] { new LineNumberFilter(), new JunitTestRunnerFilter(), new XMLTimestampFilter(), new XMLDateFilter()}); assertTrue(Compare.compare(XSLTLayoutTest.class, "target/filtered", "witness/xml/xsltLayout.4")); } /** * Tests CDATA element within NDC content. See bug 37560. */ public void testNDCWithCDATA() throws Exception { Logger logger = Logger.getLogger("com.example.bar"); Level level = Level.INFO; String ndcMessage =""; NDC.push(ndcMessage); LoggingEvent event = new LoggingEvent( "com.example.bar", logger, level, "Hello, World", null); Layout layout = createLayout(); String result = layout.format(event); NDC.clear(); Element parsedResult = parse(result); NodeList ndcs = parsedResult.getElementsByTagName("log4j:NDC"); assertEquals(1, ndcs.getLength()); StringBuffer buf = new StringBuffer(); for(Node child = ndcs.item(0).getFirstChild(); child != null; child = child.getNextSibling()) { buf.append(child.getNodeValue()); } assertEquals(ndcMessage, buf.toString()); } /** * Tests CDATA element within exception. See bug 37560. */ public void testExceptionWithCDATA() throws Exception { Logger logger = Logger.getLogger("com.example.bar"); Level level = Level.INFO; String exceptionMessage =""; LoggingEvent event = new LoggingEvent( "com.example.bar", logger, level, "Hello, World", new Exception(exceptionMessage)); Layout layout = createLayout(); String result = layout.format(event); Element parsedResult = parse(result); NodeList throwables = parsedResult.getElementsByTagName("log4j:throwable"); assertEquals(1, throwables.getLength()); StringBuffer buf = new StringBuffer(); for(Node child = throwables.item(0).getFirstChild(); child != null; child = child.getNextSibling()) { buf.append(child.getNodeValue()); } assertTrue(buf.toString().indexOf(exceptionMessage) != -1); } private static void clearMDC() { Hashtable context = MDC.getContext(); if (context != null) { context.clear(); } } } apache-log4j-extras1.2-1.2.17/src/test/java/org/apache/log4j/xml/XSLTLayoutTestCase.java000066400000000000000000000152721252742764200304140ustar00rootroot00000000000000/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.log4j.xml; import junit.framework.TestCase; import org.apache.log4j.FileAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.MDC; import org.apache.log4j.helpers.MDCKeySetExtractor; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.util.Compare; import org.apache.log4j.util.Filter; import org.apache.log4j.util.JunitTestRunnerFilter; import org.apache.log4j.util.LineNumberFilter; import org.apache.log4j.util.SunReflectFilter; import org.apache.log4j.util.Transformer; import org.apache.log4j.util.XMLLineAttributeFilter; import org.apache.log4j.util.XMLTimestampFilter; import org.apache.log4j.util.XMLDateFilter; import java.util.Set; import java.util.Iterator; import java.util.Hashtable; public class XSLTLayoutTestCase extends TestCase { static String TEMP = "target/temp"; static String FILTERED = "target/filtered"; Logger root; Logger logger; public XSLTLayoutTestCase(final String name) { super(name); } public void setUp() { root = Logger.getRootLogger(); logger = Logger.getLogger(XSLTLayoutTestCase.class); } public void tearDown() { root.getLoggerRepository().resetConfiguration(); } public void XXXtestBasic() throws Exception { XSLTLayout xmlLayout = new XSLTLayout(); root.addAppender(new FileAppender(xmlLayout, TEMP, false)); common(); Transformer.transform( TEMP, FILTERED, new Filter[] { new LineNumberFilter(), new JunitTestRunnerFilter(), new XMLTimestampFilter(), new SunReflectFilter(), new XMLDateFilter() }); assertTrue(Compare.compare(XSLTLayoutTestCase.class, FILTERED, "witness/xml/xsltLayout.1")); } public void testLocationInfo() throws Exception { XSLTLayout xmlLayout = new XSLTLayout(); xmlLayout.setLocationInfo(true); root.addAppender(new FileAppender(xmlLayout, "target/locationtemp", false)); common(); Transformer.transform( "target/locationtemp", "target/locationfiltered", new Filter[] { new LineNumberFilter(), new JunitTestRunnerFilter(), new XMLTimestampFilter(), new XMLLineAttributeFilter(), new SunReflectFilter(), new XMLDateFilter() }); assertTrue(Compare.compare(XSLTLayoutTestCase.class, "target/locationfiltered", "witness/xml/xsltLayout.2")); } public void testCDATA() throws Exception { XSLTLayout xmlLayout = new XSLTLayout(); xmlLayout.setLocationInfo(true); root.addAppender(new FileAppender(xmlLayout, TEMP, false)); logger.debug("Message with embedded hi]]>."); Transformer.transform( TEMP, FILTERED, new Filter[] { new LineNumberFilter(), new JunitTestRunnerFilter(), new XMLTimestampFilter(), new XMLLineAttributeFilter(), new SunReflectFilter(), new XMLDateFilter() }); assertTrue(Compare.compare(XSLTLayoutTestCase.class, FILTERED, "witness/xml/xsltLayout.3")); } public void testNull() throws Exception { XSLTLayout xmlLayout = new XSLTLayout(); root.addAppender(new FileAppender(xmlLayout, TEMP, false)); logger.debug("hi"); logger.debug(null); Exception e = new Exception((String) null); logger.debug("hi", e); Transformer.transform( TEMP, FILTERED, new Filter[] { new LineNumberFilter(), new JunitTestRunnerFilter(), new SunReflectFilter(), new XMLTimestampFilter(), new XMLDateFilter()}); assertTrue(Compare.compare(XSLTLayoutTestCase.class, FILTERED, "witness/xml/xsltLayout.null")); } /** * Tests the format of the MDC portion of the layout to ensure * the KVP's we put in turn up in the output file. * @throws Exception */ public void testMDC() throws Exception { XSLTLayout xmlLayout = new XSLTLayout(); root.addAppender(new FileAppender(xmlLayout, TEMP, false)); clearMDC(); MDC.put("key1", "val1"); MDC.put("key2", "val2"); logger.debug("Hello"); Transformer.transform( TEMP, FILTERED, new Filter[] { new LineNumberFilter(), new JunitTestRunnerFilter(), new XMLTimestampFilter(), new XMLDateFilter()}); assertTrue(Compare.compare(XSLTLayoutTestCase.class, FILTERED, "witness/xml/xsltLayout.mdc.1")); } public void testMDCEscaped() throws Exception { XSLTLayout xmlLayout = new XSLTLayout(); root.addAppender(new FileAppender(xmlLayout, TEMP, false)); clearMDC(); MDC.put("blahAttribute", ""); MDC.put("", "blahValue"); logger.debug("Hello"); Transformer.transform( TEMP, FILTERED, new Filter[] { new LineNumberFilter(), new JunitTestRunnerFilter(), new XMLTimestampFilter(), new XMLDateFilter()}); assertTrue(Compare.compare(XSLTLayoutTestCase.class, FILTERED, "witness/xml/xsltLayout.mdc.2")); } void common() { int i = -1; X x = new X(); logger.debug("Message " + ++i); root.debug("Message " + i); logger.info("Message " + ++i); root.info("Message " + i); logger.warn("Message " + ++i); root.warn("Message " + i); logger.error("Message " + ++i); root.error("Message " + i); logger.log(Level.FATAL, "Message " + ++i); root.log(Level.FATAL, "Message " + i); Exception e = new Exception("Just testing"); logger.debug("Message " + ++i, e); root.debug("Message " + i, e); logger.error("Message " + ++i, e); root.error("Message " + i, e); } private static void clearMDC() throws Exception { Hashtable context = MDC.getContext(); if (context != null) { context.clear(); } } private static final class X { Logger logger = Logger.getLogger(X.class); public X() { logger.info("in X() constructor"); } } } apache-log4j-extras1.2-1.2.17/src/test/resources/000077500000000000000000000000001252742764200213605ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/resources/org/000077500000000000000000000000001252742764200221475ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/000077500000000000000000000000001252742764200233705ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/000077500000000000000000000000001252742764200244075ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/TestLogMFPatterns.properties000066400000000000000000000016651252742764200320620ustar00rootroot00000000000000# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. # Iteration0=Iteration {0} Hello1=Hello, World Malformed=Hello, {. Hello2=Hello, {0}World Hello3=Hello, {0} Hello4={1}, {0}. Hello5={1}{2} {0}. Hello6={1}{2} {0}{3} apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/TestLogSFPatterns.properties000066400000000000000000000016511252742764200320630ustar00rootroot00000000000000# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. # Iteration0=Iteration {} Hello1=Hello, World Malformed=Hello, {. Hello2=Hello, {}World Hello3=Hello, {} Hello4={}, {}. Hello5={}{} {}. Hello6={}{} {}{} apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/component/000077500000000000000000000000001252742764200264115ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/component/plugins/000077500000000000000000000000001252742764200300725ustar00rootroot00000000000000plugins.PluginTestCase.test1.txt000066400000000000000000000015651252742764200361740ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/component/pluginsINFO - test 1.1 - basic starting/stopping INFO - starting plugin1-id1 INFO - stopping plugin1-id1 using plugin object DEBUG - plugin1-id1 already shutdown INFO - test 1.2 - restarting and starting when already started INFO - restarting plugin1-id1 INFO - restarting plugin1-id1 again DEBUG - plugin1-id1 already shutdown INFO - test 1.3- stopping and stopping when already stopped INFO - stopping plugin1-id1 DEBUG - plugin1-id1 already shutdown INFO - stopping plugin1-id1 again INFO - test 1.4 - restarting then stopping by plugin name INFO - starting plugin1-id1 INFO - stopping plugin1-id1 using plugin name DEBUG - plugin1-id1 already shutdown INFO - stopping plugin1-id1 using plugin object INFO - stopping all plugins DEBUG - plugin1-id1 is inactive INFO - plugin1-id1 is inactive DEBUG - plugin2-id4 is inactive INFO - plugin2-id4 is inactive INFO - stopping all plugins again apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout.1000066400000000000000000000035161252742764200307770ustar00rootroot00000000000000DEBUG - Message 0 DEBUG - Message 0 INFO - Message 1 INFO - Message 1 WARN - Message 2 WARN - Message 2 ERROR - Message 3 ERROR - Message 3 FATAL - Message 4 FATAL - Message 4 DEBUG - Message 5 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test1(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) INFO - Message 6 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test1(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) WARN - Message 7 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test1(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) ERROR - Message 8 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test1(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) FATAL - Message 9 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test1(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout.10000066400000000000000000000054041252742764200310550ustar00rootroot00000000000000[main] DEBUG org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 0 [main] DEBUG org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 0 [main] INFO org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 1 [main] INFO org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 1 [main] WARN org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 2 [main] WARN org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 2 [main] ERROR org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 3 [main] ERROR org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 3 [main] FATAL org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 4 [main] FATAL org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 4 [main] DEBUG org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 5 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test10(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] INFO org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 6 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test10(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] WARN org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 7 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test10(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] ERROR org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 8 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test10(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] FATAL org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 9 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test10(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout.11000066400000000000000000000044061252742764200310570ustar00rootroot00000000000000DEBUG [main] log4j.EnhancedPatternLayoutTest: Message 0 DEBUG [main] root: Message 0 INFO [main] log4j.EnhancedPatternLayoutTest: Message 1 INFO [main] root: Message 1 WARN [main] log4j.EnhancedPatternLayoutTest: Message 2 WARN [main] root: Message 2 ERROR [main] log4j.EnhancedPatternLayoutTest: Message 3 ERROR [main] root: Message 3 FATAL [main] log4j.EnhancedPatternLayoutTest: Message 4 FATAL [main] root: Message 4 DEBUG [main] log4j.EnhancedPatternLayoutTest: Message 5 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test11(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) INFO [main] log4j.EnhancedPatternLayoutTest: Message 6 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test11(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) WARN [main] log4j.EnhancedPatternLayoutTest: Message 7 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test11(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) ERROR [main] log4j.EnhancedPatternLayoutTest: Message 8 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test11(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) FATAL [main] log4j.EnhancedPatternLayoutTest: Message 9 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test11(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout.12000066400000000000000000000054041252742764200310570ustar00rootroot00000000000000[main] DEBUG org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 0 [main] DEBUG org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 0 [main] INFO org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 1 [main] INFO org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 1 [main] WARN org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 2 [main] WARN org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 2 [main] ERROR org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 3 [main] ERROR org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 3 [main] FATAL org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 4 [main] FATAL org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 4 [main] DEBUG org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 5 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test12(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] INFO org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 6 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test12(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] WARN org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 7 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test12(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] ERROR org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 8 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test12(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] FATAL org.apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 9 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test12(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout.13000066400000000000000000000053101252742764200310540ustar00rootroot00000000000000[main] DEBUG apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 0 [main] DEBUG apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 0 [main] INFO apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 1 [main] INFO apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 1 [main] WARN apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 2 [main] WARN apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 2 [main] ERROR apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 3 [main] ERROR apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 3 [main] FATAL apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 4 [main] FATAL apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 4 [main] DEBUG apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 5 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test13(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] INFO apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 6 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test13(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] WARN apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 7 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test13(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] ERROR apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 8 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test13(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] FATAL apache.log4j.EnhancedPatternLayoutTestCase.common(X): Message 9 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test13(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout.14000066400000000000000000000044061252742764200310620ustar00rootroot00000000000000DEBUG [main] o.a.l.EnhancedPatternLayoutTest: Message 0 DEBUG [main] root: Message 0 INFO [main] o.a.l.EnhancedPatternLayoutTest: Message 1 INFO [main] root: Message 1 WARN [main] o.a.l.EnhancedPatternLayoutTest: Message 2 WARN [main] root: Message 2 ERROR [main] o.a.l.EnhancedPatternLayoutTest: Message 3 ERROR [main] root: Message 3 FATAL [main] o.a.l.EnhancedPatternLayoutTest: Message 4 FATAL [main] root: Message 4 DEBUG [main] o.a.l.EnhancedPatternLayoutTest: Message 5 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test14(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) INFO [main] o.a.l.EnhancedPatternLayoutTest: Message 6 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test14(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) WARN [main] o.a.l.EnhancedPatternLayoutTest: Message 7 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test14(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) ERROR [main] o.a.l.EnhancedPatternLayoutTest: Message 8 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test14(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) FATAL [main] o.a.l.EnhancedPatternLayoutTest: Message 9 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test14(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout.15000066400000000000000000000035541252742764200310660ustar00rootroot00000000000000DEBUG 1 - Message 0 DEBUG 2 - Message 0 INFO 3 - Message 1 INFO 4 - Message 1 WARN 5 - Message 2 WARN 6 - Message 2 ERROR 7 - Message 3 ERROR 8 - Message 3 FATAL 9 - Message 4 FATAL 10 - Message 4 DEBUG 11 - Message 5 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test15(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) INFO 12 - Message 6 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test15(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) WARN 13 - Message 7 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test15(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) ERROR 14 - Message 8 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test15(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) FATAL 15 - Message 9 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test15(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout.17000066400000000000000000000002301252742764200310540ustar00rootroot00000000000000IN - 012 012 012 012 012 012 IN - IN - 12345 12345 12345 12345 12345 12345 IN - 0123456789 56789 56789 01234 01234 01234 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout.2000066400000000000000000000042111252742764200307710ustar00rootroot00000000000000 [main] DEBUG atternLayoutTest - Message 0 [main] DEBUG root - Message 0 [main] INFO atternLayoutTest - Message 1 [main] INFO root - Message 1 [main] WARN atternLayoutTest - Message 2 [main] WARN root - Message 2 [main] ERROR atternLayoutTest - Message 3 [main] ERROR root - Message 3 [main] FATAL atternLayoutTest - Message 4 [main] FATAL root - Message 4 [main] DEBUG atternLayoutTest - Message 5 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test2(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] INFO atternLayoutTest - Message 6 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test2(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] WARN atternLayoutTest - Message 7 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test2(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] ERROR atternLayoutTest - Message 8 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test2(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] FATAL atternLayoutTest - Message 9 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test2(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout.3000066400000000000000000000042111252742764200307720ustar00rootroot00000000000000 [main] DEBUG atternLayoutTest - Message 0 [main] DEBUG root - Message 0 [main] INFO atternLayoutTest - Message 1 [main] INFO root - Message 1 [main] WARN atternLayoutTest - Message 2 [main] WARN root - Message 2 [main] ERROR atternLayoutTest - Message 3 [main] ERROR root - Message 3 [main] FATAL atternLayoutTest - Message 4 [main] FATAL root - Message 4 [main] DEBUG atternLayoutTest - Message 5 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test3(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] INFO atternLayoutTest - Message 6 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test3(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] WARN atternLayoutTest - Message 7 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test3(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] ERROR atternLayoutTest - Message 8 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test3(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] FATAL atternLayoutTest - Message 9 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test3(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout.4000066400000000000000000000042111252742764200307730ustar00rootroot00000000000000 [main] DEBUG atternLayoutTest - Message 0 [main] DEBUG root - Message 0 [main] INFO atternLayoutTest - Message 1 [main] INFO root - Message 1 [main] WARN atternLayoutTest - Message 2 [main] WARN root - Message 2 [main] ERROR atternLayoutTest - Message 3 [main] ERROR root - Message 3 [main] FATAL atternLayoutTest - Message 4 [main] FATAL root - Message 4 [main] DEBUG atternLayoutTest - Message 5 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test4(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] INFO atternLayoutTest - Message 6 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test4(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] WARN atternLayoutTest - Message 7 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test4(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] ERROR atternLayoutTest - Message 8 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test4(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] FATAL atternLayoutTest - Message 9 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test4(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout.5000066400000000000000000000042111252742764200307740ustar00rootroot00000000000000 [main] DEBUG atternLayoutTest - Message 0 [main] DEBUG root - Message 0 [main] INFO atternLayoutTest - Message 1 [main] INFO root - Message 1 [main] WARN atternLayoutTest - Message 2 [main] WARN root - Message 2 [main] ERROR atternLayoutTest - Message 3 [main] ERROR root - Message 3 [main] FATAL atternLayoutTest - Message 4 [main] FATAL root - Message 4 [main] DEBUG atternLayoutTest - Message 5 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test5(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] INFO atternLayoutTest - Message 6 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test5(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] WARN atternLayoutTest - Message 7 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test5(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] ERROR atternLayoutTest - Message 8 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test5(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] FATAL atternLayoutTest - Message 9 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test5(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout.6000066400000000000000000000042111252742764200307750ustar00rootroot00000000000000 [main] DEBUG atternLayoutTest - Message 0 [main] DEBUG root - Message 0 [main] INFO atternLayoutTest - Message 1 [main] INFO root - Message 1 [main] WARN atternLayoutTest - Message 2 [main] WARN root - Message 2 [main] ERROR atternLayoutTest - Message 3 [main] ERROR root - Message 3 [main] FATAL atternLayoutTest - Message 4 [main] FATAL root - Message 4 [main] DEBUG atternLayoutTest - Message 5 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test6(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] INFO atternLayoutTest - Message 6 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test6(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] WARN atternLayoutTest - Message 7 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test6(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] ERROR atternLayoutTest - Message 8 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test6(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] FATAL atternLayoutTest - Message 9 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test6(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout.7000066400000000000000000000042111252742764200307760ustar00rootroot00000000000000 [main] DEBUG atternLayoutTest - Message 0 [main] DEBUG root - Message 0 [main] INFO atternLayoutTest - Message 1 [main] INFO root - Message 1 [main] WARN atternLayoutTest - Message 2 [main] WARN root - Message 2 [main] ERROR atternLayoutTest - Message 3 [main] ERROR root - Message 3 [main] FATAL atternLayoutTest - Message 4 [main] FATAL root - Message 4 [main] DEBUG atternLayoutTest - Message 5 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test7(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] INFO atternLayoutTest - Message 6 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test7(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] WARN atternLayoutTest - Message 7 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test7(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] ERROR atternLayoutTest - Message 8 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test7(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] FATAL atternLayoutTest - Message 9 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test7(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout.8000066400000000000000000000042111252742764200307770ustar00rootroot00000000000000 [main] DEBUG atternLayoutTest - Message 0 [main] DEBUG root - Message 0 [main] INFO atternLayoutTest - Message 1 [main] INFO root - Message 1 [main] WARN atternLayoutTest - Message 2 [main] WARN root - Message 2 [main] ERROR atternLayoutTest - Message 3 [main] ERROR root - Message 3 [main] FATAL atternLayoutTest - Message 4 [main] FATAL root - Message 4 [main] DEBUG atternLayoutTest - Message 5 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test8(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] INFO atternLayoutTest - Message 6 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test8(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] WARN atternLayoutTest - Message 7 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test8(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] ERROR atternLayoutTest - Message 8 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test8(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] FATAL atternLayoutTest - Message 9 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test8(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout.9000066400000000000000000000041721252742764200310060ustar00rootroot00000000000000[main] DEBUG atternLayoutTest : Message 0 [main] DEBUG root : Message 0 [main] INFO atternLayoutTest : Message 1 [main] INFO root : Message 1 [main] WARN atternLayoutTest : Message 2 [main] WARN root : Message 2 [main] ERROR atternLayoutTest : Message 3 [main] ERROR root : Message 3 [main] FATAL atternLayoutTest : Message 4 [main] FATAL root : Message 4 [main] DEBUG atternLayoutTest : Message 5 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test9(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] INFO atternLayoutTest : Message 6 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test9(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] WARN atternLayoutTest : Message 7 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test9(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] ERROR atternLayoutTest : Message 8 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test9(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) [main] FATAL atternLayoutTest : Message 9 java.lang.Exception: Just testing at org.apache.log4j.EnhancedPatternLayoutTestCase.common(X) at org.apache.log4j.EnhancedPatternLayoutTestCase.test9(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout.mdc.1000066400000000000000000000000541252742764200315330ustar00rootroot00000000000000DEBUG - Hello World {{key1,va11}{key2,va12}}enhancedPatternLayout.mdc.1.properties000066400000000000000000000024731252742764200336560ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. log4j.rootCategory=DEBUG, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=target/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.EnhancedPatternLayout log4j.appender.testAppender.layout.ConversionPattern=%-5p - %m %X%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout.mdc.2000066400000000000000000000007431252742764200315410ustar00rootroot00000000000000starting mdc pattern test empty mdc, no key specified in pattern : {} empty mdc, key1 in pattern : empty mdc, key2 in pattern : empty mdc, key3 in pattern : empty mdc, key1, key2, and key3 in pattern : ,, filled mdc, no key specified in pattern : {{key1,value1}{key2,value2}} filled mdc, key1 in pattern : value1 filled mdc, key2 in pattern : value2 filled mdc, key3 in pattern : filled mdc, key1, key2, and key3 in pattern : value1,value2, finished mdc pattern test apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout.throwable000066400000000000000000000026671252742764200326340ustar00rootroot00000000000000starting throwable pattern test plain pattern, no exception plain pattern, with exception java.lang.Exception: Test Exception at org.apache.log4j.EnhancedPatternLayoutTestCase.testThrowable(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) %throwable, no exception %throwable, with exception java.lang.Exception: Test Exception at org.apache.log4j.EnhancedPatternLayoutTestCase.testThrowable(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) %throwable{short}, no exception %throwable{short}, with exception java.lang.Exception: Test Exception %throwable{none}, no exception %throwable{none}, with exception %throwable{0}, no exception %throwable{0}, with exception %throwable{1}, no exception %throwable{1}, with exception java.lang.Exception: Test Exception %throwable{100}, no exception %throwable{100}, with exception java.lang.Exception: Test Exception at org.apache.log4j.EnhancedPatternLayoutTestCase.testThrowable(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) %throwable{-n}, no exception %throwable{-n}, with exception java.lang.Exception: Test Exception at org.apache.log4j.EnhancedPatternLayoutTestCase.testThrowable(X) apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout1.properties000066400000000000000000000024661252742764200331170ustar00rootroot00000000000000# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. log4j.rootLogger=DEBUG, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.file=target/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.EnhancedPatternLayout log4j.appender.testAppender.layout.ConversionPattern=%-5p - %m%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout10.properties000066400000000000000000000025011252742764200331650ustar00rootroot00000000000000# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. log4j.rootCategory=DEBUG, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=target/temp log4j.appender.testAppender.Append= false log4j.appender.testAppender.layout=org.apache.log4j.EnhancedPatternLayout log4j.appender.testAppender.layout.ConversionPattern=[%t] %-5p %l: %m%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout11.properties000066400000000000000000000025011252742764200331660ustar00rootroot00000000000000# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. log4j.rootCategory=DEBUG, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=target/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.EnhancedPatternLayout log4j.appender.testAppender.layout.ConversionPattern=%-5p [%t] %c{2}: %m%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout12.properties000066400000000000000000000025101252742764200331670ustar00rootroot00000000000000# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. log4j.rootCategory=DEBUG, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=target/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.EnhancedPatternLayout log4j.appender.testAppender.layout.ConversionPattern=[%t] %-5p %C.%M(%F:%L): %m%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout13.properties000066400000000000000000000025131252742764200331730ustar00rootroot00000000000000# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. log4j.rootCategory=DEBUG, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=target/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.EnhancedPatternLayout log4j.appender.testAppender.layout.ConversionPattern=[%t] %-5p %C{3}.%M(%F:%L): %m%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout14.properties000066400000000000000000000025011252742764200331710ustar00rootroot00000000000000# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. log4j.rootCategory=DEBUG, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=target/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.EnhancedPatternLayout log4j.appender.testAppender.layout.ConversionPattern=%-5p [%t] %c{1.}: %m%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout15.properties000066400000000000000000000024751252742764200332040ustar00rootroot00000000000000# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. log4j.rootCategory=TRACE, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=target/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.EnhancedMyPatternLayout log4j.appender.testAppender.layout.ConversionPattern=%5p %-4# - %m%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout16.properties000066400000000000000000000026051252742764200332000ustar00rootroot00000000000000# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. # log4j.rootCategory=TRACE, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=target/patternLayout16.log log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.EnhancedPatternLayout log4j.appender.testAppender.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss}{GMT}Z %d{yyyy-MM-dd HH:mm:ss}{GMT-6}-0600 - %m%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout17.properties000066400000000000000000000025551252742764200332050ustar00rootroot00000000000000# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. # log4j.rootCategory=TRACE, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=target/patternLayout17.log log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.EnhancedPatternLayout log4j.appender.testAppender.layout.ConversionPattern=%!.2p - %m %4.5m %-4.5m %!4.5m %!-4.5m %-!4.5m%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout2.properties000066400000000000000000000025221252742764200331110ustar00rootroot00000000000000# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. log4j.rootCategory=DEBUG, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=target/temp log4j.appender.testAppender.Append= false log4j.appender.testAppender.layout=org.apache.log4j.EnhancedPatternLayout log4j.appender.testAppender.layout.ConversionPattern=%d{ISO8601} [%t] %-5p %.16c - %m%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout3.properties000066400000000000000000000025421252742764200331140ustar00rootroot00000000000000# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. log4j.rootCategory=DEBUG, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=target/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.EnhancedPatternLayout log4j.appender.testAppender.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] %-5p %.16c - %m%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout4.properties000066400000000000000000000025161252742764200331160ustar00rootroot00000000000000# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. log4j.rootCategory=DEBUG, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=target/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.EnhancedPatternLayout log4j.appender.testAppender.layout.ConversionPattern=%d{DATE} [%t] %-5p %.16c - %m%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout5.properties000066400000000000000000000025371252742764200331220ustar00rootroot00000000000000# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. log4j.rootCategory=DEBUG, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=target/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.EnhancedPatternLayout log4j.appender.testAppender.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss,SSS} [%t] %-5p %.16c - %m%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout6.properties000066400000000000000000000025201252742764200331130ustar00rootroot00000000000000# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. log4j.rootCategory=DEBUG, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=target/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.EnhancedPatternLayout log4j.appender.testAppender.layout.ConversionPattern=%d{ABSOLUTE} [%t] %-5p %.16c - %m%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout7.properties000066400000000000000000000025231252742764200331170ustar00rootroot00000000000000# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. log4j.rootCategory=DEBUG, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=target/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.EnhancedPatternLayout log4j.appender.testAppender.layout.ConversionPattern=%d{HH:mm:ss,SSS} [%t] %-5p %.16c - %m%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout8.properties000066400000000000000000000025051252742764200331200ustar00rootroot00000000000000# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. log4j.rootCategory=DEBUG, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=target/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.EnhancedPatternLayout log4j.appender.testAppender.layout.ConversionPattern=%r [%t] %-5p %.16c - %m%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/enhancedPatternLayout9.properties000066400000000000000000000025021252742764200331160ustar00rootroot00000000000000# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. log4j.rootCategory=DEBUG, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File=target/temp log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.EnhancedPatternLayout log4j.appender.testAppender.layout.ConversionPattern=[%t] %-5p %.16c : %m%n # Prevent internal log4j DEBUG messages from polluting the output. log4j.logger.org.apache.log4j.PropertyConfigurator=INFO log4j.logger.org.apache.log4j.config.PropertySetter=INFO log4j.logger.org.apache.log4j.FileAppender=INFO apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/filter/000077500000000000000000000000001252742764200256745ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/filter/simpleFilter.1000066400000000000000000000001101252742764200304050ustar00rootroot00000000000000INFO - Message 1 INFO - Message 1 WARN - Message 2 WARN - Message 2 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/filter/simpleFilter.11000066400000000000000000000026021252742764200304760ustar00rootroot00000000000000DEBUG - Message 0 DEBUG - Message 0 INFO - Message 1 INFO - Message 1 ERROR - Message 3 ERROR - Message 3 FATAL - Message 4 FATAL - Message 4 DEBUG - Message 5 java.lang.Exception: Just testing at org.apache.log4j.filter.SimpleFilterTest.common(X) at org.apache.log4j.filter.SimpleFilterTest.test11(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) DEBUG - Message 5 java.lang.Exception: Just testing at org.apache.log4j.filter.SimpleFilterTest.common(X) at org.apache.log4j.filter.SimpleFilterTest.test11(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) ERROR - Message 6 java.lang.Exception: Just testing at org.apache.log4j.filter.SimpleFilterTest.common(X) at org.apache.log4j.filter.SimpleFilterTest.test11(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) ERROR - Message 6 java.lang.Exception: Just testing at org.apache.log4j.filter.SimpleFilterTest.common(X) at org.apache.log4j.filter.SimpleFilterTest.test11(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/filter/simpleFilter.6000066400000000000000000000000421252742764200304160ustar00rootroot00000000000000WARN - Message 2 WARN - Message 2 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/filter/simpleFilter.7000066400000000000000000000025761252742764200304350ustar00rootroot00000000000000DEBUG - Message 0 DEBUG - Message 0 INFO - Message 1 INFO - Message 1 ERROR - Message 3 ERROR - Message 3 FATAL - Message 4 FATAL - Message 4 DEBUG - Message 5 java.lang.Exception: Just testing at org.apache.log4j.filter.SimpleFilterTest.common(X) at org.apache.log4j.filter.SimpleFilterTest.test7(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) DEBUG - Message 5 java.lang.Exception: Just testing at org.apache.log4j.filter.SimpleFilterTest.common(X) at org.apache.log4j.filter.SimpleFilterTest.test7(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) ERROR - Message 6 java.lang.Exception: Just testing at org.apache.log4j.filter.SimpleFilterTest.common(X) at org.apache.log4j.filter.SimpleFilterTest.test7(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) ERROR - Message 6 java.lang.Exception: Just testing at org.apache.log4j.filter.SimpleFilterTest.common(X) at org.apache.log4j.filter.SimpleFilterTest.test7(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/filter/simpleFilter.8000066400000000000000000000000721252742764200304230ustar00rootroot00000000000000WARN org.apache.log4j.filter.SimpleFilterTest - Message 2 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/filter/simpleFilter1.xml000066400000000000000000000043011252742764200311340ustar00rootroot00000000000000 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/filter/simpleFilter10.xml000066400000000000000000000036571252742764200312310ustar00rootroot00000000000000 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/filter/simpleFilter11.xml000066400000000000000000000036231252742764200312230ustar00rootroot00000000000000 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/filter/simpleFilter12.xml000066400000000000000000000037451252742764200312310ustar00rootroot00000000000000 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/filter/simpleFilter6.xml000066400000000000000000000037021252742764200311450ustar00rootroot00000000000000 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/filter/simpleFilter7.xml000066400000000000000000000036361252742764200311540ustar00rootroot00000000000000 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/filter/simpleFilter8.xml000066400000000000000000000042161252742764200311500ustar00rootroot00000000000000 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/filter/simpleFilter9.xml000066400000000000000000000043261252742764200311530ustar00rootroot00000000000000 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/filter/timeFilter1.log000066400000000000000000000001441252742764200305630ustar00rootroot0000000000000002:00:00 - Hello, world. 02:15:00 - Hello, world. 02:30:00 - Hello, world. 02:45:00 - Hello, world. apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/filter/timeFilter1.xml000066400000000000000000000031021252742764200305770ustar00rootroot00000000000000 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/filter/timeFilter2.log000066400000000000000000000043741252742764200305750ustar00rootroot0000000000000000:00:00 - Hello, world. 00:15:00 - Hello, world. 00:30:00 - Hello, world. 00:45:00 - Hello, world. 01:00:00 - Hello, world. 01:15:00 - Hello, world. 01:30:00 - Hello, world. 01:45:00 - Hello, world. 03:00:00 - Hello, world. 03:15:00 - Hello, world. 03:30:00 - Hello, world. 03:45:00 - Hello, world. 04:00:00 - Hello, world. 04:15:00 - Hello, world. 04:30:00 - Hello, world. 04:45:00 - Hello, world. 05:00:00 - Hello, world. 05:15:00 - Hello, world. 05:30:00 - Hello, world. 05:45:00 - Hello, world. 06:00:00 - Hello, world. 06:15:00 - Hello, world. 06:30:00 - Hello, world. 06:45:00 - Hello, world. 07:00:00 - Hello, world. 07:15:00 - Hello, world. 07:30:00 - Hello, world. 07:45:00 - Hello, world. 08:00:00 - Hello, world. 08:15:00 - Hello, world. 08:30:00 - Hello, world. 08:45:00 - Hello, world. 09:00:00 - Hello, world. 09:15:00 - Hello, world. 09:30:00 - Hello, world. 09:45:00 - Hello, world. 10:00:00 - Hello, world. 10:15:00 - Hello, world. 10:30:00 - Hello, world. 10:45:00 - Hello, world. 11:00:00 - Hello, world. 11:15:00 - Hello, world. 11:30:00 - Hello, world. 11:45:00 - Hello, world. 12:00:00 - Hello, world. 12:15:00 - Hello, world. 12:30:00 - Hello, world. 12:45:00 - Hello, world. 13:00:00 - Hello, world. 13:15:00 - Hello, world. 13:30:00 - Hello, world. 13:45:00 - Hello, world. 14:00:00 - Hello, world. 14:15:00 - Hello, world. 14:30:00 - Hello, world. 14:45:00 - Hello, world. 15:00:00 - Hello, world. 15:15:00 - Hello, world. 15:30:00 - Hello, world. 15:45:00 - Hello, world. 16:00:00 - Hello, world. 16:15:00 - Hello, world. 16:30:00 - Hello, world. 16:45:00 - Hello, world. 17:00:00 - Hello, world. 17:15:00 - Hello, world. 17:30:00 - Hello, world. 17:45:00 - Hello, world. 18:00:00 - Hello, world. 18:15:00 - Hello, world. 18:30:00 - Hello, world. 18:45:00 - Hello, world. 19:00:00 - Hello, world. 19:15:00 - Hello, world. 19:30:00 - Hello, world. 19:45:00 - Hello, world. 20:00:00 - Hello, world. 20:15:00 - Hello, world. 20:30:00 - Hello, world. 20:45:00 - Hello, world. 21:00:00 - Hello, world. 21:15:00 - Hello, world. 21:30:00 - Hello, world. 21:45:00 - Hello, world. 22:00:00 - Hello, world. 22:15:00 - Hello, world. 22:30:00 - Hello, world. 22:45:00 - Hello, world. 23:00:00 - Hello, world. 23:15:00 - Hello, world. 23:30:00 - Hello, world. 23:45:00 - Hello, world. apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/filter/timeFilter2.xml000066400000000000000000000030741252742764200306100ustar00rootroot00000000000000 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/receivers/000077500000000000000000000000001252742764200263765ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/receivers/db/000077500000000000000000000000001252742764200267635ustar00rootroot00000000000000append-with-drivermanager1.xml000066400000000000000000000036461252742764200345640ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/receivers/db read-with-drivermanager1.xml000066400000000000000000000042001252742764200342130ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/receivers/db apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/receivers/rewrite/000077500000000000000000000000001252742764200300575ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/receivers/rewrite/map.log000066400000000000000000000004311252742764200313350ustar00rootroot00000000000000INFO org.apache.log4j.receivers.rewrite.RewriteAppenderTest - p1: p2: Message 0 INFO org.apache.log4j.receivers.rewrite.RewriteAppenderTest - p1:Hello p2:World {p1=Hello, p2=World, x1=Mundo} INFO org.apache.log4j.receivers.rewrite.RewriteAppenderTest - p1:Hello p2:World Message 1 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/receivers/rewrite/map.xml000066400000000000000000000027311252742764200313610ustar00rootroot00000000000000 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/receivers/rewrite/property.log000066400000000000000000000002631252742764200324470ustar00rootroot00000000000000INFO org.apache.log4j.receivers.rewrite.RewriteAppenderTest - p1:Hello p2:World Message 0 INFO org.apache.log4j.receivers.rewrite.RewriteAppenderTest - p1:Hola p2:World Message 1 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/receivers/rewrite/property.xml000066400000000000000000000030751252742764200324720ustar00rootroot00000000000000 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/receivers/rewrite/reflection.log000066400000000000000000000004101252742764200327070ustar00rootroot00000000000000INFO org.apache.log4j.receivers.rewrite.RewriteAppenderTest - p1: p2: Message 0 INFO org.apache.log4j.receivers.rewrite.RewriteAppenderTest - p1: p2:Hello I am bean. INFO org.apache.log4j.receivers.rewrite.RewriteAppenderTest - p1:Hola p2:Hello Welcome to The Hub apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/receivers/rewrite/reflection.xml000066400000000000000000000027401252742764200327360ustar00rootroot00000000000000 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/receivers/xml/000077500000000000000000000000001252742764200271765ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/receivers/xml/xmlLayout.1.xml000066400000000000000000000206661252742764200320670ustar00rootroot00000000000000 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/receivers/xml/xsltLayout.1.xml000066400000000000000000000220741252742764200322540ustar00rootroot00000000000000 in X() constructor Message 0 Message 0 Message 1 Message 1 Message 2 Message 2 Message 3 Message 3 Message 4 Message 4 Message 5 java.lang.Exception: Just testing at org.apache.log4j.xml.XSLTLayoutTestCase.common(XSLTLayoutTestCase.java:201) at org.apache.log4j.xml.XSLTLayoutTestCase.testBasic(XSLTLayoutTestCase.java:65) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at junit.textui.TestRunner.doRun(TestRunner.java:116) at com.intellij.rt.execution.junit.IdeaTestRunner.doRun(IdeaTestRunner.java:69) at junit.textui.TestRunner.doRun(TestRunner.java:109) at com.intellij.rt.execution.junit.IdeaTestRunner.startRunnerWithArgs(IdeaTestRunner.java:24) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:118) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:40) Message 5 java.lang.Exception: Just testing at org.apache.log4j.xml.XSLTLayoutTestCase.common(XSLTLayoutTestCase.java:201) at org.apache.log4j.xml.XSLTLayoutTestCase.testBasic(XSLTLayoutTestCase.java:65) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at junit.textui.TestRunner.doRun(TestRunner.java:116) at com.intellij.rt.execution.junit.IdeaTestRunner.doRun(IdeaTestRunner.java:69) at junit.textui.TestRunner.doRun(TestRunner.java:109) at com.intellij.rt.execution.junit.IdeaTestRunner.startRunnerWithArgs(IdeaTestRunner.java:24) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:118) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:40) Message 6 java.lang.Exception: Just testing at org.apache.log4j.xml.XSLTLayoutTestCase.common(XSLTLayoutTestCase.java:201) at org.apache.log4j.xml.XSLTLayoutTestCase.testBasic(XSLTLayoutTestCase.java:65) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at junit.textui.TestRunner.doRun(TestRunner.java:116) Message 6 java.lang.Exception: Just testing at org.apache.log4j.xml.XSLTLayoutTestCase.common(XSLTLayoutTestCase.java:201) at org.apache.log4j.xml.XSLTLayoutTestCase.testBasic(XSLTLayoutTestCase.java:65) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at junit.textui.TestRunner.doRun(TestRunner.java:116) apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/000077500000000000000000000000001252742764200260555ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/filter1.xml000066400000000000000000000043031252742764200301450ustar00rootroot00000000000000 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/renaming.0000066400000000000000000000000321252742764200277310ustar00rootroot00000000000000RenamingTest - Hello 0 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/renaming.1000066400000000000000000000000321252742764200277320ustar00rootroot00000000000000RenamingTest - Hello 1 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/renaming.2000077500000000000000000000000621252742764200277410ustar00rootroot00000000000000RenamingTest - Hello 0 RenamingTest - Hello 1 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/sbr-test2.0000066400000000000000000000001441252742764200277620ustar00rootroot00000000000000Hello--10 Hello--11 Hello--12 Hello--13 Hello--14 Hello--15 Hello--16 Hello--17 Hello--18 Hello--19 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/sbr-test2.1000066400000000000000000000001441252742764200277630ustar00rootroot00000000000000Hello---0 Hello---1 Hello---2 Hello---3 Hello---4 Hello---5 Hello---6 Hello---7 Hello---8 Hello---9 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/sbr-test2.log000066400000000000000000000000621252742764200304030ustar00rootroot00000000000000Hello--20 Hello--21 Hello--22 Hello--23 Hello--24 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/sbr-test3.0.gz000066400000000000000000000001041252742764200303760ustar00rootroot00000000000000$hAsbr-test3.0H54 ,#82L,38β,O dapache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/sbr-test3.1.gz000066400000000000000000000001041252742764200303770ustar00rootroot00000000000000(hAsbr-test3.1H5 ,#82L,38β,`bdapache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/sbr-test3.log000066400000000000000000000000621252742764200304040ustar00rootroot00000000000000Hello--20 Hello--21 Hello--22 Hello--23 Hello--24 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/sbr-test4.log000066400000000000000000000003721252742764200304110ustar00rootroot00000000000000Hello---0 Hello---1 Hello---2 Hello---3 Hello---4 Hello---5 Hello---6 Hello---7 Hello---8 Hello---9 Hello--10 Hello--11 Hello--12 Hello--13 Hello--14 Hello--15 Hello--16 Hello--17 Hello--18 Hello--19 Hello--20 Hello--21 Hello--22 Hello--23 Hello--24 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/tbr-test1.0000066400000000000000000000000001252742764200277510ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/tbr-test1.1000066400000000000000000000001041252742764200277570ustar00rootroot00000000000000TimeBasedRollingTest - Hello---0 TimeBasedRollingTest - Hello---1 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/tbr-test1.2000066400000000000000000000001041252742764200277600ustar00rootroot00000000000000TimeBasedRollingTest - Hello---2 TimeBasedRollingTest - Hello---3 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/tbr-test1.3000066400000000000000000000000421252742764200277620ustar00rootroot00000000000000TimeBasedRollingTest - Hello---4 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/tbr-test2.0000066400000000000000000000000001252742764200277520ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/tbr-test2.1000066400000000000000000000001041252742764200277600ustar00rootroot00000000000000TimeBasedRollingTest - Hello---0 TimeBasedRollingTest - Hello---1 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/tbr-test2.2000066400000000000000000000001041252742764200277610ustar00rootroot00000000000000TimeBasedRollingTest - Hello---2 TimeBasedRollingTest - Hello---3 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/tbr-test2.3000066400000000000000000000000421252742764200277630ustar00rootroot00000000000000TimeBasedRollingTest - Hello---4 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/tbr-test3.0.gz000066400000000000000000000000401252742764200303760ustar00rootroot00000000000000h?tbr-test3.0apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/tbr-test3.1.gz000066400000000000000000000001101252742764200303750ustar00rootroot00000000000000Kh?tbr-test3.1 MuJ,NM KI-.QUH5  l[Dapache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/tbr-test3.2.gz000066400000000000000000000001101252742764200303760ustar00rootroot00000000000000[h?tbr-test3.2 MuJ,NM KI-.QUH5 ˜ /yDapache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/tbr-test3.3000066400000000000000000000000421252742764200277640ustar00rootroot00000000000000TimeBasedRollingTest - Hello---4 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/tbr-test4.0000066400000000000000000000000001252742764200277540ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/tbr-test4.1000066400000000000000000000001041252742764200277620ustar00rootroot00000000000000TimeBasedRollingTest - Hello---0 TimeBasedRollingTest - Hello---1 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/tbr-test4.2000066400000000000000000000001041252742764200277630ustar00rootroot00000000000000TimeBasedRollingTest - Hello---2 TimeBasedRollingTest - Hello---3 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/tbr-test4.3000066400000000000000000000000421252742764200277650ustar00rootroot00000000000000TimeBasedRollingTest - Hello---4 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/tbr-test5.0000066400000000000000000000000001252742764200277550ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/tbr-test5.1000066400000000000000000000001041252742764200277630ustar00rootroot00000000000000TimeBasedRollingTest - Hello---0 TimeBasedRollingTest - Hello---1 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/tbr-test5.2000066400000000000000000000001041252742764200277640ustar00rootroot00000000000000TimeBasedRollingTest - Hello---2 TimeBasedRollingTest - Hello---3 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/tbr-test5.3000066400000000000000000000000421252742764200277660ustar00rootroot00000000000000TimeBasedRollingTest - Hello---4 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/tbr-test6.0.gz000066400000000000000000000000241252742764200304030ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/tbr-test6.1.gz000066400000000000000000000001101252742764200304000ustar00rootroot00000000000000h?tbr-test6.1 MuJ,NM KI-.QUH5  l[Dapache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/tbr-test6.2.gz000066400000000000000000000001101252742764200304010ustar00rootroot00000000000000:h?tbr-test6.2 MuJ,NM KI-.QUH5 ˜ /yDapache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/tbr-test6.3000066400000000000000000000000421252742764200277670ustar00rootroot00000000000000TimeBasedRollingTest - Hello---4 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/rolling/time1.xml000066400000000000000000000034341252742764200276220ustar00rootroot00000000000000 apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/xml/000077500000000000000000000000001252742764200252075ustar00rootroot00000000000000apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/xml/xsltLayout.1000066400000000000000000000130321252742764200274600ustar00rootroot00000000000000 in X() constructor Message 0 Message 0 Message 1 Message 1 Message 2 Message 2 Message 3 Message 3 Message 4 Message 4 Message 5 java.lang.Exception: Just testing at org.apache.log4j.xml.XSLTLayoutTestCase.common(X) at org.apache.log4j.xml.XSLTLayoutTestCase.testBasic(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) Message 5 java.lang.Exception: Just testing at org.apache.log4j.xml.XSLTLayoutTestCase.common(X) at org.apache.log4j.xml.XSLTLayoutTestCase.testBasic(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) Message 6 java.lang.Exception: Just testing at org.apache.log4j.xml.XSLTLayoutTestCase.common(X) at org.apache.log4j.xml.XSLTLayoutTestCase.testBasic(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) Message 6 java.lang.Exception: Just testing at org.apache.log4j.xml.XSLTLayoutTestCase.common(X) at org.apache.log4j.xml.XSLTLayoutTestCase.testBasic(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestResult$1.protect(X) at junit.framework.TestResult.runProtected(X) at junit.framework.TestResult.run(X) at junit.framework.TestCase.run(X) at junit.framework.TestSuite.runTest(X) at junit.framework.TestSuite.run(X) apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/xml/xsltLayout.2000066400000000000000000000151371252742764200274710ustar00rootroot00000000000000 in X() constructor Message 0 Message 0 Message 1 Message 1 Message 2 Message 2 Message 3 Message 3 Message 4 Message 4 Message 5 java.lang.Exception: Just testing at org.apache.log4j.xml.XSLTLayoutTestCase.common(X) at org.apache.log4j.xml.XSLTLayoutTestCase.testLocationInfo(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) Message 5 java.lang.Exception: Just testing at org.apache.log4j.xml.XSLTLayoutTestCase.common(X) at org.apache.log4j.xml.XSLTLayoutTestCase.testLocationInfo(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) Message 6 java.lang.Exception: Just testing at org.apache.log4j.xml.XSLTLayoutTestCase.common(X) at org.apache.log4j.xml.XSLTLayoutTestCase.testLocationInfo(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) Message 6 java.lang.Exception: Just testing at org.apache.log4j.xml.XSLTLayoutTestCase.common(X) at org.apache.log4j.xml.XSLTLayoutTestCase.testLocationInfo(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/xml/xsltLayout.3000066400000000000000000000006621252742764200274670ustar00rootroot00000000000000 Message with embedded <![CDATA[<hello>hi</hello>]]>. apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/xml/xsltLayout.4000066400000000000000000000015311252742764200274640ustar00rootroot00000000000000 HTTPAppender log record yyyy-MM-ddTHH:mm:ss.SSSZ org.apache.log4j.xml.XSLTLayoutTest DEBUG main DEBUG message HTTPAppender log record yyyy-MM-ddTHH:mm:ss.SSSZ org.apache.log4j.xml.XSLTLayoutTest INFO main INFO message apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/xml/xsltLayout.mdc.1000066400000000000000000000005521252742764200302250ustar00rootroot00000000000000 Hello apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/xml/xsltLayout.mdc.2000066400000000000000000000006721252742764200302310ustar00rootroot00000000000000 Hello apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/xml/xsltLayout.null000066400000000000000000000017111252742764200302730ustar00rootroot00000000000000 hi hi java.lang.Exception at org.apache.log4j.xml.XSLTLayoutTestCase.testNull(X) at java.lang.reflect.Method.invoke(X) at junit.framework.TestCase.runTest(X) at junit.framework.TestCase.runBare(X) at junit.framework.TestCase.run(X) apache-log4j-extras1.2-1.2.17/src/test/resources/org/apache/log4j/xml/xsltLayout4.xml000066400000000000000000000076301252742764200302130ustar00rootroot00000000000000 HTTPAppender log record