apache-log4cxx-1.3.1/INSTALL0000644000175100001770000000173714721727031014735 0ustar runnerdockerLicensed 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. Detailed build instructions are provided for in both HTML (as generated by Doxygen) and Markdown format in releases. CMake: src/site/markdown/development/build-cmake.md Microsoft Vcpkg: src/site/markdown/development/build-vcpkg.md apache-log4cxx-1.3.1/LICENSE0000644000175100001770000002613614721727031014711 0ustar runnerdocker 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 [yyyy] [name of copyright owner] 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-log4cxx-1.3.1/NOTICE0000644000175100001770000000025014721727031014575 0ustar runnerdockerApache log4cxx Copyright 2004-2023 The Apache Software Foundation This product includes software developed by The Apache Software Foundation (http://www.apache.org/). apache-log4cxx-1.3.1/README.md0000644000175100001770000000535614721727031015164 0ustar runnerdocker [![Linux](https://github.com/apache/logging-log4cxx/actions/workflows/log4cxx-ubuntu.yml/badge.svg)](https://github.com/apache/logging-log4cxx/actions/workflows/log4cxx-ubuntu.yml) [![MacOS](https://github.com/apache/logging-log4cxx/actions/workflows/log4cxx-macos.yml/badge.svg)](https://github.com/apache/logging-log4cxx/actions/workflows/log4cxx-macos.yml)
[![Windows (dll)](https://github.com/apache/logging-log4cxx/actions/workflows/log4cxx-windows.yml/badge.svg)](https://github.com/apache/logging-log4cxx/actions/workflows/log4cxx-windows.yml) [![Windows (static)](https://github.com/apache/logging-log4cxx/actions/workflows/log4cxx-windows-static.yml/badge.svg)](https://github.com/apache/logging-log4cxx/actions/workflows/log4cxx-windows-static.yml)
[![ABI stability](https://github.com/apache/logging-log4cxx/actions/workflows/abi-compatibility.yml/badge.svg)](https://github.com/apache/logging-log4cxx/actions/workflows/abi-compatibility.yml) [![Quality gate](https://github.com/apache/logging-log4cxx/actions/workflows/sonarcloud.yml/badge.svg)](https://github.com/apache/logging-log4cxx/actions/workflows/sonarcloud.yml) Apache Log4cxx is a logging framework for C++. For answers to such questions as "What is logging?", "What should a logging framework do?" and "How to do logging properly?" refer to the [logging overview page](https://logging.apache.org/what-is-logging.html). The [quick start guide](https://logging.apache.org/log4cxx/latest_stable/quick-start.html) shows what code you write to use Log4cxx in your project. For other information about Log4cxx (e.g. [getting help](https://logging.apache.org/log4cxx/latest_stable/community.html), [official release downloads](https://logging.apache.org/log4cxx/latest_stable/download.html), [building Log4cxx](https://logging.apache.org/log4cxx/latest_stable/build.html)) use [the Log4cxx project website](https://logging.apache.org/log4cxx/latest_stable). Log4cxx is part of the [Apache Logging Services](https://logging.apache.org/) PMC. apache-log4cxx-1.3.1/CMakeLists.txt0000644000175100001770000003363114721727031016442 0ustar runnerdocker# # 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. # cmake_minimum_required(VERSION 3.13) include(src/cmake/projectVersionDetails.cmake) project(log4cxx VERSION ${log4cxx_VER} LANGUAGES CXX) include(CTest) # If you are including log4cxx from a higher-level CMake file(perhaps as a submodule?) # CMAKE_SOURCE_DIR will refer to the first CMakeLists.txt. Since we need some files # in relation to the log4cxx source root, set a variable that contains the log4cxx root. set(LOG4CXX_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}") # The namespace in which all log4cxx entities will be placed, default value is "log4cxx" set(LOG4CXX_NS "log4cxx" CACHE STRING "Root namespace name") # define the SO Version of the library. Version of the log4cxx project is subtly different than the version of the library # (at least in the past it was project vesion: 0.a.b.c and the library so vesion a.b.c.0 # See also: https://mail.kde.org/pipermail/kde-buildsystem/2008-April/004543.html # Note that the lib version is different from the SOVERSION # The lib version is the version of log4cxx, the SOVERSION is the ABI version # See also: https://cmake.org/pipermail/cmake/2012-September/051904.html set(current_log4cxx_ABI_VER 15) set(next_log4cxx_ABI_VER 16) set(log4cxx_ABI_VER "${current_log4cxx_ABI_VER}" CACHE STRING "The DSO library version") set_property(CACHE log4cxx_ABI_VER PROPERTY STRINGS "${current_log4cxx_ABI_VER}" "${next_log4cxx_ABI_VER}") set(LIBLOG4CXX_LIB_VERSION ${log4cxx_ABI_VER}.${log4cxx_VERSION_MINOR}.${log4cxx_VERSION_PATCH}) set(LIBLOG4CXX_LIB_SOVERSION ${log4cxx_ABI_VER}) # Set the 'release' version. This is the human-readable version set(LOG4CXX_RELEASE_VERSION ${log4cxx_VERSION_MAJOR}.${log4cxx_VERSION_MINOR}.${log4cxx_VERSION_PATCH}) # FindAPR and FindAPR-util are not provided by APR and APR-Util so source them locally list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/src/cmake") # Add support for linking statically option(BUILD_SHARED_LIBS "Build shared libraries" ON) if(NOT BUILD_SHARED_LIBS) set(LOG4CXX_COMPILE_DEFINITIONS LOG4CXX_STATIC) endif() option(ENABLE_COVERAGE "Enable code coverage" OFF) if(ENABLE_COVERAGE) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --coverage") endif() # Find Apache Runtime option(APR_STATIC "Link to the APR static library" OFF) find_package(APR REQUIRED) # Find Apache Runtime Utilities option(APU_STATIC "Link to the APR-Util static library" OFF) find_package(APR-Util REQUIRED) find_package( Threads REQUIRED ) # Find expat for XML parsing find_package(EXPAT REQUIRED) if(TARGET EXPAT::EXPAT) set(EXPAT_LIBRARIES EXPAT::EXPAT) elseif(TARGET expat::expat) set(EXPAT_LIBRARIES expat::expat) endif() option(LOG4CXX_ENABLE_ODBC "Support logging via ODBC" OFF) if(LOG4CXX_ENABLE_ODBC) find_package(ODBC) if(${ODBC_FOUND}) set(HAS_ODBC 1) else() set(HAS_ODBC 0) endif(${ODBC_FOUND}) if(NOT ${HAS_ODBC}) message(SEND_ERROR "ODBC not found but requested") endif() else() set(HAS_ODBC 0) endif(LOG4CXX_ENABLE_ODBC) option(LOG4CXX_ENABLE_ESMTP "Support logging via libesmtp" OFF) option(LIBESMTP_STATIC "Link to the libesmtp static library" OFF) if(LOG4CXX_ENABLE_ESMTP) find_package(ESMTP) if(ESMTP_FOUND) set(HAS_LIBESMTP 1) else() set(HAS_LIBESMTP 0) message(SEND_ERROR "libesmtp not found but SMTP support requested") endif(ESMTP_FOUND) else() set(ESMTP_LIBRARIES ) set(HAS_LIBESMTP 0) endif(LOG4CXX_ENABLE_ESMTP) find_package(fmt 7.1 QUIET) if(${fmt_FOUND}) option(ENABLE_FMT_LAYOUT "Enable the FMT layout(if libfmt found)" ON) else() set(ENABLE_FMT_LAYOUT "OFF") endif() # Request C++20, if available # This *should* fallback to an older standard if it is not available if( NOT "${CMAKE_CXX_STANDARD}") set(CMAKE_CXX_STANDARD 20) endif() # Don't allow for compiler-specific extensions set(CMAKE_CXX_EXTENSIONS OFF) # Use solution folders. set_property(GLOBAL PROPERTY USE_FOLDERS ON) # Building add_subdirectory(src) ## Installing if(WIN32) option(LOG4CXX_INSTALL_PDB "Install .pdb files (if generated)" ON) endif() include(GNUInstallDirs) install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/src/main/include/log4cxx DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} FILES_MATCHING PATTERN "*.h" PATTERN "Private" EXCLUDE ) install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/src/main/include/log4cxx DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} FILES_MATCHING PATTERN "*.h" PATTERN "Private" EXCLUDE ) install(TARGETS log4cxx EXPORT ${LOG4CXX_LIB_NAME}Targets RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} ) if(LOG4CXX_QT_SUPPORT) install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/src/main/include/log4cxx-qt DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} FILES_MATCHING PATTERN "*.h" ) install(TARGETS log4cxx-qt EXPORT ${LOG4CXX_LIB_NAME}-qtTargets RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} ) endif(LOG4CXX_QT_SUPPORT) IF(MSVC AND BUILD_SHARED_LIBS AND LOG4CXX_INSTALL_PDB) INSTALL(FILES $ DESTINATION ${CMAKE_INSTALL_BINDIR} CONFIGURATIONS RelWithDebInfo Debug ) ENDIF() set(install_pkg_config ON) if(MSVC) set(install_pkg_config OFF) endif(MSVC) option(LOG4CXX_WITH_PKG_CONFIG "Support pkg_config in consuming projects" ${install_pkg_config}) if(LOG4CXX_WITH_PKG_CONFIG) set(prefix "${CMAKE_INSTALL_PREFIX}") set(exec_prefix "${CMAKE_INSTALL_PREFIX}") set(libdir "\${prefix}/${CMAKE_INSTALL_LIBDIR}") set(includedir "\${prefix}/${CMAKE_INSTALL_INCLUDEDIR}") set(VERSION "${log4cxx_VERSION_MAJOR}.${log4cxx_VERSION_MINOR}.${log4cxx_VERSION_PATCH}") configure_file("${CMAKE_CURRENT_SOURCE_DIR}/liblog4cxx.pc.in" "${CMAKE_CURRENT_BINARY_DIR}/lib${LOG4CXX_LIB_NAME}.pc" ) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/lib${LOG4CXX_LIB_NAME}.pc" DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig) if(LOG4CXX_QT_SUPPORT) set(prefix "${CMAKE_INSTALL_PREFIX}") set(exec_prefix "${CMAKE_INSTALL_PREFIX}") set(libdir "\${prefix}/${CMAKE_INSTALL_LIBDIR}") set(includedir "\${prefix}/${CMAKE_INSTALL_INCLUDEDIR}") set(VERSION "${log4cxx_VERSION_MAJOR}.${log4cxx_VERSION_MINOR}.${log4cxx_VERSION_PATCH}") configure_file("${CMAKE_CURRENT_SOURCE_DIR}/liblog4cxx-qt.pc.in" "${CMAKE_CURRENT_BINARY_DIR}/lib${LOG4CXX_LIB_NAME}-qt.pc" ) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/lib${LOG4CXX_LIB_NAME}-qt.pc" DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig ) endif(LOG4CXX_QT_SUPPORT) endif(LOG4CXX_WITH_PKG_CONFIG) # Support for find_package(log4cxx) in consuming CMake projects using # target_include_directories(myApplication PRIVATE $) # target_link_libraries( myApplication PRIVATE log4cxx) install(EXPORT ${LOG4CXX_LIB_NAME}Targets FILE ${LOG4CXX_LIB_NAME}Config.cmake DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${LOG4CXX_LIB_NAME} ) # Support for find_package(log4cxx 1.3) in consuming CMake projects include(CMakePackageConfigHelpers) write_basic_package_version_file("${CMAKE_CURRENT_BINARY_DIR}/${LOG4CXX_LIB_NAME}ConfigVersion.cmake" VERSION ${PROJECT_VERSION} COMPATIBILITY SameMinorVersion ) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${LOG4CXX_LIB_NAME}ConfigVersion.cmake" DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${LOG4CXX_LIB_NAME} ) if(LOG4CXX_QT_SUPPORT) install(EXPORT ${LOG4CXX_LIB_NAME}-qtTargets FILE ${LOG4CXX_LIB_NAME}-qtConfig.cmake DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${LOG4CXX_LIB_NAME}-qt ) # Support for find_package(log4cxx 0.11) in consuming CMake projects include(CMakePackageConfigHelpers) write_basic_package_version_file("${CMAKE_CURRENT_BINARY_DIR}/${LOG4CXX_LIB_NAME}-qtConfigVersion.cmake" VERSION ${PROJECT_VERSION} COMPATIBILITY SameMinorVersion ) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${LOG4CXX_LIB_NAME}-qtConfigVersion.cmake" DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${LOG4CXX_LIB_NAME}-qt ) endif(LOG4CXX_QT_SUPPORT) # # Get variables used in configuration information messages from subdirectories # get_directory_property( HAS_LIBESMTP DIRECTORY src/main/include DEFINITION HAS_LIBESMTP ) get_directory_property( HAS_SYSLOG DIRECTORY src/main/include DEFINITION HAS_SYSLOG ) get_directory_property( FILESYSTEM_IMPL DIRECTORY src DEFINITION FILESYSTEM_IMPL ) get_directory_property( STD_MAKE_UNIQUE_IMPL DIRECTORY src DEFINITION STD_MAKE_UNIQUE_IMPL ) get_directory_property( STD_LIB_HAS_UNICODE_STRING DIRECTORY src DEFINITION STD_LIB_HAS_UNICODE_STRING ) get_directory_property( HAS_THREAD_LOCAL DIRECTORY src DEFINITION HAS_THREAD_LOCAL ) get_directory_property( BUILD_FUZZERS DIRECTORY src DEFINITION BUILD_FUZZERS ) # # Use ON/OFF in configuration information messages # foreach(varName HAS_ODBC HAS_LIBESMTP HAS_SYSLOG) if(${varName} EQUAL 0) set(${varName} "OFF" ) elseif(${varName} EQUAL 1) set(${varName} "ON" ) else() set(${varName} "UNKNOWN" ) endif() endforeach() if(${WIN32}) set(HAS_NT_EVENTLOG_APPENDER "ON") else() set(HAS_NT_EVENTLOG_APPENDER "OFF") endif() # # Output configuration information # Similar to APR CMake configuration # message(STATUS "") message(STATUS "") message(STATUS "Log4cxx configuration summary:") message(STATUS "") message(STATUS " C++ compiler .................... : ${CMAKE_CXX_COMPILER}") message(STATUS " C++ features requested: ......... : ${CMAKE_CXX_STANDARD}") message(STATUS " Build shared library ............ : ${BUILD_SHARED_LIBS}") message(STATUS " Build tests ..................... : ${BUILD_TESTING}") message(STATUS " Build examples................... : ${BUILD_EXAMPLES}") message(STATUS " Build fuzzers.................... : ${BUILD_FUZZERS}") message(STATUS " Build site ...................... : ${BUILD_SITE}") message(STATUS " Install prefix .................. : ${CMAKE_INSTALL_PREFIX}") message(STATUS " log4cxx library name ............ : ${LOG4CXX_LIB_NAME}") message(STATUS " log4cxx namespace ............... : ${LOG4CXX_NS}") message(STATUS " log4cxx char API ................ : ON") message(STATUS " log4cxx wchar API ............... : ${LOG4CXX_WCHAR_T}") if(STD_LIB_HAS_UNICODE_STRING) message(STATUS " log4cxx unichar API ............. : ${LOG4CXX_UNICHAR}") else() message(STATUS " std::basic_string ok? .. : FALSE") endif() if(APPLE) message(STATUS " log4cxx cfstring API ............ : ${LOG4CXX_CFSTRING}") endif() message(STATUS " log4cxx char type ............... : ${LOG4CXX_CHAR}") message(STATUS " character encoding .............. : ${LOG4CXX_CHARSET}") message(STATUS " Networking support .............. : ${LOG4CXX_NETWORKING_SUPPORT}") message(STATUS " DOMConfigurator support ......... : ${LOG4CXX_DOMCONFIGURATOR_SUPPORT}") message(STATUS " Qt support ...................... : ${LOG4CXX_QT_SUPPORT}") message(STATUS "C++ version and Boost settings:") message(STATUS " Prefer boost: ................... : ${PREFER_BOOST}") message(STATUS " make_unique implementation :..... : ${STD_MAKE_UNIQUE_IMPL}") message(STATUS " filesystem implementation ....... : ${FILESYSTEM_IMPL}") message(STATUS " format implementation ........... : ${LOG4CXX_FORMAT_NAMESPACE}::format") message(STATUS " thread_local support? ........... : ${HAS_THREAD_LOCAL}") if(BUILD_TESTING) message(STATUS "Applications required for tests:") message(STATUS " zip ............................. : ${ZIP_APP}") message(STATUS " sed ............................. : ${SED_APP}") message(STATUS " gzip ............................ : ${GZIP_APP}") endif(BUILD_TESTING) message(STATUS "Available appenders:") message(STATUS " Async Appender .................. : ON") message(STATUS " ODBC Appender ................... : ${HAS_ODBC}") message(STATUS " DB Appender ..................... : ON") message(STATUS " SMTP Appender ................... : ${HAS_LIBESMTP}") message(STATUS " XMLSocketAppender ............... : ${LOG4CXX_NETWORKING_SUPPORT}") message(STATUS " SyslogAppender .................. : ${LOG4CXX_NETWORKING_SUPPORT}") if(LOG4CXX_NETWORKING_SUPPORT) message(STATUS " Using syslog.h .................. : ${HAS_SYSLOG}") endif() message(STATUS " TelnetAppender .................. : ${LOG4CXX_NETWORKING_SUPPORT}") message(STATUS " NTEventLogAppender .............. : ${HAS_NT_EVENTLOG_APPENDER}") message(STATUS " OutputDebugStringAppender ....... : ${LOG4CXX_NETWORKING_SUPPORT}") message(STATUS " ConsoleAppender ................. : ON") message(STATUS " FileAppender .................... : ON") message(STATUS " RollingFileAppender ............. : ON") message(STATUS " MultiprocessRollingFileAppender . : ${LOG4CXX_MULTIPROCESS_ROLLING_FILE_APPENDER}") message(STATUS "Available layouts:") message(STATUS " HTMLLayout ...................... : ON") message(STATUS " JSONLayout ...................... : ON") message(STATUS " PatternLayout ................... : ON") message(STATUS " SimpleLayout .................... : ON") message(STATUS " XMLLayout ....................... : ON") message(STATUS " FMTLayout ....................... : ${ENABLE_FMT_LAYOUT}") apache-log4cxx-1.3.1/src/0000755000175100001770000000000014721727031014463 5ustar runnerdockerapache-log4cxx-1.3.1/src/test/0000755000175100001770000000000014721727031015442 5ustar runnerdockerapache-log4cxx-1.3.1/src/test/resources/0000755000175100001770000000000014721727031017454 5ustar runnerdockerapache-log4cxx-1.3.1/src/test/resources/L7D_fr_CH.properties0000644000175100001770000000154514721727031023226 0ustar runnerdocker# 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. # test=Ceci est le test en francais pour la p'tite Suisse. hello world=Salut le monde. apache-log4cxx-1.3.1/src/test/resources/input/0000755000175100001770000000000014721727031020613 5ustar runnerdockerapache-log4cxx-1.3.1/src/test/resources/input/hierarchyThreshold1.properties0000644000175100001770000000204314721727031026644 0ustar runnerdocker# 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.threshold=OFF log4j.rootLogger=,A log4j.appender.A=org.apache.log4j.FileAppender log4j.appender.A.File=output/hierarchythreshold log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%p %c = %m%n apache-log4cxx-1.3.1/src/test/resources/input/l7d1.properties0000644000175100001770000000211414721727031023476 0ustar runnerdocker# 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=INFO, testAppender log4j.appender.testAppender=org.apache.log4j.FileAppender log4j.appender.testAppender.File= output/l7d1 log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=T1 %5p - %m%n apache-log4cxx-1.3.1/src/test/resources/input/propertiestestcase-mixed.properties0000644000175100001770000000160614721727031027770 0ustar runnerdocker# 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. # propertiestestcase.value1=hi this is a test propertiestestcase.value2=something propertiestestcase.value3=some_value apache-log4cxx-1.3.1/src/test/resources/input/hierarchyThreshold4.properties0000644000175100001770000000204414721727031026650 0ustar runnerdocker# 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.threshold=WARN log4j.rootLogger=,A log4j.appender.A=org.apache.log4j.FileAppender log4j.appender.A.File=output/hierarchythreshold log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%p %c = %m%n apache-log4cxx-1.3.1/src/test/resources/input/defaultInit3.properties0000644000175100001770000000203714721727031025266 0ustar runnerdocker# 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, D3 log4j.appender.D3=org.apache.log4j.FileAppender log4j.appender.D3.File=output/temp log4j.appender.D3.Append=false log4j.appender.D3.layout=org.apache.log4j.PatternLayout log4j.appender.D3.layout.ConversionPattern=%d [%t] %-5p %.16c - %m%napache-log4cxx-1.3.1/src/test/resources/input/patternLayout1.properties0000644000175100001770000000212314721727031025663 0ustar runnerdocker# 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=output/patternlayout log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=%-5p - %m%n apache-log4cxx-1.3.1/src/test/resources/input/socketServer1.properties0000644000175100001770000000217114721727031025472 0ustar runnerdocker# 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=TRACE, A log4j.logger.org.apache.log4j.test.ShortSocketServer=WARN log4j.logger.org.apache.log4j.net.SocketNode=WARN log4j.appender.A=org.apache.log4j.FileAppender log4j.appender.A.file=output/temp log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%5p %x [%t] %c %m%n apache-log4cxx-1.3.1/src/test/resources/input/patternLayout.mdc.1.properties0000644000175100001770000000212414721727031026504 0ustar runnerdocker# 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=output/patternlayout log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=%-5p - %m %Xapache-log4cxx-1.3.1/src/test/resources/input/hierarchyThreshold6.properties0000644000175100001770000000204514721727031026653 0ustar runnerdocker# 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.threshold=DEBUG log4j.rootLogger=,A log4j.appender.A=org.apache.log4j.FileAppender log4j.appender.A.File=output/hierarchythreshold log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%p %c = %m%n apache-log4cxx-1.3.1/src/test/resources/input/patternLayout8.properties0000644000175100001770000000214014721727031025671 0ustar runnerdocker# 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=output/patternlayout log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=%r [%t] %-5p %.16c - %m%napache-log4cxx-1.3.1/src/test/resources/input/hierarchyThreshold7.properties0000644000175100001770000000210414721727031026650 0ustar runnerdocker# 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.threshold=TRACE#org.apache.log4j.xml.XLevel log4j.rootLogger=ALL,A log4j.appender.A=org.apache.log4j.FileAppender log4j.appender.A.File=output/hierarchythreshold log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%p %c = %m%n apache-log4cxx-1.3.1/src/test/resources/input/patternLayout6.properties0000644000175100001770000000215214721727031025672 0ustar runnerdocker# 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=output/patternlayout log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=%d{ABSOLUTE} [%t] %-5p %.16c - %m%napache-log4cxx-1.3.1/src/test/resources/input/patternLayout13.properties0000644000175100001770000000213014721727031025744 0ustar runnerdocker# 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=output/patternlayout log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=%Y%-5p -%y %m%n apache-log4cxx-1.3.1/src/test/resources/input/ndc/0000755000175100001770000000000014721727031021357 5ustar runnerdockerapache-log4cxx-1.3.1/src/test/resources/input/ndc/NDC1.properties0000644000175100001770000000246314721727031024167 0ustar runnerdocker# 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=output/ndc log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=%-5p %x - %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-log4cxx-1.3.1/src/test/resources/input/patternLayout9.properties0000644000175100001770000000213514721727031025676 0ustar runnerdocker# 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=output/patternlayout log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=[%t] %-5p %.16c : %m%napache-log4cxx-1.3.1/src/test/resources/input/socketServer3.properties0000644000175100001770000000220314721727031025470 0ustar runnerdocker# 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=TRACE, A log4j.Logger.org.apache.log4j.test.ShortSocketServer=WARN log4j.Logger.org.apache.log4j.net.SocketNode=WARN log4j.appender.A=org.apache.log4j.FileAppender log4j.appender.A.file=output/temp log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%5p %x [%t] %c{1} (%F:%L) %m%n apache-log4cxx-1.3.1/src/test/resources/input/patternLayout7.properties0000644000175100001770000000215714721727031025700 0ustar runnerdocker# 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=output/patternlayout log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=%d{HH:mm:ss,SSS} [%t] %-5p %.16c - %m%n apache-log4cxx-1.3.1/src/test/resources/input/hierarchyThreshold8.properties0000644000175100001770000000204614721727031026656 0ustar runnerdocker# 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.threshold=ALL log4j.rootLogger=ALL,A log4j.appender.A=org.apache.log4j.FileAppender log4j.appender.A.File=output/hierarchythreshold log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%p %c = %m%n apache-log4cxx-1.3.1/src/test/resources/input/patternLayout4.properties0000644000175100001770000000215114721727031025667 0ustar runnerdocker# 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=output/patternlayout log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=%d{DATE} [%t] %-5p %.16c - %m%napache-log4cxx-1.3.1/src/test/resources/input/patternLayout10.properties0000644000175100001770000000213614721727031025747 0ustar runnerdocker# 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= output/patternlayout log4j.appender.testAppender.Append= false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=[%t] %-5p %l: %m%n apache-log4cxx-1.3.1/src/test/resources/input/patternLayout11.properties0000644000175100001770000000213414721727031025746 0ustar runnerdocker# 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=output/patternlayout log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=%-5p [%t] %c{2}: %m%napache-log4cxx-1.3.1/src/test/resources/input/rolling/0000755000175100001770000000000014721727031022261 5ustar runnerdockerapache-log4cxx-1.3.1/src/test/resources/input/rolling/obsoleteRFA1.properties0000644000175100001770000000263014721727031026626 0ustar runnerdocker# 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.RollingFileAppender log4j.appender.testAppender.file=output/obsoleteRFA-test1.log log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=%m\n log4j.appender.testAppender.maxFileSize=100 log4j.appender.testAppender.maxBackupIndex=3 # 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-log4cxx-1.3.1/src/test/resources/input/rolling/filter1.xml0000644000175100001770000000416414721727031024356 0ustar runnerdocker apache-log4cxx-1.3.1/src/test/resources/input/rolling/rollingFileAppenderFromProperties.properties0000644000175100001770000000304514721727031033227 0ustar runnerdocker# 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, FILE log4j.appender.FILE=RollingFileAppender log4j.appender.FILE.layout=org.apache.log4j.PatternLayout log4j.appender.FILE.layout.ConversionPattern=%m%n log4j.appender.FILE.file=output/rollingFileFromProperties-test.log log4j.appender.FILE.rollingPolicy=FixedWindowRollingPolicy log4j.appender.FILE.rollingPolicy.MaxIndex=3 log4j.appender.FILE.rollingPolicy.FileNamePattern=output/rollingFileFromProperties-test-%i.log log4j.appender.FILE.triggeringPolicy=SizeBasedTriggeringPolicy log4j.appender.FILE.triggeringPolicy.MaxFileSize=100 # 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-log4cxx-1.3.1/src/test/resources/input/rolling/obsoleteERFA1.properties0000644000175100001770000000264314721727031026737 0ustar runnerdocker# 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.varia.ExternallyRolledFileAppender log4j.appender.testAppender.file=output/obsoleteERFA-test1.log log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=%m\n log4j.appender.testAppender.maxFileSize=10000 log4j.appender.testAppender.port=6700 # 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-log4cxx-1.3.1/src/test/resources/input/rolling/time1.xml0000644000175100001770000000343414721727031024026 0ustar runnerdocker apache-log4cxx-1.3.1/src/test/resources/input/rolling/obsoleteDRFA1.properties0000644000175100001770000000260414721727031026733 0ustar runnerdocker# 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.DailyRollingFileAppender log4j.appender.testAppender.file=output/obsoleteDRFA-test1.log log4j.appender.testAppender.datePattern='.'yyyy-MM-dd_HH_mm_ss log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=%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-log4cxx-1.3.1/src/test/resources/input/decoding/0000755000175100001770000000000014721727031022367 5ustar runnerdockerapache-log4cxx-1.3.1/src/test/resources/input/decoding/UTF-16LE.txt0000644000175100001770000000002014721727031024223 0ustar runnerdockerA0 N apache-log4cxx-1.3.1/src/test/resources/input/decoding/UTF-8.txt0000644000175100001770000000002014721727031023723 0ustar runnerdockerA؅԰আ七Ѐ ¹apache-log4cxx-1.3.1/src/test/resources/input/decoding/ascii.txt0000644000175100001770000000001014721727031024207 0ustar runnerdockerA????? ?apache-log4cxx-1.3.1/src/test/resources/input/decoding/UTF-16BE.txt0000644000175100001770000000002014721727031024211 0ustar runnerdockerA0 N apache-log4cxx-1.3.1/src/test/resources/input/decoding/latin1.txt0000644000175100001770000000001014721727031024307 0ustar runnerdockerA????? apache-log4cxx-1.3.1/src/test/resources/input/decoding/UTF-16.txt0000644000175100001770000000002214721727031024004 0ustar runnerdockerA0 N apache-log4cxx-1.3.1/src/test/resources/input/fmtLayout1.properties0000644000175100001770000000211714721727031024777 0ustar runnerdocker# 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=output/fmtlayout log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.FMTLayout log4j.appender.testAppender.layout.ConversionPattern={p:<5} - {m}{n} apache-log4cxx-1.3.1/src/test/resources/input/propertiestestcase-lf.properties0000644000175100001770000000161014721727031027256 0ustar runnerdocker# 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. # propertiestestcase.value1=hi this is a test propertiestestcase.value2=multi\ line propertiestestcase.value3=some_value apache-log4cxx-1.3.1/src/test/resources/input/hierarchyThreshold5.properties0000644000175100001770000000204414721727031026651 0ustar runnerdocker# 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.threshold=INFO log4j.rootLogger=,A log4j.appender.A=org.apache.log4j.FileAppender log4j.appender.A.File=output/hierarchythreshold log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%p %c = %m%n apache-log4cxx-1.3.1/src/test/resources/input/patternLayout5.properties0000644000175100001770000000217314721727031025674 0ustar runnerdocker# 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=output/patternlayout log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss,SSS} [%t] %-5p %.16c - %m%n apache-log4cxx-1.3.1/src/test/resources/input/socketServer8.properties0000644000175100001770000000222114721727031025475 0ustar runnerdocker# 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=TRACE, A log4j.Logger.org.apache.log4j.test.ShortSocketServer=WARN log4j.Logger.org.apache.log4j.net.SocketNode=WARN log4j.appender.A=org.apache.log4j.FileAppender log4j.appender.A.file=output/temp log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%5p %x %X{hostID} %X{key8} [%t] %c{1} - %m%n apache-log4cxx-1.3.1/src/test/resources/input/messagebuffer1.properties0000644000175100001770000000212314721727031025626 0ustar runnerdocker# 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=output/messagebuffer log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=%-5p - %m%n apache-log4cxx-1.3.1/src/test/resources/input/socketServer4.properties0000644000175100001770000000221614721727031025475 0ustar runnerdocker# 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=TRACE, A log4j.Logger.org.apache.log4j.test.ShortSocketServer=WARN log4j.Logger.org.apache.log4j.net.SocketNode=WARN log4j.appender.A=org.apache.log4j.FileAppender log4j.appender.A.file=output/temp log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%5p %x %X{key1}%X{key4} [%t] %c{1} - %m%n apache-log4cxx-1.3.1/src/test/resources/input/patternLayout12.properties0000644000175100001770000000213614721727031025751 0ustar runnerdocker# 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=output/patternlayout log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=[%t] %-5p %F(%L): %m%n apache-log4cxx-1.3.1/src/test/resources/input/fmtLayout1_expanded.properties0000644000175100001770000000213714721727031026651 0ustar runnerdocker# 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=output/fmtlayout log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.FMTLayout log4j.appender.testAppender.layout.ConversionPattern={level:<5} - {message}{newline} apache-log4cxx-1.3.1/src/test/resources/input/patternLayout2.properties0000644000175100001770000000215614721727031025672 0ustar runnerdocker# 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=output/patternlayout log4j.appender.testAppender.Append= false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=%d{ISO8601} [%t] %-5p %.16c - %m%n apache-log4cxx-1.3.1/src/test/resources/input/socketServer7.properties0000644000175100001770000000222114721727031025474 0ustar runnerdocker# 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=TRACE, A log4j.Logger.org.apache.log4j.test.ShortSocketServer=WARN log4j.Logger.org.apache.log4j.net.SocketNode=WARN log4j.appender.A=org.apache.log4j.FileAppender log4j.appender.A.file=output/temp log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%5p %x %X{hostID} %X{key7} [%t] %c{1} - %m%n apache-log4cxx-1.3.1/src/test/resources/input/patternLayout3.properties0000644000175100001770000000216414721727031025672 0ustar runnerdocker# 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=output/layout3 log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] %-5p %.16c - %m%n apache-log4cxx-1.3.1/src/test/resources/input/locationdisabled.properties0000644000175100001770000000215214721727031026231 0ustar runnerdocker# 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=output/location-disabled-test log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=%-5p[%F](%f)%L|%M| - %m%n apache-log4cxx-1.3.1/src/test/resources/input/hierarchyThreshold3.properties0000644000175100001770000000204514721727031026650 0ustar runnerdocker# 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.threshold=ERROR log4j.rootLogger=,A log4j.appender.A=org.apache.log4j.FileAppender log4j.appender.A.File=output/hierarchythreshold log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%p %c = %m%n apache-log4cxx-1.3.1/src/test/resources/input/location1.properties0000644000175100001770000000213414721727031024622 0ustar runnerdocker# 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=output/location-good-test log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=%-5p(%f) - %m%n apache-log4cxx-1.3.1/src/test/resources/input/socketServer6.properties0000644000175100001770000000222114721727031025473 0ustar runnerdocker# 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=TRACE, A log4j.Logger.org.apache.log4j.test.ShortSocketServer=WARN log4j.Logger.org.apache.log4j.net.SocketNode=WARN log4j.appender.A=org.apache.log4j.FileAppender log4j.appender.A.file=output/temp log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%5p %x %X{hostID} %X{key6} [%t] %c{1} - %m%n apache-log4cxx-1.3.1/src/test/resources/input/propertiestestcase-crlf.properties0000644000175100001770000000163314721727031027610 0ustar runnerdocker# 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. # propertiestestcase.value1=hi this is a test propertiestestcase.value2=multi\ line propertiestestcase.value3=some_value apache-log4cxx-1.3.1/src/test/resources/input/propertiestestcase.properties0000644000175100001770000000251714721727031026666 0ustar runnerdocker# 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. # propertiestestcase.tab1 tab delimited propertiestestcase.tab2=tab before key propertiestestcase.tab3\ =key contains tab propertiestestcase.tab4= tab after equals propertiestestcase\ .tab5=tab after continue propertiestestcase.tab6=\ in value propertiestestcase.tab7=continued\ value propertiestestcase.continued=continued\ value propertiestestcase.esct1\t=key contains tab propertiestestcase.esct2=\t in value propertiestestcase.escn1\n=key contains lf propertiestestcase.escn2=\n in value propertiestestcase.escr1\r=key contains cr propertiestestcase.escr2=\r in value apache-log4cxx-1.3.1/src/test/resources/input/socketServer5.properties0000644000175100001770000000221614721727031025476 0ustar runnerdocker# 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=TRACE, A log4j.Logger.org.apache.log4j.test.ShortSocketServer=WARN log4j.Logger.org.apache.log4j.net.SocketNode=WARN log4j.appender.A=org.apache.log4j.FileAppender log4j.appender.A.file=output/temp log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%5p %x %X{key1}%X{key5} [%t] %c{1} - %m%n apache-log4cxx-1.3.1/src/test/resources/input/xml/0000755000175100001770000000000014721727031021413 5ustar runnerdockerapache-log4cxx-1.3.1/src/test/resources/input/xml/DOMTestCase4.xml0000644000175100001770000000253414721727031024300 0ustar runnerdocker apache-log4cxx-1.3.1/src/test/resources/input/xml/customLevel2.xml0000644000175100001770000000312414721727031024521 0ustar runnerdocker apache-log4cxx-1.3.1/src/test/resources/input/xml/customLevel1.xml0000644000175100001770000000254014721727031024521 0ustar runnerdocker apache-log4cxx-1.3.1/src/test/resources/input/xml/customLogger2.xml0000644000175100001770000000325114721727031024672 0ustar runnerdocker apache-log4cxx-1.3.1/src/test/resources/input/xml/fallback1.xml0000644000175100001770000000436514721727031023765 0ustar runnerdocker apache-log4cxx-1.3.1/src/test/resources/input/xml/customLogger1.xml0000644000175100001770000000262614721727031024676 0ustar runnerdocker apache-log4cxx-1.3.1/src/test/resources/input/xml/DOMTestCase2.xml0000644000175100001770000000341014721727031024270 0ustar runnerdocker apache-log4cxx-1.3.1/src/test/resources/input/xml/filters.LevelMatchFilter.test4.4.xml0000644000175100001770000000301014721727031030174 0ustar runnerdocker apache-log4cxx-1.3.1/src/test/resources/input/xml/customLevel3.xml0000644000175100001770000000322514721727031024524 0ustar runnerdocker apache-log4cxx-1.3.1/src/test/resources/input/xml/customLevel4.xml0000644000175100001770000000257414721727031024533 0ustar runnerdocker apache-log4cxx-1.3.1/src/test/resources/input/xml/log4j.dtd0000644000175100001770000001507614721727031023140 0ustar runnerdocker apache-log4cxx-1.3.1/src/test/resources/input/xml/DOMTestCase1.xml0000644000175100001770000000342714721727031024277 0ustar runnerdocker apache-log4cxx-1.3.1/src/test/resources/input/xml/odbcAppenderDSN-Log4cxxTest.xml0000644000175100001770000000440014721727031027254 0ustar runnerdocker apache-log4cxx-1.3.1/src/test/resources/input/xml/filters.LevelMatchFilter.test4.2.xml0000644000175100001770000000300714721727031030200 0ustar runnerdocker apache-log4cxx-1.3.1/src/test/resources/input/xml/smtpAppender1.xml0000644000175100001770000000304314721727031024660 0ustar runnerdocker apache-log4cxx-1.3.1/src/test/resources/input/xml/filters.LevelMatchFilter.test4.0.xml0000644000175100001770000000301014721727031030170 0ustar runnerdocker apache-log4cxx-1.3.1/src/test/resources/input/xml/asyncAppender1.xml0000644000175100001770000000251514721727031025015 0ustar runnerdocker apache-log4cxx-1.3.1/src/test/resources/input/xml/defaultInit.xml0000644000175100001770000000237414721727031024413 0ustar runnerdocker apache-log4cxx-1.3.1/src/test/resources/input/xml/fluent-bit.xml0000644000175100001770000000231114721727031024203 0ustar runnerdocker apache-log4cxx-1.3.1/src/test/resources/input/xml/filters.LevelMatchFilter.test4.3.xml0000644000175100001770000000301014721727031030173 0ustar runnerdocker apache-log4cxx-1.3.1/src/test/resources/input/xml/DOMTestCase3.xml0000644000175100001770000000253214721727031024275 0ustar runnerdocker apache-log4cxx-1.3.1/src/test/resources/input/xml/filters.LevelMatchFilter.test4.1.xml0000644000175100001770000000300714721727031030177 0ustar runnerdocker apache-log4cxx-1.3.1/src/test/resources/input/xml/fallback2.xml0000644000175100001770000000502714721727031023762 0ustar runnerdocker apache-log4cxx-1.3.1/src/test/resources/input/xml/smtpAppenderValid.xml0000644000175100001770000000315114721727031025557 0ustar runnerdocker apache-log4cxx-1.3.1/src/test/resources/input/socketServer2.properties0000644000175100001770000000220414721727031025470 0ustar runnerdocker# 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=TRACE, A log4j.logger.org.apache.log4j.test.ShortSocketServer=WARN log4j.logger.org.apache.log4j.net.SocketNode=WARN log4j.appender.A=org.apache.log4j.FileAppender log4j.appender.A.file=output/temp log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%5p %x [%t] %c{1} (%F:%L) %m%n apache-log4cxx-1.3.1/src/test/resources/input/patternLayout14.properties0000644000175100001770000000212514721727031025751 0ustar runnerdocker# 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=output/patternlayout log4j.appender.testAppender.Append=false log4j.appender.testAppender.layout=org.apache.log4j.PatternLayout log4j.appender.testAppender.layout.ConversionPattern=%-5p %f: %m%n apache-log4cxx-1.3.1/src/test/resources/input/fmtLayout10.properties0000644000175100001770000000213414721727031025056 0ustar runnerdocker# 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= output/fmtlayout log4j.appender.testAppender.Append= false log4j.appender.testAppender.layout=org.apache.log4j.FMTLayout log4j.appender.testAppender.layout.ConversionPattern=[{t}] {p:<5} {l}: {m}{n} apache-log4cxx-1.3.1/src/test/resources/input/autoConfigureTest.properties0000644000175100001770000000214214721727031026402 0ustar runnerdocker# 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=INFO, A1 log4j.appender.A1=org.apache.log4j.FileAppender log4j.appender.A1.File=output/autoConfigureTest.log log4j.appender.A1.Append=false log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=%m%n #log4j.logger.AutoConfig.test1=DEBUG log4j.logger.AutoConfig.test2=DEBUG apache-log4cxx-1.3.1/src/test/resources/input/hierarchyThreshold2.properties0000644000175100001770000000204514721727031026647 0ustar runnerdocker# 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.threshold=FATAL log4j.rootLogger=,A log4j.appender.A=org.apache.log4j.FileAppender log4j.appender.A.File=output/hierarchythreshold log4j.appender.A.Append=false log4j.appender.A.layout=org.apache.log4j.PatternLayout log4j.appender.A.layout.ConversionPattern=%p %c = %m%n apache-log4cxx-1.3.1/src/test/resources/L7D_fr.properties0000644000175100001770000000175114721727031022653 0ustar runnerdocker# 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. # test=Ceci est le test en francais pour la France. hello_world=Bonjour la France. msg1=Ceci est le test numero {0} contenant l'argument {1}. msg3=Ceci est le test numero {0} contenant l'argument {1} et l'argument {2}. apache-log4cxx-1.3.1/src/test/resources/L7D_en_US.properties0000644000175100001770000000160314721727031023251 0ustar runnerdocker# 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. # test=This is the English, US test. hello_world=Hello world. msg1=This is test number {0} with string argument {1}. apache-log4cxx-1.3.1/src/test/resources/witness/0000755000175100001770000000000014721727031021150 5ustar runnerdockerapache-log4cxx-1.3.1/src/test/resources/witness/patternLayout.40000644000175100001770000000056114721727031024112 0ustar runnerdocker [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 4apache-log4cxx-1.3.1/src/test/resources/witness/socketServer.60000644000175100001770000000366614721727031023731 0ustar runnerdockerTRACE some6 T6 client-test6 MDC-TEST6 [main] SocketServerTestCase - Message 1 TRACE some6 T6 client-test6 MDC-TEST6 [main] root - Message 2 DEBUG some6 T6 client-test6 MDC-TEST6 [main] SocketServerTestCase - Message 3 DEBUG some6 T6 client-test6 MDC-TEST6 [main] root - Message 4 INFO some6 T6 client-test6 MDC-TEST6 [main] SocketServerTestCase - Message 5 WARN some6 T6 client-test6 MDC-TEST6 [main] SocketServerTestCase - Message 6 FATAL some6 T6 client-test6 MDC-TEST6 [main] SocketServerTestCase - Message 7 DEBUG some6 T6 client-test6 MDC-TEST6 [main] SocketServerTestCase - Message 8 java.lang.Exception: Just testing at org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX) at org.apache.log4j.net.SocketServerTestCase.test6(SocketServerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) ERROR some6 T6 client-test6 MDC-TEST6 [main] root - Message 9 java.lang.Exception: Just testing at org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX) at org.apache.log4j.net.SocketServerTestCase.test6(SocketServerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4cxx-1.3.1/src/test/resources/witness/dom.A1.20000644000175100001770000000070714721727031022256 0ustar runnerdockerDEBUG xml.DOMTestCase - Message 0 DEBUG xml.DOMTestCase - Message 0 DEBUG root - Message 0 INFO xml.DOMTestCase - Message 1 INFO xml.DOMTestCase - Message 1 INFO root - Message 1 WARN xml.DOMTestCase - Message 2 WARN xml.DOMTestCase - Message 2 WARN root - Message 2 ERROR xml.DOMTestCase - Message 3 ERROR xml.DOMTestCase - Message 3 ERROR root - Message 3 FATAL xml.DOMTestCase - Message 4 FATAL xml.DOMTestCase - Message 4 FATAL root - Message 4 apache-log4cxx-1.3.1/src/test/resources/witness/encoding/0000755000175100001770000000000014721727031022736 5ustar runnerdockerapache-log4cxx-1.3.1/src/test/resources/witness/encoding/UTF-16LE.log0000644000175100001770000000012614721727031024543 0ustar runnerdockerINFO - Hello, World INFO - INFO - A0 N apache-log4cxx-1.3.1/src/test/resources/witness/encoding/UTF-8.log0000644000175100001770000000006314721727031024243 0ustar runnerdockerINFO - Hello, World INFO - ¹ INFO - A؅԰আ七Ѐ apache-log4cxx-1.3.1/src/test/resources/witness/encoding/UTF-16BE.log0000644000175100001770000000012614721727031024531 0ustar runnerdockerINFO - Hello, World INFO - INFO - A0 N apache-log4cxx-1.3.1/src/test/resources/witness/encoding/ascii.log0000644000175100001770000000005314721727031024527 0ustar runnerdockerINFO - Hello, World INFO - ? INFO - A????? apache-log4cxx-1.3.1/src/test/resources/witness/encoding/UTF-16.log0000644000175100001770000000013014721727031024315 0ustar runnerdockerINFO - Hello, World INFO - INFO - A0 N apache-log4cxx-1.3.1/src/test/resources/witness/encoding/latin1.log0000644000175100001770000000005314721727031024627 0ustar runnerdockerINFO - Hello, World INFO - INFO - A????? apache-log4cxx-1.3.1/src/test/resources/witness/xmlLayout.mdc.10000644000175100001770000000044014721727031023770 0ustar runnerdocker apache-log4cxx-1.3.1/src/test/resources/witness/patternLayout.60000644000175100001770000000056114721727031024114 0ustar runnerdocker [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 4apache-log4cxx-1.3.1/src/test/resources/witness/hierarchyThreshold.70000644000175100001770000000034214721727031025072 0ustar runnerdockerTRACE HierarchyThresholdTestCase = m0 DEBUG HierarchyThresholdTestCase = m1 INFO HierarchyThresholdTestCase = m2 WARN HierarchyThresholdTestCase = m3 ERROR HierarchyThresholdTestCase = m4 FATAL HierarchyThresholdTestCase = m5 apache-log4cxx-1.3.1/src/test/resources/witness/messagebuffer.10000644000175100001770000000006514721727031024051 0ustar runnerdockerINFO - number in hex: dc INFO - number in dec: 220 apache-log4cxx-1.3.1/src/test/resources/witness/xmlLayout.mdc.20000644000175100001770000000053414721727031023775 0ustar runnerdocker apache-log4cxx-1.3.1/src/test/resources/witness/socketServer.80000644000175100001770000000374314721727031023727 0ustar runnerdockerTRACE some8 T8 shortSocketServer MDC-TEST8 [main] SocketServerTestCase - Message 1 TRACE some8 T8 shortSocketServer MDC-TEST8 [main] root - Message 2 DEBUG some8 T8 shortSocketServer MDC-TEST8 [main] SocketServerTestCase - Message 3 DEBUG some8 T8 shortSocketServer MDC-TEST8 [main] root - Message 4 INFO some8 T8 shortSocketServer MDC-TEST8 [main] SocketServerTestCase - Message 5 WARN some8 T8 shortSocketServer MDC-TEST8 [main] SocketServerTestCase - Message 6 FATAL some8 T8 shortSocketServer MDC-TEST8 [main] SocketServerTestCase - Message 7 DEBUG some8 T8 shortSocketServer MDC-TEST8 [main] SocketServerTestCase - Message 8 java.lang.Exception: Just testing at org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX) at org.apache.log4j.net.SocketServerTestCase.test8(SocketServerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) ERROR some8 T8 shortSocketServer MDC-TEST8 [main] root - Message 9 java.lang.Exception: Just testing at org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX) at org.apache.log4j.net.SocketServerTestCase.test8(SocketServerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4cxx-1.3.1/src/test/resources/witness/patternLayout.90000644000175100001770000000054714721727031024123 0ustar runnerdocker[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 4apache-log4cxx-1.3.1/src/test/resources/witness/socketServer.40000644000175100001770000000347014721727031023720 0ustar runnerdockerTRACE some T4 MDC-TEST4 [main] SocketServerTestCase - Message 1 TRACE some T4 MDC-TEST4 [main] root - Message 2 DEBUG some T4 MDC-TEST4 [main] SocketServerTestCase - Message 3 DEBUG some T4 MDC-TEST4 [main] root - Message 4 INFO some T4 MDC-TEST4 [main] SocketServerTestCase - Message 5 WARN some T4 MDC-TEST4 [main] SocketServerTestCase - Message 6 FATAL some T4 MDC-TEST4 [main] SocketServerTestCase - Message 7 DEBUG some T4 MDC-TEST4 [main] SocketServerTestCase - Message 8 java.lang.Exception: Just testing at org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX) at org.apache.log4j.net.SocketServerTestCase.test4(SocketServerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) ERROR some T4 MDC-TEST4 [main] root - Message 9 java.lang.Exception: Just testing at org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX) at org.apache.log4j.net.SocketServerTestCase.test4(SocketServerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4cxx-1.3.1/src/test/resources/witness/socketServer.70000644000175100001770000000366614721727031023732 0ustar runnerdockerTRACE some7 T7 client-test7 MDC-TEST7 [main] SocketServerTestCase - Message 1 TRACE some7 T7 client-test7 MDC-TEST7 [main] root - Message 2 DEBUG some7 T7 client-test7 MDC-TEST7 [main] SocketServerTestCase - Message 3 DEBUG some7 T7 client-test7 MDC-TEST7 [main] root - Message 4 INFO some7 T7 client-test7 MDC-TEST7 [main] SocketServerTestCase - Message 5 WARN some7 T7 client-test7 MDC-TEST7 [main] SocketServerTestCase - Message 6 FATAL some7 T7 client-test7 MDC-TEST7 [main] SocketServerTestCase - Message 7 DEBUG some7 T7 client-test7 MDC-TEST7 [main] SocketServerTestCase - Message 8 java.lang.Exception: Just testing at org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX) at org.apache.log4j.net.SocketServerTestCase.test7(SocketServerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) ERROR some7 T7 client-test7 MDC-TEST7 [main] root - Message 9 java.lang.Exception: Just testing at org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX) at org.apache.log4j.net.SocketServerTestCase.test7(SocketServerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4cxx-1.3.1/src/test/resources/witness/patternLayout.120000644000175100001770000000075114721727031024172 0ustar runnerdocker[main] DEBUG patternlayouttest.cpp(X): Message 0 [main] DEBUG patternlayouttest.cpp(X): Message 0 [main] INFO patternlayouttest.cpp(X): Message 1 [main] INFO patternlayouttest.cpp(X): Message 1 [main] WARN patternlayouttest.cpp(X): Message 2 [main] WARN patternlayouttest.cpp(X): Message 2 [main] ERROR patternlayouttest.cpp(X): Message 3 [main] ERROR patternlayouttest.cpp(X): Message 3 [main] FATAL patternlayouttest.cpp(X): Message 4 [main] FATAL patternlayouttest.cpp(X): Message 4apache-log4cxx-1.3.1/src/test/resources/witness/ndc/0000755000175100001770000000000014721727031021714 5ustar runnerdockerapache-log4cxx-1.3.1/src/test/resources/witness/ndc/NDC.10000644000175100001770000000104614721727031022403 0ustar runnerdockerDEBUG ndctest - m1 INFO ndctest - m2 WARN ndctest - m3 ERROR ndctest - m4 FATAL ndctest - m5 DEBUG ndctest n1 - m1 INFO ndctest n1 - m2 WARN ndctest n1 - m3 ERROR ndctest n1 - m4 FATAL ndctest n1 - m5 DEBUG ndctest n1 n2 n3 - m1 INFO ndctest n1 n2 n3 - m2 WARN ndctest n1 n2 n3 - m3 ERROR ndctest n1 n2 n3 - m4 FATAL ndctest n1 n2 n3 - m5 DEBUG ndctest n1 n2 - m1 INFO ndctest n1 n2 - m2 WARN ndctest n1 n2 - m3 ERROR ndctest n1 n2 - m4 FATAL ndctest n1 n2 - m5 DEBUG null - m1 INFO null - m2 WARN null - m3 ERROR null - m4 FATAL null - m5 apache-log4cxx-1.3.1/src/test/resources/witness/fallback10000644000175100001770000000061014721727031022710 0ustar runnerdockerFALLBACK - test - Message 0 FALLBACK - root - Message 0 FALLBACK - test - Message 1 FALLBACK - root - Message 1 FALLBACK - test - Message 2 FALLBACK - root - Message 2 FALLBACK - test - Message 3 FALLBACK - root - Message 3 FALLBACK - test - Message 4 FALLBACK - root - Message 4 FALLBACK - test - Message 5 FALLBACK - root - Message 5 FALLBACK - test - Message 6 FALLBACK - root - Message 6 apache-log4cxx-1.3.1/src/test/resources/witness/location1-disabled0000644000175100001770000000003614721727031024530 0ustar runnerdockerDEBUG[?](?)-1|?| - Message -1 apache-log4cxx-1.3.1/src/test/resources/witness/xmlLayout.10000644000175100001770000000522514721727031023234 0ustar runnerdocker apache-log4cxx-1.3.1/src/test/resources/witness/hierarchyThreshold.30000644000175100001770000000011414721727031025063 0ustar runnerdockerERROR HierarchyThresholdTestCase = m4 FATAL HierarchyThresholdTestCase = m5 apache-log4cxx-1.3.1/src/test/resources/witness/patternLayout.mdc.20000644000175100001770000000072714721727031024656 0ustar runnerdockerstarting 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-log4cxx-1.3.1/src/test/resources/witness/patternLayout.30000644000175100001770000000056114721727031024111 0ustar runnerdocker [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 4apache-log4cxx-1.3.1/src/test/resources/witness/customLevel.40000644000175100001770000000032214721727031023534 0ustar runnerdockerDEBUG xml.CustomLevelTestCase - Message 1 INFO xml.CustomLevelTestCase - Message 2 WARN xml.CustomLevelTestCase - Message 3 ERROR xml.CustomLevelTestCase - Message 4 TRACE xml.CustomLevelTestCase - Message 5 apache-log4cxx-1.3.1/src/test/resources/witness/LevelRangeFilter_accept0000644000175100001770000000523414721727031025610 0ustar runnerdockerDEBUG - pass 0; no min or max set INFO - pass 0; no min or max set WARN - pass 0; no min or max set ERROR - pass 0; no min or max set FATAL - pass 0; no min or max set WARN - pass 1; min set to WARN, max not set ERROR - pass 1; min set to WARN, max not set FATAL - pass 1; min set to WARN, max not set DEBUG - pass 2; min not set, max set to WARN INFO - pass 2; min not set, max set to WARN WARN - pass 2; min not set, max set to WARN DEBUG - pass 3; filter set to accept between DEBUG and FATAL msgs INFO - pass 3; filter set to accept between DEBUG and FATAL msgs WARN - pass 3; filter set to accept between DEBUG and FATAL msgs ERROR - pass 3; filter set to accept between DEBUG and FATAL msgs FATAL - pass 3; filter set to accept between DEBUG and FATAL msgs DEBUG - pass 4; filter set to accept between DEBUG and ERROR msgs INFO - pass 4; filter set to accept between DEBUG and ERROR msgs WARN - pass 4; filter set to accept between DEBUG and ERROR msgs ERROR - pass 4; filter set to accept between DEBUG and ERROR msgs DEBUG - pass 5; filter set to accept between DEBUG and WARN msgs INFO - pass 5; filter set to accept between DEBUG and WARN msgs WARN - pass 5; filter set to accept between DEBUG and WARN msgs DEBUG - pass 6; filter set to accept between DEBUG and INFO msgs INFO - pass 6; filter set to accept between DEBUG and INFO msgs DEBUG - pass 7; filter set to accept between DEBUG and DEBUG msgs INFO - pass 8; filter set to accept between INFO and FATAL msgs WARN - pass 8; filter set to accept between INFO and FATAL msgs ERROR - pass 8; filter set to accept between INFO and FATAL msgs FATAL - pass 8; filter set to accept between INFO and FATAL msgs INFO - pass 9; filter set to accept between INFO and ERROR msgs WARN - pass 9; filter set to accept between INFO and ERROR msgs ERROR - pass 9; filter set to accept between INFO and ERROR msgs INFO - pass 10; filter set to accept between INFO and WARN msgs WARN - pass 10; filter set to accept between INFO and WARN msgs INFO - pass 11; filter set to accept between INFO and INFO msgs WARN - pass 13; filter set to accept between WARN and FATAL msgs ERROR - pass 13; filter set to accept between WARN and FATAL msgs FATAL - pass 13; filter set to accept between WARN and FATAL msgs WARN - pass 14; filter set to accept between WARN and ERROR msgs ERROR - pass 14; filter set to accept between WARN and ERROR msgs WARN - pass 15; filter set to accept between WARN and WARN msgs ERROR - pass 18; filter set to accept between ERROR and FATAL msgs FATAL - pass 18; filter set to accept between ERROR and FATAL msgs ERROR - pass 19; filter set to accept between ERROR and ERROR msgs FATAL - pass 23; filter set to accept between FATAL and FATAL msgs apache-log4cxx-1.3.1/src/test/resources/witness/l7d.10000644000175100001770000000215714721727031021725 0ustar runnerdockerT1 INFO - This is the English, US test. T1 WARN - Hello world. T1 ERROR - No resource is associated with key "bogusMsg". T1 ERROR - bogusMsg T1 ERROR - This is test number 1 with string argument log4j. T1 ERROR - No resource is associated with key "bogus2". T1 INFO - bogus2 T1 ERROR - No resource is associated with key "msg3". T1 ERROR - msg3 T1 INFO - Ceci est le test en francais pour la France. T1 WARN - Bonjour la France. T1 ERROR - No resource is associated with key "bogusMsg". T1 ERROR - bogusMsg T1 ERROR - Ceci est le test numero 2 contenant l'argument log4j. T1 ERROR - No resource is associated with key "bogus2". T1 INFO - bogus2 T1 ERROR - Ceci est le test numero 2 contenant l'argument log4j et l'argument log4cxx. T1 INFO - Ceci est le test en francais pour la p'tite Suisse. T1 WARN - Bonjour la France. T1 ERROR - No resource is associated with key "bogusMsg". T1 ERROR - bogusMsg T1 ERROR - Ceci est le test numero 3 contenant l'argument log4j. T1 ERROR - No resource is associated with key "bogus2". T1 INFO - bogus2 T1 ERROR - Ceci est le test numero 3 contenant l'argument log4j et l'argument log4cxx. apache-log4cxx-1.3.1/src/test/resources/witness/NDCMatchFilter_deny0000644000175100001770000000222514721727031024642 0ustar runnerdockerpass 0: "level_1" does not exactly match "level_1 level_2 level_3" pass 0: "level_1" does not exactly match "level_1 level_2" pass 0: "level_1" does not exactly match "" pass 1: "level_1 level_2" does not exactly match "level_1 level_2 level_3" pass 1: "level_1 level_2" does not exactly match "level_1" pass 1: "level_1 level_2" does not exactly match "" pass 2: "level_1 level_2 level_3" does not exactly match "level_1 level_2" pass 2: "level_1 level_2 level_3" does not exactly match "level_1" pass 2: "level_1 level_2 level_3" does not exactly match "" pass 3: "level_1" not contained in "" pass 4: "level_1 level_2" not contained in "level_1" pass 4: "level_1 level_2" not contained in "" pass 5: "level_1 level_2 level_3" not contained in "level_1 level_2" pass 5: "level_1 level_2 level_3" not contained in "level_1" pass 5: "level_1 level_2 level_3" not contained in "" pass 6: "" does not exactly match "level_1 level_2 level_3" pass 6: "" does not exactly match "level_1 level_2" pass 6: "" does not exactly match "level_1" pass 7: "" not contained in "level_1 level_2 level_3" pass 7: "" not contained in "level_1 level_2" pass 7: "" not contained in "level_1" apache-log4cxx-1.3.1/src/test/resources/witness/hierarchyThreshold.20000644000175100001770000000004614721727031025066 0ustar runnerdockerFATAL HierarchyThresholdTestCase = m5 apache-log4cxx-1.3.1/src/test/resources/witness/patternLayout.130000644000175100001770000000041614721727031024171 0ustar runnerdockerDEBUG - 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 apache-log4cxx-1.3.1/src/test/resources/witness/socketServer.10000644000175100001770000000343514721727031023716 0ustar runnerdockerTRACE T1 [main] org.apache.log4j.net.SocketServerTestCase Message 1 TRACE T1 [main] root Message 2 DEBUG T1 [main] org.apache.log4j.net.SocketServerTestCase Message 3 DEBUG T1 [main] root Message 4 INFO T1 [main] org.apache.log4j.net.SocketServerTestCase Message 5 WARN T1 [main] org.apache.log4j.net.SocketServerTestCase Message 6 FATAL T1 [main] org.apache.log4j.net.SocketServerTestCase Message 7 DEBUG T1 [main] org.apache.log4j.net.SocketServerTestCase Message 8 java.lang.Exception: Just testing at org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX) at org.apache.log4j.net.SocketServerTestCase.test1(SocketServerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) ERROR T1 [main] root Message 9 java.lang.Exception: Just testing at org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX) at org.apache.log4j.net.SocketServerTestCase.test1(SocketServerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4cxx-1.3.1/src/test/resources/witness/patternLayout.20000644000175100001770000000056214721727031024111 0ustar runnerdocker [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 apache-log4cxx-1.3.1/src/test/resources/witness/rolling/0000755000175100001770000000000014721727031022616 5ustar runnerdockerapache-log4cxx-1.3.1/src/test/resources/witness/rolling/tbr-test5.30000644000175100001770000000010214721727031024524 0ustar runnerdockerTimeBasedRollingTest - Hello---4 TimeBasedRollingTest - Hello---5 apache-log4cxx-1.3.1/src/test/resources/witness/rolling/tbr-test3.30000644000175100001770000000004114721727031024524 0ustar runnerdockerTimeBasedRollingTest - Hello---4 apache-log4cxx-1.3.1/src/test/resources/witness/rolling/sbr-test3.0.gz0000644000175100001770000000010414721727031025137 0ustar runnerdocker$hAsbr-test3.0H54 ,#82L,38β,O dapache-log4cxx-1.3.1/src/test/resources/witness/rolling/tbr-test5.10000644000175100001770000000010214721727031024522 0ustar runnerdockerTimeBasedRollingTest - Hello---0 TimeBasedRollingTest - Hello---1 apache-log4cxx-1.3.1/src/test/resources/witness/rolling/sbr-test3.1.gz0000644000175100001770000000010414721727031025140 0ustar runnerdocker(hAsbr-test3.1H5 ,#82L,38β,`bdapache-log4cxx-1.3.1/src/test/resources/witness/rolling/tbr-test5.00000644000175100001770000000004114721727031024523 0ustar runnerdockerTimeBasedRollingTest - Hello---6 apache-log4cxx-1.3.1/src/test/resources/witness/rolling/tbr-test1.30000644000175100001770000000004114721727031024522 0ustar runnerdockerTimeBasedRollingTest - Hello---4 apache-log4cxx-1.3.1/src/test/resources/witness/rolling/tbr-test1.20000644000175100001770000000010214721727031024517 0ustar runnerdockerTimeBasedRollingTest - Hello---2 TimeBasedRollingTest - Hello---3 apache-log4cxx-1.3.1/src/test/resources/witness/rolling/tbr-test4.20000644000175100001770000000010214721727031024522 0ustar runnerdockerTimeBasedRollingTest - Hello---2 TimeBasedRollingTest - Hello---3 apache-log4cxx-1.3.1/src/test/resources/witness/rolling/tbr-test1.10000644000175100001770000000010214721727031024516 0ustar runnerdockerTimeBasedRollingTest - Hello---0 TimeBasedRollingTest - Hello---1 apache-log4cxx-1.3.1/src/test/resources/witness/rolling/tbr-test2.00000644000175100001770000000000014721727031024513 0ustar runnerdockerapache-log4cxx-1.3.1/src/test/resources/witness/rolling/sbr-test3.log0000644000175100001770000000006214721727031025145 0ustar runnerdockerHello--20 Hello--21 Hello--22 Hello--23 Hello--24 apache-log4cxx-1.3.1/src/test/resources/witness/rolling/tbr-test5.20000644000175100001770000000010214721727031024523 0ustar runnerdockerTimeBasedRollingTest - Hello---2 TimeBasedRollingTest - Hello---3 apache-log4cxx-1.3.1/src/test/resources/witness/rolling/tbr-test1.00000644000175100001770000000000014721727031024512 0ustar runnerdockerapache-log4cxx-1.3.1/src/test/resources/witness/rolling/sbr-test2.00000644000175100001770000000014414721727031024523 0ustar runnerdockerHello--10 Hello--11 Hello--12 Hello--13 Hello--14 Hello--15 Hello--16 Hello--17 Hello--18 Hello--19 apache-log4cxx-1.3.1/src/test/resources/witness/rolling/tbr-test4.00000644000175100001770000000004114721727031024522 0ustar runnerdockerTimeBasedRollingTest - Hello---6 apache-log4cxx-1.3.1/src/test/resources/witness/rolling/tbr-test4.10000644000175100001770000000010214721727031024521 0ustar runnerdockerTimeBasedRollingTest - Hello---0 TimeBasedRollingTest - Hello---1 apache-log4cxx-1.3.1/src/test/resources/witness/rolling/sbr-test2.log0000644000175100001770000000006214721727031025144 0ustar runnerdockerHello--20 Hello--21 Hello--22 Hello--23 Hello--24 apache-log4cxx-1.3.1/src/test/resources/witness/rolling/tbr-test4.30000644000175100001770000000010214721727031024523 0ustar runnerdockerTimeBasedRollingTest - Hello---4 TimeBasedRollingTest - Hello---5 apache-log4cxx-1.3.1/src/test/resources/witness/rolling/sbr-test4.log0000644000175100001770000000037214721727031025152 0ustar runnerdockerHello---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-log4cxx-1.3.1/src/test/resources/witness/rolling/tbr-test2.20000644000175100001770000000010214721727031024520 0ustar runnerdockerTimeBasedRollingTest - Hello---2 TimeBasedRollingTest - Hello---3 apache-log4cxx-1.3.1/src/test/resources/witness/rolling/tbr-test6.00000644000175100001770000000004114721727031024524 0ustar runnerdockerTimeBasedRollingTest - Hello---6 apache-log4cxx-1.3.1/src/test/resources/witness/rolling/tbr-test2.30000644000175100001770000000004114721727031024523 0ustar runnerdockerTimeBasedRollingTest - Hello---4 apache-log4cxx-1.3.1/src/test/resources/witness/rolling/tbr-test2.10000644000175100001770000000010214721727031024517 0ustar runnerdockerTimeBasedRollingTest - Hello---0 TimeBasedRollingTest - Hello---1 apache-log4cxx-1.3.1/src/test/resources/witness/rolling/sbr-test2.10000644000175100001770000000014414721727031024524 0ustar runnerdockerHello---0 Hello---1 Hello---2 Hello---3 Hello---4 Hello---5 Hello---6 Hello---7 Hello---8 Hello---9 apache-log4cxx-1.3.1/src/test/resources/witness/NDCMatchFilter_accept0000644000175100001770000000110314721727031025134 0ustar runnerdockerpass 0: "level_1" exactly matches "level_1" pass 1: "level_1 level_2" exactly matches "level_1 level_2" pass 2: "level_1 level_2 level_3" exactly matches "level_1 level_2 level_3" pass 3: "level_1" contained in "level_1 level_2 level_3" pass 3: "level_1" contained in "level_1 level_2" pass 3: "level_1" contained in "level_1" pass 4: "level_1 level_2" contained in "level_1 level_2 level_3" pass 4: "level_1 level_2" contained in "level_1 level_2" pass 5: "level_1 level_2 level_3" contained in "level_1 level_2 level_3" pass 6: "" exactly matches "" pass 7: "" contained in "" apache-log4cxx-1.3.1/src/test/resources/witness/LevelRangeFilter_neutral0000644000175100001770000000523414721727031026023 0ustar runnerdockerDEBUG - pass 0; no min or max set INFO - pass 0; no min or max set WARN - pass 0; no min or max set ERROR - pass 0; no min or max set FATAL - pass 0; no min or max set WARN - pass 1; min set to WARN, max not set ERROR - pass 1; min set to WARN, max not set FATAL - pass 1; min set to WARN, max not set DEBUG - pass 2; min not set, max set to WARN INFO - pass 2; min not set, max set to WARN WARN - pass 2; min not set, max set to WARN DEBUG - pass 3; filter set to accept between DEBUG and FATAL msgs INFO - pass 3; filter set to accept between DEBUG and FATAL msgs WARN - pass 3; filter set to accept between DEBUG and FATAL msgs ERROR - pass 3; filter set to accept between DEBUG and FATAL msgs FATAL - pass 3; filter set to accept between DEBUG and FATAL msgs DEBUG - pass 4; filter set to accept between DEBUG and ERROR msgs INFO - pass 4; filter set to accept between DEBUG and ERROR msgs WARN - pass 4; filter set to accept between DEBUG and ERROR msgs ERROR - pass 4; filter set to accept between DEBUG and ERROR msgs DEBUG - pass 5; filter set to accept between DEBUG and WARN msgs INFO - pass 5; filter set to accept between DEBUG and WARN msgs WARN - pass 5; filter set to accept between DEBUG and WARN msgs DEBUG - pass 6; filter set to accept between DEBUG and INFO msgs INFO - pass 6; filter set to accept between DEBUG and INFO msgs DEBUG - pass 7; filter set to accept between DEBUG and DEBUG msgs INFO - pass 8; filter set to accept between INFO and FATAL msgs WARN - pass 8; filter set to accept between INFO and FATAL msgs ERROR - pass 8; filter set to accept between INFO and FATAL msgs FATAL - pass 8; filter set to accept between INFO and FATAL msgs INFO - pass 9; filter set to accept between INFO and ERROR msgs WARN - pass 9; filter set to accept between INFO and ERROR msgs ERROR - pass 9; filter set to accept between INFO and ERROR msgs INFO - pass 10; filter set to accept between INFO and WARN msgs WARN - pass 10; filter set to accept between INFO and WARN msgs INFO - pass 11; filter set to accept between INFO and INFO msgs WARN - pass 13; filter set to accept between WARN and FATAL msgs ERROR - pass 13; filter set to accept between WARN and FATAL msgs FATAL - pass 13; filter set to accept between WARN and FATAL msgs WARN - pass 14; filter set to accept between WARN and ERROR msgs ERROR - pass 14; filter set to accept between WARN and ERROR msgs WARN - pass 15; filter set to accept between WARN and WARN msgs ERROR - pass 18; filter set to accept between ERROR and FATAL msgs FATAL - pass 18; filter set to accept between ERROR and FATAL msgs ERROR - pass 19; filter set to accept between ERROR and ERROR msgs FATAL - pass 23; filter set to accept between FATAL and FATAL msgs apache-log4cxx-1.3.1/src/test/resources/witness/simple0000644000175100001770000000075014721727031022366 0ustar runnerdockerFATAL - Message 0 ERROR - Message 1 FATAL - Message 2 ERROR - Message 3 WARN - Message 4 INFO - Message 5 FATAL - Message 6 ERROR - Message 7 WARN - Message 8 INFO - Message 9 FATAL - Message 10 ERROR - Message 11 FATAL - Message 12 ERROR - Message 13 FATAL - Message 14 ERROR - Message 15 WARN - Message 16 INFO - Message 17 DEBUG - Message 18 FATAL - Message 19 ERROR - Message 20 WARN - Message 21 INFO - Message 22 DEBUG - Message 23 INFO - Messages should bear numbers 0 through 23. apache-log4cxx-1.3.1/src/test/resources/witness/LevelMatchFilter_deny0000644000175100001770000000175414721727031025313 0ustar runnerdockerINFO - pass 0; filter set to deny only DEBUG msgs WARN - pass 0; filter set to deny only DEBUG msgs ERROR - pass 0; filter set to deny only DEBUG msgs FATAL - pass 0; filter set to deny only DEBUG msgs DEBUG - pass 1; filter set to deny only INFO msgs WARN - pass 1; filter set to deny only INFO msgs ERROR - pass 1; filter set to deny only INFO msgs FATAL - pass 1; filter set to deny only INFO msgs DEBUG - pass 2; filter set to deny only WARN msgs INFO - pass 2; filter set to deny only WARN msgs ERROR - pass 2; filter set to deny only WARN msgs FATAL - pass 2; filter set to deny only WARN msgs DEBUG - pass 3; filter set to deny only ERROR msgs INFO - pass 3; filter set to deny only ERROR msgs WARN - pass 3; filter set to deny only ERROR msgs FATAL - pass 3; filter set to deny only ERROR msgs DEBUG - pass 4; filter set to deny only FATAL msgs INFO - pass 4; filter set to deny only FATAL msgs WARN - pass 4; filter set to deny only FATAL msgs ERROR - pass 4; filter set to deny only FATAL msgs apache-log4cxx-1.3.1/src/test/resources/witness/LevelMatchFilter_accept0000644000175100001770000000040514721727031025603 0ustar runnerdockerDEBUG - pass 0; filter set to accept only DEBUG msgs INFO - pass 1; filter set to accept only INFO msgs WARN - pass 2; filter set to accept only WARN msgs ERROR - pass 3; filter set to accept only ERROR msgs FATAL - pass 4; filter set to accept only FATAL msgs apache-log4cxx-1.3.1/src/test/resources/witness/dom.A2.10000644000175100001770000000067614721727031022263 0ustar runnerdocker [main] DEBUG org.apache.log4j.xml.DOMTestCase - Message 0 [main] DEBUG root - Message 0 [main] INFO org.apache.log4j.xml.DOMTestCase - Message 1 [main] INFO root - Message 1 [main] WARN org.apache.log4j.xml.DOMTestCase - Message 2 [main] WARN root - Message 2 [main] ERROR org.apache.log4j.xml.DOMTestCase - Message 3 [main] ERROR root - Message 3 [main] FATAL org.apache.log4j.xml.DOMTestCase - Message 4 [main] FATAL root - Message 4 apache-log4cxx-1.3.1/src/test/resources/witness/patternLayout.50000644000175100001770000000056114721727031024113 0ustar runnerdocker [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 4apache-log4cxx-1.3.1/src/test/resources/witness/socketServer.50000644000175100001770000000350114721727031023714 0ustar runnerdockerTRACE some5 T5 MDC-TEST5 [main] SocketServerTestCase - Message 1 TRACE some5 T5 MDC-TEST5 [main] root - Message 2 DEBUG some5 T5 MDC-TEST5 [main] SocketServerTestCase - Message 3 DEBUG some5 T5 MDC-TEST5 [main] root - Message 4 INFO some5 T5 MDC-TEST5 [main] SocketServerTestCase - Message 5 WARN some5 T5 MDC-TEST5 [main] SocketServerTestCase - Message 6 FATAL some5 T5 MDC-TEST5 [main] SocketServerTestCase - Message 7 DEBUG some5 T5 MDC-TEST5 [main] SocketServerTestCase - Message 8 java.lang.Exception: Just testing at org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX) at org.apache.log4j.net.SocketServerTestCase.test5(SocketServerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) ERROR some5 T5 MDC-TEST5 [main] root - Message 9 java.lang.Exception: Just testing at org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX) at org.apache.log4j.net.SocketServerTestCase.test5(SocketServerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4cxx-1.3.1/src/test/resources/witness/xmlLayout.30000644000175100001770000000124614721727031023235 0ustar runnerdocker hi]]>]]> hi]]>]]> apache-log4cxx-1.3.1/src/test/resources/witness/patternLayout.80000644000175100001770000000054714721727031024122 0ustar runnerdocker[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 4apache-log4cxx-1.3.1/src/test/resources/witness/customLogger.20000644000175100001770000000005714721727031023707 0ustar runnerdockerTRACE customLogger.XLoggerTestCase - Message 0 apache-log4cxx-1.3.1/src/test/resources/witness/customLogger.10000644000175100001770000000043214721727031023703 0ustar runnerdockerTRACE customLogger.XLoggerTestCase - Message 0 DEBUG customLogger.XLoggerTestCase - Message 1 WARN customLogger.XLoggerTestCase - Message 2 ERROR customLogger.XLoggerTestCase - Message 3 FATAL customLogger.XLoggerTestCase - Message 4 DEBUG customLogger.XLoggerTestCase - Message 5 apache-log4cxx-1.3.1/src/test/resources/witness/socketServer.30000644000175100001770000000366614721727031023726 0ustar runnerdockerTRACE T3 [main] SocketServerTestCase (socketservertestcase.cpp:XXX) Message 1 TRACE T3 [main] root (socketservertestcase.cpp:XXX) Message 2 DEBUG T3 [main] SocketServerTestCase (socketservertestcase.cpp:XXX) Message 3 DEBUG T3 [main] root (socketservertestcase.cpp:XXX) Message 4 INFO T3 [main] SocketServerTestCase (socketservertestcase.cpp:XXX) Message 5 WARN T3 [main] SocketServerTestCase (socketservertestcase.cpp:XXX) Message 6 FATAL T3 [main] SocketServerTestCase (socketservertestcase.cpp:XXX) Message 7 DEBUG T3 [main] SocketServerTestCase (socketservertestcase.cpp:XXX) Message 8 java.lang.Exception: Just testing at org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX) at org.apache.log4j.net.SocketServerTestCase.test3(SocketServerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) ERROR T3 [main] root (socketservertestcase.cpp:XXX) Message 9 java.lang.Exception: Just testing at org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX) at org.apache.log4j.net.SocketServerTestCase.test3(SocketServerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4cxx-1.3.1/src/test/resources/witness/location1-good0000644000175100001770000000004514721727031023711 0ustar runnerdockerDEBUG(locationtest.cpp) - Message -1 apache-log4cxx-1.3.1/src/test/resources/witness/hierarchyThreshold.10000644000175100001770000000000014721727031025053 0ustar runnerdockerapache-log4cxx-1.3.1/src/test/resources/witness/patternLayout.10000644000175100001770000000026414721727031024107 0ustar runnerdockerDEBUG - 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 apache-log4cxx-1.3.1/src/test/resources/witness/hierarchyThreshold.50000644000175100001770000000022614721727031025071 0ustar runnerdockerINFO HierarchyThresholdTestCase = m2 WARN HierarchyThresholdTestCase = m3 ERROR HierarchyThresholdTestCase = m4 FATAL HierarchyThresholdTestCase = m5 apache-log4cxx-1.3.1/src/test/resources/witness/customLevel.30000644000175100001770000000005214721727031023533 0ustar runnerdockerTRACE xml.CustomLevelTestCase - Message 5 apache-log4cxx-1.3.1/src/test/resources/witness/xmlLayout.null0000644000175100001770000000077214721727031024050 0ustar runnerdocker apache-log4cxx-1.3.1/src/test/resources/witness/socketServer.20000644000175100001770000000366614721727031023725 0ustar runnerdockerTRACE T2 [main] SocketServerTestCase (socketservertestcase.cpp:XXX) Message 1 TRACE T2 [main] root (socketservertestcase.cpp:XXX) Message 2 DEBUG T2 [main] SocketServerTestCase (socketservertestcase.cpp:XXX) Message 3 DEBUG T2 [main] root (socketservertestcase.cpp:XXX) Message 4 INFO T2 [main] SocketServerTestCase (socketservertestcase.cpp:XXX) Message 5 WARN T2 [main] SocketServerTestCase (socketservertestcase.cpp:XXX) Message 6 FATAL T2 [main] SocketServerTestCase (socketservertestcase.cpp:XXX) Message 7 DEBUG T2 [main] SocketServerTestCase (socketservertestcase.cpp:XXX) Message 8 java.lang.Exception: Just testing at org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX) at org.apache.log4j.net.SocketServerTestCase.test2(SocketServerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) ERROR T2 [main] root (socketservertestcase.cpp:XXX) Message 9 java.lang.Exception: Just testing at org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX) at org.apache.log4j.net.SocketServerTestCase.test2(SocketServerTestCase.java:XXX) at junit.framework.TestCase.runTest(TestCase.java:XXX) at junit.framework.TestCase.runBare(TestCase.java:XXX) at junit.framework.TestResult$1.protect(TestResult.java:XXX) at junit.framework.TestResult.runProtected(TestResult.java:XXX) at junit.framework.TestResult.run(TestResult.java:XXX) at junit.framework.TestCase.run(TestCase.java:XXX) at junit.framework.TestSuite.runTest(TestSuite.java:XXX) at junit.framework.TestSuite.run(TestSuite.java:XXX) apache-log4cxx-1.3.1/src/test/resources/witness/threadnametestcase.10000644000175100001770000000002514721727031025073 0ustar runnerdockerFooName Test message apache-log4cxx-1.3.1/src/test/resources/witness/hierarchyThreshold.60000644000175100001770000000027414721727031025075 0ustar runnerdockerDEBUG HierarchyThresholdTestCase = m1 INFO HierarchyThresholdTestCase = m2 WARN HierarchyThresholdTestCase = m3 ERROR HierarchyThresholdTestCase = m4 FATAL HierarchyThresholdTestCase = m5 apache-log4cxx-1.3.1/src/test/resources/witness/patternLayout.140000644000175100001770000000060614721727031024173 0ustar runnerdockerDEBUG patternlayouttest.cpp: Message 0 DEBUG patternlayouttest.cpp: Message 0 INFO patternlayouttest.cpp: Message 1 INFO patternlayouttest.cpp: Message 1 WARN patternlayouttest.cpp: Message 2 WARN patternlayouttest.cpp: Message 2 ERROR patternlayouttest.cpp: Message 3 ERROR patternlayouttest.cpp: Message 3 FATAL patternlayouttest.cpp: Message 4 FATAL patternlayouttest.cpp: Message 4 apache-log4cxx-1.3.1/src/test/resources/witness/patternLayout.100000644000175100001770000000075114721727031024170 0ustar runnerdocker[main] DEBUG patternlayouttest.cpp(X): Message 0 [main] DEBUG patternlayouttest.cpp(X): Message 0 [main] INFO patternlayouttest.cpp(X): Message 1 [main] INFO patternlayouttest.cpp(X): Message 1 [main] WARN patternlayouttest.cpp(X): Message 2 [main] WARN patternlayouttest.cpp(X): Message 2 [main] ERROR patternlayouttest.cpp(X): Message 3 [main] ERROR patternlayouttest.cpp(X): Message 3 [main] FATAL patternlayouttest.cpp(X): Message 4 [main] FATAL patternlayouttest.cpp(X): Message 4apache-log4cxx-1.3.1/src/test/resources/witness/customLevel.10000644000175100001770000000032214721727031023531 0ustar runnerdockerDEBUG xml.CustomLevelTestCase - Message 1 INFO xml.CustomLevelTestCase - Message 2 WARN xml.CustomLevelTestCase - Message 3 ERROR xml.CustomLevelTestCase - Message 4 TRACE xml.CustomLevelTestCase - Message 5 apache-log4cxx-1.3.1/src/test/resources/witness/hierarchyThreshold.80000644000175100001770000000034214721727031025073 0ustar runnerdockerTRACE HierarchyThresholdTestCase = m0 DEBUG HierarchyThresholdTestCase = m1 INFO HierarchyThresholdTestCase = m2 WARN HierarchyThresholdTestCase = m3 ERROR HierarchyThresholdTestCase = m4 FATAL HierarchyThresholdTestCase = m5 apache-log4cxx-1.3.1/src/test/resources/witness/patternLayout.mdc.10000644000175100001770000000005514721727031024647 0ustar runnerdockerDEBUG - Hello World {{key1,va11}{key2,va12}} apache-log4cxx-1.3.1/src/test/resources/witness/dom.A1.10000644000175100001770000000070714721727031022255 0ustar runnerdockerDEBUG xml.DOMTestCase - Message 0 DEBUG xml.DOMTestCase - Message 0 DEBUG root - Message 0 INFO xml.DOMTestCase - Message 1 INFO xml.DOMTestCase - Message 1 INFO root - Message 1 WARN xml.DOMTestCase - Message 2 WARN xml.DOMTestCase - Message 2 WARN root - Message 2 ERROR xml.DOMTestCase - Message 3 ERROR xml.DOMTestCase - Message 3 ERROR root - Message 3 FATAL xml.DOMTestCase - Message 4 FATAL xml.DOMTestCase - Message 4 FATAL root - Message 4 apache-log4cxx-1.3.1/src/test/resources/witness/dom.A2.20000644000175100001770000000067614721727031022264 0ustar runnerdocker [main] DEBUG org.apache.log4j.xml.DOMTestCase - Message 0 [main] DEBUG root - Message 0 [main] INFO org.apache.log4j.xml.DOMTestCase - Message 1 [main] INFO root - Message 1 [main] WARN org.apache.log4j.xml.DOMTestCase - Message 2 [main] WARN root - Message 2 [main] ERROR org.apache.log4j.xml.DOMTestCase - Message 3 [main] ERROR root - Message 3 [main] FATAL org.apache.log4j.xml.DOMTestCase - Message 4 [main] FATAL root - Message 4 apache-log4cxx-1.3.1/src/test/resources/witness/hierarchyThreshold.40000644000175100001770000000016114721727031025066 0ustar runnerdockerWARN HierarchyThresholdTestCase = m3 ERROR HierarchyThresholdTestCase = m4 FATAL HierarchyThresholdTestCase = m5 apache-log4cxx-1.3.1/src/test/resources/witness/customLevel.20000644000175100001770000000032214721727031023532 0ustar runnerdockerDEBUG xml.CustomLevelTestCase - Message 1 INFO xml.CustomLevelTestCase - Message 2 WARN xml.CustomLevelTestCase - Message 3 ERROR xml.CustomLevelTestCase - Message 4 TRACE xml.CustomLevelTestCase - Message 5 apache-log4cxx-1.3.1/src/test/resources/witness/xmlLayout.20000644000175100001770000001052714721727031023236 0ustar runnerdocker apache-log4cxx-1.3.1/src/test/resources/witness/patternLayout.110000644000175100001770000000060014721727031024162 0ustar runnerdockerDEBUG [main] log4j.PatternLayoutTest: Message 0 DEBUG [main] root: Message 0 INFO [main] log4j.PatternLayoutTest: Message 1 INFO [main] root: Message 1 WARN [main] log4j.PatternLayoutTest: Message 2 WARN [main] root: Message 2 ERROR [main] log4j.PatternLayoutTest: Message 3 ERROR [main] root: Message 3 FATAL [main] log4j.PatternLayoutTest: Message 4 FATAL [main] root: Message 4apache-log4cxx-1.3.1/src/test/resources/witness/patternLayout.70000644000175100001770000000056114721727031024115 0ustar runnerdocker [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 4apache-log4cxx-1.3.1/src/test/CMakeLists.txt0000644000175100001770000000145214721727031020204 0ustar runnerdocker# # 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. # add_subdirectory(cpp) apache-log4cxx-1.3.1/src/test/cpp/0000755000175100001770000000000014721727031016224 5ustar runnerdockerapache-log4cxx-1.3.1/src/test/cpp/abts.h0000644000175100001770000000641514721727031017334 0ustar runnerdocker/* Copyright 2000-2004 Ryan Bloom * * 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. */ #include #include #include #include #include #include #ifdef _WIN32 #include #else #include #endif #ifndef ABTS_H #define ABTS_H #ifndef FALSE #define FALSE 0 #endif #ifndef TRUE #define TRUE 1 #endif struct sub_suite { std::string name; int num_test; std::vector failed; int not_run; int not_impl; struct sub_suite* next; }; typedef struct sub_suite sub_suite; struct abts_suite { sub_suite* head; sub_suite* tail; }; typedef struct abts_suite abts_suite; struct abts_case { int failed; sub_suite* suite; }; typedef struct abts_case abts_case; typedef void (*test_func)(abts_case* tc, void* data); #define ADD_SUITE(suite) abts_add_suite(suite, __FILE__); abts_suite* abts_add_suite(abts_suite* suite, const char* suite_name); void abts_run_test(abts_suite* ts, const char* name, test_func f, void* value); void abts_log_message(const char* fmt, ...); void abts_int_equal(abts_case* tc, const int expected, const int actual, int lineno); void abts_int_nequal(abts_case* tc, const int expected, const int actual, int lineno); void abts_str_equal(abts_case* tc, const char* expected, const char* actual, int lineno); void abts_str_nequal(abts_case* tc, const char* expected, const char* actual, size_t n, int lineno); void abts_ptr_notnull(abts_case* tc, const void* ptr, int lineno); void abts_ptr_equal(abts_case* tc, const void* expected, const void* actual, int lineno); void abts_true(abts_case* tc, int condition, int lineno); void abts_fail(abts_case* tc, const char* message, int lineno); void abts_not_impl(abts_case* tc, const char* message, int lineno); void abts_assert(abts_case* tc, const char* message, int condition, int lineno); void abts_size_equal(abts_case* tc, size_t expected, size_t actual, int lineno); /* Convenience macros. Ryan hates these! */ #define ABTS_INT_EQUAL(a, b, c) abts_int_equal(a, b, c, __LINE__) #define ABTS_INT_NEQUAL(a, b, c) abts_int_nequal(a, b, c, __LINE__) #define ABTS_STR_EQUAL(a, b, c) abts_str_equal(a, b, c, __LINE__) #define ABTS_STR_NEQUAL(a, b, c, d) abts_str_nequal(a, b, c, d, __LINE__) #define ABTS_PTR_NOTNULL(a, b) abts_ptr_notnull(a, b, __LINE__) #define ABTS_PTR_EQUAL(a, b, c) abts_ptr_equal(a, b, c, __LINE__) #define ABTS_TRUE(a, b) abts_true(a, b, __LINE__); #define ABTS_FAIL(a, b) abts_fail(a, b, __LINE__); #define ABTS_NOT_IMPL(a, b) abts_not_impl(a, b, __LINE__); #define ABTS_ASSERT(a, b, c) abts_assert(a, b, c, __LINE__); #define ABTS_SIZE_EQUAL(a, b, c) abts_size_equal(a, b, c, __LINE__) abts_suite* run_tests(abts_suite* suite); abts_suite* run_tests1(abts_suite* suite); #endif apache-log4cxx-1.3.1/src/test/cpp/jsonlayouttest.cpp0000644000175100001770000003066114721727031022045 0ustar runnerdocker/* * 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. */ #include "logunit.h" #include #include #include #include #include #include using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::spi; #if defined(__LOG4CXX_FUNC__) #undef __LOG4CXX_FUNC__ #define __LOG4CXX_FUNC__ "X::X()" #else #error __LOG4CXX_FUNC__ expected to be defined #endif static LogString ppIndentL1(LOG4CXX_STR(" ")); static LogString ppIndentL2(LOG4CXX_STR(" ")); /** * Test for JSONLayout. * */ LOGUNIT_CLASS(JSONLayoutTest), public JSONLayout { LOGUNIT_TEST_SUITE(JSONLayoutTest); LOGUNIT_TEST(testGetContentType); LOGUNIT_TEST(testIgnoresThrowable); LOGUNIT_TEST(testAppendQuotedEscapedStringWithPrintableChars); LOGUNIT_TEST(testAppendQuotedEscapedStringWithControlChars); LOGUNIT_TEST(testAppendSerializedMDC); LOGUNIT_TEST(testAppendSerializedMDCWithPrettyPrint); LOGUNIT_TEST(testAppendSerializedNDC); LOGUNIT_TEST(testAppendSerializedNDCWithPrettyPrint); LOGUNIT_TEST(testAppendSerializedLocationInfo); LOGUNIT_TEST(testAppendSerializedLocationInfoWithPrettyPrint); LOGUNIT_TEST(testFormat); LOGUNIT_TEST(testFormatWithPrettyPrint); LOGUNIT_TEST(testGetSetLocationInfo); LOGUNIT_TEST_SUITE_END(); public: /** * Clear MDC and NDC before test. */ void setUp() { NDC::clear(); MDC::clear(); } /** * Clear MDC and NDC after test. */ void tearDown() { setUp(); } public: /** * Tests getContentType. */ void testGetContentType() { LogString expected(LOG4CXX_STR("application/json")); LogString actual(JSONLayout().getContentType()); LOGUNIT_ASSERT(expected == actual); } /** * Tests ignoresThrowable. */ void testIgnoresThrowable() { LOGUNIT_ASSERT_EQUAL(false, JSONLayout().ignoresThrowable()); } /** * Tests appendQuotedEscapedString with printable characters. */ void testAppendQuotedEscapedStringWithPrintableChars() { LogString s1(LOG4CXX_STR("foo")); /* foo */ LogString s2; appendQuotedEscapedString(s2, s1); /* "foo" */ LOGUNIT_ASSERT_EQUAL(LOG4CXX_STR("\"foo\""), s2); LogString s3; appendQuotedEscapedString(s3, s2); /* "\"foo\"" */ LOGUNIT_ASSERT_EQUAL(LOG4CXX_STR("\"\\\"foo\\\"\""), s3); LogString t1(LOG4CXX_STR("bar\"baz")); /* bar"baz */ LogString t2; appendQuotedEscapedString(t2, t1); /* "bar\"baz" */ LOGUNIT_ASSERT_EQUAL(LOG4CXX_STR("\"bar\\\"baz\""), t2); LogString t3; appendQuotedEscapedString(t3, t2); /* "\"bar\\\"baz\"" */ LOGUNIT_ASSERT_EQUAL(LOG4CXX_STR("\"\\\"bar\\\\\\\"baz\\\"\""), t3); } /** * Tests appendQuotedEscapedString with control characters. */ void testAppendQuotedEscapedStringWithControlChars() { logchar bs[] = {0x08, 0x00}; logchar bs_expected[] = {0x22, 0x5c, 'b', 0x22, 0x00}; /* "\b" */ LogString bs_escaped; appendQuotedEscapedString(bs_escaped, bs); LOGUNIT_ASSERT_EQUAL(bs_expected, bs_escaped); logchar tab[] = {0x09, 0x00}; logchar tab_expected[] = {0x22, 0x5c, 't', 0x22, 0x00}; /* "\t" */ LogString tab_escaped; appendQuotedEscapedString(tab_escaped, tab); LOGUNIT_ASSERT_EQUAL(tab_expected, tab_escaped); logchar newline[] = {0x0a, 0x00}; logchar newline_expected[] = {0x22, 0x5c, 'n', 0x22, 0x00}; /* "\n" */ LogString newline_escaped; appendQuotedEscapedString(newline_escaped, newline); LOGUNIT_ASSERT_EQUAL(newline_expected, newline_escaped); logchar ff[] = {0x0c, 0x00}; logchar ff_expected[] = {0x22, 0x5c, 'f', 0x22, 0x00}; /* "\f" */ LogString ff_escaped; appendQuotedEscapedString(ff_escaped, ff); LOGUNIT_ASSERT_EQUAL(ff_expected, ff_escaped); logchar cr[] = {0x0d, 0x00}; logchar cr_expected[] = {0x22, 0x5c, 'r', 0x22, 0x00}; /* "\r" */ LogString cr_escaped; appendQuotedEscapedString(cr_escaped, cr); LOGUNIT_ASSERT_EQUAL(cr_expected, cr_escaped); } /** * Tests appendSerializedMDC. */ void testAppendSerializedMDC() { LoggingEventPtr event1 = LoggingEventPtr(new LoggingEvent(LOG4CXX_STR("Logger"), Level::getInfo(), LOG4CXX_STR("A message goes here."), LOG4CXX_LOCATION)); MDC::put("key1", "value1"); MDC::put("key2", "value2"); LogString output1; LogString expected1 = LOG4CXX_STR(", \"context_map\": { " "\"key1\": \"value1\", \"key2\": \"value2\" }"); appendSerializedMDC(output1, event1); LOGUNIT_ASSERT_EQUAL(expected1, output1); } /** * Tests appendSerializedMDC with prettyPrint set to true. */ void testAppendSerializedMDCWithPrettyPrint() { LoggingEventPtr event1 = LoggingEventPtr(new LoggingEvent(LOG4CXX_STR("Logger"), Level::getInfo(), LOG4CXX_STR("A message goes here."), LOG4CXX_LOCATION)); MDC::put("key1", "value1"); MDC::put("key2", "value2"); LogString output1; LogString expected1; expected1 .append(LOG4CXX_STR(",")) .append(LOG4CXX_EOL) .append(ppIndentL1) .append(LOG4CXX_STR("\"context_map\": {")) .append(LOG4CXX_EOL) .append(ppIndentL2) .append(LOG4CXX_STR("\"key1\": \"value1\",")) .append(LOG4CXX_EOL) .append(ppIndentL2) .append(LOG4CXX_STR("\"key2\": \"value2\"")) .append(LOG4CXX_EOL) .append(ppIndentL1) .append(LOG4CXX_STR("}")); setPrettyPrint(true); appendSerializedMDC(output1, event1); LOGUNIT_ASSERT_EQUAL(expected1, output1); } /** * Tests appendSerializedNDC. */ void testAppendSerializedNDC() { LoggingEventPtr event1 = LoggingEventPtr(new LoggingEvent(LOG4CXX_STR("Logger"), Level::getInfo(), LOG4CXX_STR("A message goes here."), LOG4CXX_LOCATION)); NDC::push("one"); NDC::push("two"); NDC::push("three"); LogString output1; LogString expected1 = LOG4CXX_STR(", \"context_stack\": [ \"one two three\" ]"); appendSerializedNDC(output1, event1); LOGUNIT_ASSERT_EQUAL(expected1, output1); } /** * Tests appendSerializedNDC with prettyPrint set to true. */ void testAppendSerializedNDCWithPrettyPrint() { LoggingEventPtr event1 = LoggingEventPtr(new LoggingEvent(LOG4CXX_STR("Logger"), Level::getInfo(), LOG4CXX_STR("A message goes here."), LOG4CXX_LOCATION)); NDC::push("one"); NDC::push("two"); NDC::push("three"); LogString output1; LogString expected1; expected1 .append(LOG4CXX_STR(",")) .append(LOG4CXX_EOL) .append(ppIndentL1) .append(LOG4CXX_STR("\"context_stack\": [")) .append(LOG4CXX_EOL) .append(ppIndentL2) .append(LOG4CXX_STR("\"one two three\"")) .append(LOG4CXX_EOL) .append(ppIndentL1) .append(LOG4CXX_STR("]")); setPrettyPrint(true); appendSerializedNDC(output1, event1); LOGUNIT_ASSERT_EQUAL(expected1, output1); } /** * Tests appendSerializedLocationInfo. */ void testAppendSerializedLocationInfo() { Pool p; LoggingEventPtr event1 = LoggingEventPtr(new LoggingEvent(LOG4CXX_STR("Logger"), Level::getInfo(), LOG4CXX_STR("A message goes here."), spi::LocationInfo("FooFile", "FooFile", "BarFunc", 42))); LogString output1; LogString expected1; expected1 .append(LOG4CXX_STR("\"location_info\": { ")) .append(LOG4CXX_STR("\"file\": \"FooFile\", ")) .append(LOG4CXX_STR("\"line\": \"42\", ")) .append(LOG4CXX_STR("\"class\": \"\", ")) .append(LOG4CXX_STR("\"method\": \"BarFunc\" }")); appendSerializedLocationInfo(output1, event1, p); LOGUNIT_ASSERT_EQUAL(expected1, output1); } /** * Tests appendSerializedLocationInfo with prettyPrint set to true. */ void testAppendSerializedLocationInfoWithPrettyPrint() { Pool p; LoggingEventPtr event1 = LoggingEventPtr(new LoggingEvent(LOG4CXX_STR("Logger"), Level::getInfo(), LOG4CXX_STR("A message goes here."), spi::LocationInfo("FooFile", "FooFile", "BarFunc", 42))); LogString output1; LogString expected1; expected1 .append(ppIndentL1) .append(LOG4CXX_STR("\"location_info\": {")) .append(LOG4CXX_EOL) .append(ppIndentL2) .append(LOG4CXX_STR("\"file\": \"FooFile\",")) .append(LOG4CXX_EOL) .append(ppIndentL2) .append(LOG4CXX_STR("\"line\": \"42\",")) .append(LOG4CXX_EOL) .append(ppIndentL2) .append(LOG4CXX_STR("\"class\": \"\",")) .append(LOG4CXX_EOL) .append(ppIndentL2) .append(LOG4CXX_STR("\"method\": \"BarFunc\"")) .append(LOG4CXX_EOL) .append(ppIndentL1) .append(LOG4CXX_STR("}")); setPrettyPrint(true); appendSerializedLocationInfo(output1, event1, p); LOGUNIT_ASSERT_EQUAL(expected1, output1); } /** * Tests format. */ void testFormat() { Pool p; LoggingEventPtr event1 = LoggingEventPtr(new LoggingEvent(LOG4CXX_STR("Logger"), Level::getInfo(), LOG4CXX_STR("A message goes here."), spi::LocationInfo("FooFile", "FooFile", "BarFunc", 42))); LogString timestamp; helpers::ISO8601DateFormat dateFormat; dateFormat.format(timestamp, event1->getTimeStamp(), p); NDC::push("one"); NDC::push("two"); NDC::push("three"); MDC::put("key1", "value1"); MDC::put("key2", "value2"); LogString output1; LogString expected1; expected1 .append(LOG4CXX_STR("{ \"timestamp\": \"")) .append(timestamp) .append(LOG4CXX_STR("\", ")) .append(LOG4CXX_STR("\"level\": \"INFO\", ")) .append(LOG4CXX_STR("\"logger\": \"Logger\", ")) .append(LOG4CXX_STR("\"message\": \"A message goes here.\"")); setLocationInfo(true); appendSerializedMDC(expected1, event1); appendSerializedNDC(expected1, event1); expected1.append(LOG4CXX_STR(", ")); appendSerializedLocationInfo(expected1, event1, p); expected1.append(LOG4CXX_STR(" }")); expected1.append(LOG4CXX_EOL); format(output1, event1, p); LOGUNIT_ASSERT_EQUAL(expected1, output1); } /** * Tests format with PrettyPrint set to true. */ void testFormatWithPrettyPrint() { Pool p; LoggingEventPtr event1 = LoggingEventPtr(new LoggingEvent(LOG4CXX_STR("Logger"), Level::getInfo(), LOG4CXX_STR("A message goes here."), spi::LocationInfo("FooFile", "FooFile", "BarFunc", 42))); LogString timestamp; helpers::ISO8601DateFormat dateFormat; dateFormat.format(timestamp, event1->getTimeStamp(), p); NDC::push("one"); NDC::push("two"); NDC::push("three"); MDC::put("key1", "value1"); MDC::put("key2", "value2"); LogString output1; LogString expected1; expected1 .append(LOG4CXX_STR("{")) .append(LOG4CXX_EOL) .append(ppIndentL1) .append(LOG4CXX_STR("\"timestamp\": \"")) .append(timestamp) .append(LOG4CXX_STR("\",")) .append(LOG4CXX_EOL) .append(ppIndentL1) .append(LOG4CXX_STR("\"level\": \"INFO\",")) .append(LOG4CXX_EOL) .append(ppIndentL1) .append(LOG4CXX_STR("\"logger\": \"Logger\",")) .append(LOG4CXX_EOL) .append(ppIndentL1) .append(LOG4CXX_STR("\"message\": \"A message goes here.\"")); setPrettyPrint(true); setLocationInfo(true); appendSerializedMDC(expected1, event1); appendSerializedNDC(expected1, event1); expected1.append(LOG4CXX_STR(",")); expected1.append(LOG4CXX_EOL); appendSerializedLocationInfo(expected1, event1, p); expected1.append(LOG4CXX_EOL); expected1.append(LOG4CXX_STR("}")); expected1.append(LOG4CXX_EOL); format(output1, event1, p); LOGUNIT_ASSERT_EQUAL(expected1, output1); } /** * Tests getLocationInfo and setLocationInfo. */ void testGetSetLocationInfo() { JSONLayout layout; LOGUNIT_ASSERT_EQUAL(false, layout.getLocationInfo()); layout.setLocationInfo(true); LOGUNIT_ASSERT_EQUAL(true, layout.getLocationInfo()); layout.setLocationInfo(false); LOGUNIT_ASSERT_EQUAL(false, layout.getLocationInfo()); } /** * Tests getPrettyPrint and setPrettyPrint. */ void testGetSetPrettyPrint() { JSONLayout layout; LOGUNIT_ASSERT_EQUAL(false, layout.getPrettyPrint()); layout.setPrettyPrint(true); LOGUNIT_ASSERT_EQUAL(true, layout.getPrettyPrint()); layout.setPrettyPrint(false); LOGUNIT_ASSERT_EQUAL(false, layout.getPrettyPrint()); } }; LOGUNIT_TEST_SUITE_REGISTRATION(JSONLayoutTest); apache-log4cxx-1.3.1/src/test/cpp/customlogger/0000755000175100001770000000000014721727031020736 5ustar runnerdockerapache-log4cxx-1.3.1/src/test/cpp/customlogger/xloggertestcase.cpp0000644000175100001770000000461014721727031024646 0ustar runnerdocker/* * 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. */ #define LOG4CXX_TEST 1 #include #include "../logunit.h" #include "xlogger.h" #include #include "../util/transformer.h" #include "../util/compare.h" #include using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::xml; #define LOG4CXX_TEST_STR(x) L##x /** Tests handling of custom loggers. */ LOGUNIT_CLASS(XLoggerTestCase) { LOGUNIT_TEST_SUITE(XLoggerTestCase); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST_SUITE_END(); LoggerPtr logger; public: void setUp() { logger = XLogger::getLogger( LOG4CXX_STR("org.apache.log4j.customLogger.XLoggerTestCase")); } void tearDown() { auto rep = logger->getLoggerRepository(); if (rep) { rep->resetConfiguration(); } } void test1() { common("1"); } void test2() { common("2"); } void common(const char* number) { std::string fn("input/xml/customLogger"); fn.append(number); fn.append(".xml"); DOMConfigurator::configure(fn); int i = 0; LOG4CXX_LOG(logger, log4cxx::XLevel::getTrace(), "Message " << i); i++; LOG4CXX_DEBUG(logger, "Message " << i); i++; LOG4CXX_WARN(logger, "Message " << i); i++; LOG4CXX_ERROR(logger, "Message " << i); i++; LOG4CXX_FATAL(logger, "Message " << i); i++; LOG4CXX_DEBUG(logger, "Message " << i); const File OUTPUT("output/customlogger"); std::string witness("witness/customLogger."); witness.append(number); const File WITNESS(witness); LOGUNIT_ASSERT(Compare::compare(OUTPUT, WITNESS)); } }; LOGUNIT_TEST_SUITE_REGISTRATION(XLoggerTestCase); apache-log4cxx-1.3.1/src/test/cpp/customlogger/CMakeLists.txt0000644000175100001770000000163514721727031023503 0ustar runnerdocker# # 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. # add_executable(xloggertestcase xloggertestcase.cpp xlogger.cpp) set(ALL_LOG4CXX_TESTS ${ALL_LOG4CXX_TESTS} xloggertestcase PARENT_SCOPE) apache-log4cxx-1.3.1/src/test/cpp/customlogger/xlogger.h0000644000175100001770000000641314721727031022562 0ustar runnerdocker/* * 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. */ #include #include "../xml/xlevel.h" #include namespace LOG4CXX_NS { namespace spi { namespace location { class LocationInfo; } } // Any sub-class of Logger must also have its own implementation of // LoggerFactory. class XFactory : public virtual spi::LoggerFactory, public virtual helpers::Object { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(XFactory) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(XFactory) LOG4CXX_CAST_ENTRY(spi::LoggerFactory) END_LOG4CXX_CAST_MAP() XFactory(); #if LOG4CXX_ABI_VERSION <= 15 LoggerPtr makeNewLoggerInstance( helpers::Pool& pool, const LogString& name) const override; LoggerPtr makeNewLoggerInstance(const LogString& name) const; #else LoggerPtr makeNewLoggerInstance(const LogString& name) const override; #endif }; typedef std::shared_ptr XFactoryPtr; /** A simple example showing Logger sub-classing. It shows the minimum steps necessary to implement one's {@link LoggerFactory}. Note that sub-classes follow the hierarchy even if its loggers belong to different classes. */ class XLogger : public Logger { // It's enough to instantiate a factory once and for all. static XFactoryPtr factory; LogString suffix; public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(XLogger) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(XLogger) LOG4CXX_CAST_ENTRY_CHAIN(Logger) END_LOG4CXX_CAST_MAP() /** Just calls the parent constuctor. */ XLogger(const LogString& name) : Logger(name) {} /** Nothing to activate. */ void activateOptions() {} /** We introduce a new printing method in order to support {@link XLevel#LETHAL}. */ void lethal(const LogString& message, const log4cxx::spi::LocationInfo& location); /** We introduce a new printing method in order to support {@link XLevel#LETHAL}. */ void lethal(const LogString& message); static LoggerPtr getLogger(const LogString& name); static LoggerPtr getLogger(const helpers::Class& clazz); LogString getSuffix() const { return suffix; } void setSuffix(const LogString& suffix1) { this->suffix = suffix1; } /** We introduce a new printing method that takes the TRACE level. */ void trace(const LogString& message, const log4cxx::spi::LocationInfo& location); /** We introduce a new printing method that takes the TRACE level. */ void trace(const LogString& message); }; typedef std::shared_ptr XLoggerPtr; } apache-log4cxx-1.3.1/src/test/cpp/customlogger/xlogger.cpp0000644000175100001770000000560114721727031023113 0ustar runnerdocker/* * 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. */ #include #include "xlogger.h" #include #include #include #include using namespace log4cxx; using namespace log4cxx::spi; IMPLEMENT_LOG4CXX_OBJECT(XLogger) IMPLEMENT_LOG4CXX_OBJECT(XFactory) XFactoryPtr XLogger::factory = XFactoryPtr(new XFactory()); void XLogger::lethal(const LogString& message, const LocationInfo& locationInfo) { auto rep = getLoggerRepository(); if (rep->isDisabled(XLevel::LETHAL_INT)) { return; } if (XLevel::getLethal()->isGreaterOrEqual(this->getEffectiveLevel())) { forcedLog(XLevel::getLethal(), message, locationInfo); } } void XLogger::lethal(const LogString& message) { auto rep = getLoggerRepository(); if (rep->isDisabled(XLevel::LETHAL_INT)) { return; } if (XLevel::getLethal()->isGreaterOrEqual(this->getEffectiveLevel())) { forcedLog(XLevel::getLethal(), message, LocationInfo::getLocationUnavailable()); } } LoggerPtr XLogger::getLogger(const LogString& name) { return LogManager::getLogger(name, factory); } LoggerPtr XLogger::getLogger(const helpers::Class& clazz) { return XLogger::getLogger(clazz.getName()); } void XLogger::trace(const LogString& message, const LocationInfo& locationInfo) { auto rep = getLoggerRepository(); if (rep->isDisabled(XLevel::TRACE_INT)) { return; } if (XLevel::getTrace()->isGreaterOrEqual(this->getEffectiveLevel())) { forcedLog(XLevel::getTrace(), message, locationInfo); } } void XLogger::trace(const LogString& message) { auto rep = getLoggerRepository(); if (rep->isDisabled(XLevel::TRACE_INT)) { return; } if (XLevel::getTrace()->isGreaterOrEqual(this->getEffectiveLevel())) { forcedLog(XLevel::getTrace(), message, LocationInfo::getLocationUnavailable()); } } XFactory::XFactory() { } #if LOG4CXX_ABI_VERSION <= 15 LoggerPtr XFactory::makeNewLoggerInstance(helpers::Pool&, const LogString& name) const { return LoggerPtr(new XLogger(name)); } #endif LoggerPtr XFactory::makeNewLoggerInstance(const LogString& name) const { return LoggerPtr(new XLogger(name)); } apache-log4cxx-1.3.1/src/test/cpp/writerappendertestcase.h0000644000175100001770000000222614721727031023166 0ustar runnerdocker/* * 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. */ #include #include "appenderskeletontestcase.h" /** An abstract set of tests for inclusion in concrete appender test case */ class WriterAppenderTestCase : public AppenderSkeletonTestCase { public: log4cxx::AppenderSkeleton* createAppenderSkeleton() const; virtual log4cxx::WriterAppender* createWriterAppender() const = 0; }; apache-log4cxx-1.3.1/src/test/cpp/locationdisabledtest.cpp0000644000175100001770000000351214721727031023131 0ustar runnerdocker/* * 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. */ #include #include #include "testchar.h" #include "logunit.h" #include "util/compare.h" using namespace log4cxx; using namespace log4cxx::helpers; LOGUNIT_CLASS(LocationDisabledTest) { LOGUNIT_TEST_SUITE(LocationDisabledTest); LOGUNIT_TEST(test1); LOGUNIT_TEST_SUITE_END(); LoggerPtr root; LoggerPtr logger; public: void setUp() { root = Logger::getRootLogger(); } void tearDown() { if (auto rep = root->getLoggerRepository()) rep->resetConfiguration(); } void test1() { PropertyConfigurator::configure(LOG4CXX_FILE("input/locationdisabled.properties")); common(); LOGUNIT_ASSERT(Compare::compare(LOG4CXX_STR("output/location-disabled-test"), LOG4CXX_FILE("witness/location1-disabled"))); } std::string createMessage(Pool & pool, int i) { std::string msg("Message "); msg.append(pool.itoa(i)); return msg; } void common() { int i = -1; Pool pool; LOG4CXX_DEBUG(root, createMessage(pool, i)); } }; LOGUNIT_TEST_SUITE_REGISTRATION(LocationDisabledTest); apache-log4cxx-1.3.1/src/test/cpp/leveltestcase.cpp0000644000175100001770000000665114721727031021603 0ustar runnerdocker /* * 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. */ #include #include "testchar.h" #include "logunit.h" #include #if LOG4CXX_CFSTRING_API #include #endif using namespace log4cxx; LOGUNIT_CLASS(LevelTestCase) { LOGUNIT_TEST_SUITE(LevelTestCase); LOGUNIT_TEST(testToLevelFatal); LOGUNIT_TEST(testTraceInt); LOGUNIT_TEST(testTrace); LOGUNIT_TEST(testIntToTrace); LOGUNIT_TEST(testStringToTrace); #if LOG4CXX_WCHAR_T_API LOGUNIT_TEST(testWideStringToTrace); #endif #if LOG4CXX_UNICHAR_API LOGUNIT_TEST(testUniCharStringToTrace); #endif #if LOG4CXX_CFSTRING_API LOGUNIT_TEST(testCFStringToTrace); #endif LOGUNIT_TEST(testTrimmedToTrace); LOGUNIT_TEST_SUITE_END(); #ifdef _DEBUG struct Fixture { Fixture() { helpers::LogLog::setInternalDebugging(true); } } suiteFixture; #endif public: void testToLevelFatal() { LevelPtr level(Level::toLevel(LOG4CXX_TEST_STR("fATal"))); LOGUNIT_ASSERT_EQUAL((int) Level::FATAL_INT, level->toInt()); } /** * Tests Level::TRACE_INT. */ void testTraceInt() { LOGUNIT_ASSERT_EQUAL(5000, (int) Level::TRACE_INT); } /** * Tests Level.TRACE. */ void testTrace() { LOGUNIT_ASSERT(Level::getTrace()->toString() == LOG4CXX_STR("TRACE")); LOGUNIT_ASSERT_EQUAL(5000, Level::getTrace()->toInt()); LOGUNIT_ASSERT_EQUAL(7, Level::getTrace()->getSyslogEquivalent()); } /** * Tests Level.toLevel(Level.TRACE_INT). */ void testIntToTrace() { LevelPtr trace(Level::toLevel(5000)); LOGUNIT_ASSERT(trace->toString() == LOG4CXX_STR("TRACE")); } /** * Tests Level.toLevel("TRACE"); */ void testStringToTrace() { LevelPtr trace(Level::toLevel("TRACE")); LOGUNIT_ASSERT(trace->toString() == LOG4CXX_STR("TRACE")); } #if LOG4CXX_WCHAR_T_API /** * Tests Level.toLevel(L"TRACE"); */ void testWideStringToTrace() { LevelPtr trace(Level::toLevel(L"TRACE")); LOGUNIT_ASSERT(trace->toString() == LOG4CXX_STR("TRACE")); } #endif #if LOG4CXX_UNICHAR_API /** * Tests Level.toLevel("TRACE"); */ void testUniCharStringToTrace() { const log4cxx::UniChar name[] = { 'T', 'R', 'A', 'C', 'E', 0 }; LevelPtr trace(Level::toLevel(name)); LOGUNIT_ASSERT(trace->toString() == LOG4CXX_STR("TRACE")); } #endif #if LOG4CXX_CFSTRING_API /** * Tests Level.toLevel(CFSTR("TRACE")); */ void testCFStringToTrace() { LevelPtr trace(Level::toLevel(CFSTR("TRACE"))); LOGUNIT_ASSERT(trace->toString() == LOG4CXX_STR("TRACE")); } #endif /** * Tests Level.toLevel("TRACE "); */ void testTrimmedToTrace() { LevelPtr trace(Level::toLevel("TRACE ")); LOGUNIT_ASSERT(trace->toString() == LOG4CXX_STR("TRACE")); } }; LOGUNIT_TEST_SUITE_REGISTRATION(LevelTestCase); apache-log4cxx-1.3.1/src/test/cpp/hierarchytest.cpp0000644000175100001770000000355514721727031021616 0ustar runnerdocker/* * 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. */ #include #include #include "logunit.h" #include "insertwide.h" using namespace log4cxx; /** * Tests hierarchy. * */ LOGUNIT_CLASS(HierarchyTest) { LOGUNIT_TEST_SUITE(HierarchyTest); LOGUNIT_TEST(testGetParent); LOGUNIT_TEST_SUITE_END(); public: /** * Tests getParent. */ void testGetParent() { // // Note: test inspired by LOGCXX-118. // LoggerPtr logger1(Logger::getLogger("HierarchyTest_testGetParent.logger1")); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("root")), logger1->getParent()->getName()); LoggerPtr logger2(Logger::getLogger("HierarchyTest_testGetParent.logger2")); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("root")), logger1->getParent()->getName()); LoggerPtr logger3(Logger::getLogger("HierarchyTest_testGetParent")); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("HierarchyTest_testGetParent")), logger1->getParent()->getName()); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("HierarchyTest_testGetParent")), logger2->getParent()->getName()); } }; LOGUNIT_TEST_SUITE_REGISTRATION(HierarchyTest); apache-log4cxx-1.3.1/src/test/cpp/encodingtest.cpp0000644000175100001770000001133514721727031021421 0ustar runnerdocker/* * 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. */ #include #include "logunit.h" // // If there is no support for wchar_t logging then // there is not a consistent way to get the test characters logged // #if LOG4CXX_WCHAR_T_API #include #include #include #include "util/binarycompare.h" #include #include using namespace log4cxx; using namespace log4cxx::util; using namespace log4cxx::helpers; /** * Tests support for encoding specification. * * */ LOGUNIT_CLASS(EncodingTest) { LOGUNIT_TEST_SUITE(EncodingTest); LOGUNIT_TEST(testASCII); LOGUNIT_TEST(testLatin1); LOGUNIT_TEST(testUtf8); LOGUNIT_TEST(testUtf16); LOGUNIT_TEST(testUtf16LE); LOGUNIT_TEST(testUtf16BE); LOGUNIT_TEST_SUITE_END(); public: /** * Resets configuration after each test. */ void tearDown() { auto rep = Logger::getRootLogger()->getLoggerRepository(); if (rep) { rep->resetConfiguration(); } } /** * Test us-ascii encoding. */ void testASCII() { LoggerPtr root(Logger::getRootLogger()); configure(root, LOG4CXX_STR("output/encoding/ascii.log"), LOG4CXX_STR("US-ASCII")); common(root); BinaryCompare::compare( "output/encoding/ascii.log", "witness/encoding/ascii.log"); } /** * Test iso-8859-1 encoding. */ void testLatin1() { LoggerPtr root(Logger::getRootLogger()); configure(root, LOG4CXX_STR("output/encoding/latin1.log"), LOG4CXX_STR("iso-8859-1")); common(root); BinaryCompare::compare( "output/encoding/latin1.log", "witness/encoding/latin1.log"); } /** * Test utf-8 encoding. */ void testUtf8() { LoggerPtr root(Logger::getRootLogger()); configure(root, LOG4CXX_STR("output/encoding/UTF-8.log"), LOG4CXX_STR("UTF-8")); common(root); BinaryCompare::compare( "output/encoding/UTF-8.log", "witness/encoding/UTF-8.log"); } /** * Test utf-16 encoding. */ void testUtf16() { LoggerPtr root(Logger::getRootLogger()); configure(root, LOG4CXX_STR("output/encoding/UTF-16.log"), LOG4CXX_STR("UTF-16")); common(root); BinaryCompare::compare( "output/encoding/UTF-16.log", "witness/encoding/UTF-16.log"); } /** * Test utf-16be encoding. */ void testUtf16BE() { LoggerPtr root(Logger::getRootLogger()); configure(root, LOG4CXX_STR("output/encoding/UTF-16BE.log"), LOG4CXX_STR("UTF-16BE")); common(root); BinaryCompare::compare( "output/encoding/UTF-16BE.log", "witness/encoding/UTF-16BE.log"); } /** * Test utf16-le encoding. */ void testUtf16LE() { LoggerPtr root(Logger::getRootLogger()); configure(root, LOG4CXX_STR("output/encoding/UTF-16LE.log"), LOG4CXX_STR("UTF-16LE")); common(root); BinaryCompare::compare( "output/encoding/UTF-16LE.log", "witness/encoding/UTF-16LE.log"); } /** * Configure logging. * @param logger logger * @param filename logging file name * @param encoding encoding */ private: void configure( LoggerPtr & logger, const LogString & filename, const LogString & encoding) { FileAppenderPtr appender(new FileAppender()); PatternLayoutPtr layout(new PatternLayout()); Pool p; layout->setConversionPattern(LOG4CXX_STR("%p - %m\n")); layout->activateOptions(p); appender->setAppend(false); appender->setEncoding(encoding); appender->setFile(filename); appender->setLayout(layout); appender->activateOptions(p); logger->addAppender(appender); logger->setLevel(Level::getInfo()); } /** * Common logging requests. * @param logger logger */ void common(LoggerPtr & logger) { logger->info("Hello, World"); // pi can be encoded in iso-8859-1 const wchar_t pi[] = { 0x00B9, 0 }; logger->info(pi); // arbitrary, hopefully meaningless, characters from // Latin, Arabic, Armenian, Bengali, CJK and Cyrillic const wchar_t greeting[] = { L'A', 0x0605, 0x0530, 0x986, 0x4E03, 0x400, 0 }; logger->info(greeting); } }; LOGUNIT_TEST_SUITE_REGISTRATION(EncodingTest); #endif apache-log4cxx-1.3.1/src/test/cpp/defaultinit/0000755000175100001770000000000014721727031020534 5ustar runnerdockerapache-log4cxx-1.3.1/src/test/cpp/defaultinit/testcase1.cpp0000644000175100001770000000251714721727031023141 0ustar runnerdocker/* * 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. */ #include "../logunit.h" #include #include using namespace log4cxx; LOGUNIT_CLASS(TestCase1) { LOGUNIT_TEST_SUITE(TestCase1); LOGUNIT_TEST(noneTest); LOGUNIT_TEST_SUITE_END(); public: void setUp() { } void tearDown() { LogManager::shutdown(); } void noneTest() { LoggerPtr root = Logger::getRootLogger(); LOG4CXX_DEBUG(root, "Hello, world"); bool rootIsConfigured = !root->getAllAppenders().empty(); LOGUNIT_ASSERT(!rootIsConfigured); } }; LOGUNIT_TEST_SUITE_REGISTRATION(TestCase1) apache-log4cxx-1.3.1/src/test/cpp/defaultinit/testcase4.cpp0000644000175100001770000000361614721727031023145 0ustar runnerdocker/* * 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. */ #define LOG4CXX_TEST 1 #include #include #include #include #include #include "../insertwide.h" #include "../logunit.h" using namespace log4cxx; LOGUNIT_CLASS(TestCase4) { LOGUNIT_TEST_SUITE(TestCase4); LOGUNIT_TEST(combinedTest); LOGUNIT_TEST_SUITE_END(); public: void setUp() { helpers::Pool p; apr_file_copy("input/xml/defaultInit.xml", "log4cxx.xml", APR_FPROT_UREAD | APR_FPROT_UWRITE, p.getAPRPool()); } void tearDown() { helpers::Pool p; apr_file_remove("log4cxx.xml", p.getAPRPool()); LogManager::shutdown(); } void combinedTest() { LoggerPtr root = Logger::getRootLogger(); LOG4CXX_DEBUG(root, "Hello, world"); bool rootIsConfigured = !root->getAllAppenders().empty(); LOGUNIT_ASSERT(rootIsConfigured); AppenderList list = root->getAllAppenders(); LOGUNIT_ASSERT_EQUAL((size_t) 1, list.size()); AppenderPtr appender = list.front(); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("D1"), appender->getName()); } }; LOGUNIT_TEST_SUITE_REGISTRATION(TestCase4) apache-log4cxx-1.3.1/src/test/cpp/defaultinit/testcase3.cpp0000644000175100001770000000345414721727031023144 0ustar runnerdocker/* * 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. */ #include #include #include #include #include "../insertwide.h" #include "../logunit.h" using namespace log4cxx; LOGUNIT_CLASS(TestCase3) { LOGUNIT_TEST_SUITE(TestCase3); LOGUNIT_TEST(testProperties); LOGUNIT_TEST_SUITE_END(); public: void setUp() { helpers::Pool p; apr_file_copy("input/defaultInit3.properties", "log4cxx.properties", APR_FPROT_UREAD | APR_FPROT_UWRITE, p.getAPRPool()); } void tearDown() { helpers::Pool p; apr_file_remove("log4cxx.properties", p.getAPRPool()); LogManager::shutdown(); } void testProperties() { LoggerPtr root = Logger::getRootLogger(); LOG4CXX_DEBUG(root, "Hello, world"); bool rootIsConfigured = !root->getAllAppenders().empty(); LOGUNIT_ASSERT(rootIsConfigured); AppenderList list = root->getAllAppenders(); AppenderPtr appender = list.front(); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("D3"), appender->getName()); } }; LOGUNIT_TEST_SUITE_REGISTRATION(TestCase3) apache-log4cxx-1.3.1/src/test/cpp/defaultinit/CMakeLists.txt0000644000175100001770000000207514721727031023300 0ustar runnerdocker# # 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. # if(NOT LOG4CXX_DOMCONFIGURATOR_SUPPORT) add_executable(defaultinittestcase testcase1.cpp testcase3.cpp) else() add_executable(defaultinittestcase testcase1.cpp testcase2.cpp testcase3.cpp testcase4.cpp) endif() set(ALL_LOG4CXX_TESTS ${ALL_LOG4CXX_TESTS} defaultinittestcase PARENT_SCOPE) apache-log4cxx-1.3.1/src/test/cpp/defaultinit/testcase2.cpp0000644000175100001770000000352414721727031023141 0ustar runnerdocker/* * 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. */ #define LOG4CXX_TEST 1 #include #include #include #include #include #include "../insertwide.h" #include "../logunit.h" using namespace log4cxx; LOGUNIT_CLASS(TestCase2) { LOGUNIT_TEST_SUITE(TestCase2); LOGUNIT_TEST(xmlTest); LOGUNIT_TEST_SUITE_END(); public: void setUp() { helpers::Pool p; apr_file_copy("input/xml/defaultInit.xml", "log4cxx.xml", APR_FPROT_UREAD | APR_FPROT_UWRITE, p.getAPRPool()); } void tearDown() { helpers::Pool p; apr_file_remove("log4cxx.xml", p.getAPRPool()); LogManager::shutdown(); } void xmlTest() { LoggerPtr root = Logger::getRootLogger(); LOG4CXX_DEBUG(root, "Hello, world"); bool rootIsConfigured = !root->getAllAppenders().empty(); LOGUNIT_ASSERT(rootIsConfigured); AppenderList list = root->getAllAppenders(); AppenderPtr appender = list.front(); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("D1"), appender->getName()); } }; LOGUNIT_TEST_SUITE_REGISTRATION(TestCase2) apache-log4cxx-1.3.1/src/test/cpp/locationtest.cpp0000644000175100001770000000344314721727031021444 0ustar runnerdocker/* * 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. */ #include #include #include "testchar.h" #include "logunit.h" #include "util/compare.h" using namespace log4cxx; using namespace log4cxx::helpers; LOGUNIT_CLASS(LocationTest) { LOGUNIT_TEST_SUITE(LocationTest); LOGUNIT_TEST(test1); LOGUNIT_TEST_SUITE_END(); LoggerPtr root; LoggerPtr logger; public: void setUp() { root = Logger::getRootLogger(); } void tearDown() { if (auto rep = root->getLoggerRepository()) rep->resetConfiguration(); } void test1() { PropertyConfigurator::configure(LOG4CXX_FILE("input/location1.properties")); common(); LOGUNIT_ASSERT(Compare::compare(LOG4CXX_STR("output/location-good-test"), LOG4CXX_FILE("witness/location1-good"))); } std::string createMessage(Pool & pool, int i) { std::string msg("Message "); msg.append(pool.itoa(i)); return msg; } void common() { int i = -1; Pool pool; LOG4CXX_DEBUG(root, createMessage(pool, i)); } }; LOGUNIT_TEST_SUITE_REGISTRATION(LocationTest); apache-log4cxx-1.3.1/src/test/cpp/hexdumptestcase.cpp0000644000175100001770000000622014721727031022136 0ustar runnerdocker/* * 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. */ #include "logunit.h" #include #include using namespace log4cxx; LOGUNIT_CLASS(HexdumpTestCase) { LOGUNIT_TEST_SUITE(HexdumpTestCase); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST(test_newline); LOGUNIT_TEST(test_newline2); LOGUNIT_TEST_SUITE_END(); public: void setUp() { } void tearDown() { } void test1() { unsigned char test1_str[] = { 0x74, 0x65, 0x73, 0x74, 0x31 }; LogString expectedOutput = LOG4CXX_STR("00000000 74 65 73 74 31 |test1|"); LogString dumped = log4cxx::hexdump(test1_str, sizeof(test1_str)); LOGUNIT_ASSERT_EQUAL(expectedOutput, dumped); } void test2() { unsigned char quick_brown_fox[] = { 0x54, 0x68, 0x65, 0x20, 0x71, 0x75, 0x69, 0x63, 0x6b, 0x20, 0x62, 0x72, 0x6f, 0x77, 0x6e, 0x20, 0x66, 0x6f, 0x78, 0x20, 0x6a, 0x75, 0x6d, 0x70, 0x73, 0x20, 0x6f, 0x76, 0x65, 0x72, 0x20, 0x74, 0x68, 0x65, 0x20, 0x6c, 0x61, 0x7a, 0x79, 0x20, 0x64, 0x6f, 0x67 }; LogString expectedOutput = LOG4CXX_STR("00000000 54 68 65 20 71 75 69 63 6b 20 62 72 6f 77 6e 20 |The quick brown |") LOG4CXX_EOL LOG4CXX_STR("00000010 66 6f 78 20 6a 75 6d 70 73 20 6f 76 65 72 20 74 |fox jumps over t|") LOG4CXX_EOL LOG4CXX_STR("00000020 68 65 20 6c 61 7a 79 20 64 6f 67 |he lazy dog|"); // Hexdump up until the NULL char LogString dumped = log4cxx::hexdump(quick_brown_fox, sizeof(quick_brown_fox)); LOGUNIT_ASSERT_EQUAL(expectedOutput, dumped); } void test_newline() { unsigned char test1_str[] = { 0x74, 0x65, 0x73, 0x74, 0x31 }; LogString expectedOutput = LOG4CXX_EOL LOG4CXX_STR("00000000 74 65 73 74 31 |test1|") LOG4CXX_EOL; LogString dumped = log4cxx::hexdump(test1_str, sizeof(test1_str), HexdumpFlags::AddNewline); LOGUNIT_ASSERT_EQUAL(expectedOutput, dumped); } void test_newline2() { unsigned char test1_str[] = { 0x74, 0x65, 0x73, 0x74, 0x31 }; LogString expectedOutput = LOG4CXX_EOL LOG4CXX_STR("00000000 74 65 73 74 31 |test1|") LOG4CXX_EOL; LogString dumped = log4cxx::hexdump(test1_str, sizeof(test1_str), HexdumpFlags::AddStartingNewline | HexdumpFlags::AddEndingNewline); LOGUNIT_ASSERT_EQUAL(expectedOutput, dumped); } }; LOGUNIT_TEST_SUITE_REGISTRATION(HexdumpTestCase); apache-log4cxx-1.3.1/src/test/cpp/filetestcase.cpp0000644000175100001770000001263714721727031021414 0ustar runnerdocker/* * 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. */ #include #include "logunit.h" #include "insertwide.h" #include #include #include #include #include #include #include #include #include #if LOG4CXX_CFSTRING_API #include #endif using namespace log4cxx; using namespace log4cxx::helpers; LOGUNIT_CLASS(FileTestCase) { LOGUNIT_TEST_SUITE(FileTestCase); LOGUNIT_TEST(defaultConstructor); LOGUNIT_TEST(defaultExists); LOGUNIT_TEST(defaultRead); LOGUNIT_TEST(propertyRead); LOGUNIT_TEST(propertyExists); LOGUNIT_TEST(fileWrite1); #if LOG4CXX_WCHAR_T_API LOGUNIT_TEST(wcharConstructor); #endif #if LOG4CXX_UNICHAR_API LOGUNIT_TEST(unicharConstructor); #endif #if LOG4CXX_CFSTRING_API LOGUNIT_TEST(cfstringConstructor); #endif LOGUNIT_TEST(copyConstructor); LOGUNIT_TEST(assignment); LOGUNIT_TEST(deleteBackslashedFileName); LOGUNIT_TEST_SUITE_END(); #ifdef _DEBUG struct Fixture { Fixture() { helpers::LogLog::setInternalDebugging(true); } } suiteFixture; #endif public: void defaultConstructor() { File defFile; LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR(""), defFile.getPath()); } void defaultExists() { File defFile; Pool pool; bool exists = defFile.exists(pool); LOGUNIT_ASSERT_EQUAL(false, exists); } // check default constructor. read() throws an exception // if no file name was given. void defaultRead() { File defFile; Pool pool; try { InputStreamPtr defInput = FileInputStreamPtr(new FileInputStream(defFile)); InputStreamReaderPtr inputReader = InputStreamReaderPtr(new InputStreamReader(defInput)); LogString contents(inputReader->read(pool)); LOGUNIT_ASSERT(false); } catch (IOException& ex) { } } #if LOG4CXX_WCHAR_T_API void wcharConstructor() { File propFile(L"input/patternLayout1.properties"); Pool pool; bool exists = propFile.exists(pool); LOGUNIT_ASSERT_EQUAL(true, exists); } #endif #if LOG4CXX_UNICHAR_API void unicharConstructor() { const log4cxx::UniChar filename[] = { 'i', 'n', 'p', 'u', 't', '/', 'p', 'a', 't', 't', 'e', 'r', 'n', 'L', 'a', 'y', 'o', 'u', 't', '1', '.', 'p', 'r', 'o', 'p', 'e', 'r', 't', 'i', 'e', 's', 0 }; File propFile(filename); Pool pool; bool exists = propFile.exists(pool); LOGUNIT_ASSERT_EQUAL(true, exists); } #endif #if LOG4CXX_CFSTRING_API void cfstringConstructor() { File propFile(CFSTR("input/patternLayout1.properties")); Pool pool; bool exists = propFile.exists(pool); LOGUNIT_ASSERT_EQUAL(true, exists); } #endif void copyConstructor() { File propFile("input/patternLayout1.properties"); File copy(propFile); Pool pool; bool exists = copy.exists(pool); LOGUNIT_ASSERT_EQUAL(true, exists); } void assignment() { File propFile("input/patternLayout1.properties"); File copy = propFile; Pool pool; bool exists = copy.exists(pool); LOGUNIT_ASSERT_EQUAL(true, exists); } void propertyRead() { File propFile("input/patternLayout1.properties"); Pool pool; InputStreamPtr propStream = FileInputStreamPtr(new FileInputStream(propFile)); InputStreamReaderPtr propReader = InputStreamReaderPtr(new InputStreamReader(propStream)); LogString props(propReader->read(pool)); LogString line1(LOG4CXX_STR("# Licensed to the Apache Software Foundation (ASF) under one or more")); LOGUNIT_ASSERT_EQUAL(line1, props.substr(0, line1.length())); } void propertyExists() { File propFile("input/patternLayout1.properties"); Pool pool; bool exists = propFile.exists(pool); LOGUNIT_ASSERT_EQUAL(true, exists); } void fileWrite1() { OutputStreamPtr fos = FileOutputStreamPtr( new FileOutputStream(LOG4CXX_STR("output/fileWrite1.txt"))); OutputStreamWriterPtr osw = OutputStreamWriterPtr(new OutputStreamWriter(fos)); Pool pool; LogString greeting(LOG4CXX_STR("Hello, World")); greeting.append(LOG4CXX_EOL); osw->write(greeting, pool); InputStreamPtr is = FileInputStreamPtr( new FileInputStream(LOG4CXX_STR("output/fileWrite1.txt"))); InputStreamReaderPtr isr = InputStreamReaderPtr(new InputStreamReader(is)); LogString reply = isr->read(pool); LOGUNIT_ASSERT_EQUAL(greeting, reply); } /** * Tests conversion of backslash containing file names. * Would cause infinite loop due to bug LOGCXX-105. */ void deleteBackslashedFileName() { File file("output\\bogus.txt"); Pool pool; /*bool deleted = */file.deleteFile(pool); } }; LOGUNIT_TEST_SUITE_REGISTRATION(FileTestCase); apache-log4cxx-1.3.1/src/test/cpp/net/0000755000175100001770000000000014721727031017012 5ustar runnerdockerapache-log4cxx-1.3.1/src/test/cpp/net/xmlsocketappendertestcase.cpp0000644000175100001770000000345614721727031025012 0ustar runnerdocker/* * 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. */ #include #include #include "../appenderskeletontestcase.h" #include "apr.h" using namespace log4cxx; using namespace log4cxx::helpers; /** Unit tests of log4cxx::net::XMLSocketAppender */ class XMLSocketAppenderTestCase : public AppenderSkeletonTestCase { LOGUNIT_TEST_SUITE(XMLSocketAppenderTestCase); // // tests inherited from AppenderSkeletonTestCase // LOGUNIT_TEST(testDefaultThreshold); LOGUNIT_TEST(testSetOptionThreshold); //LOGUNIT_TEST(test_fluent_bit); LOGUNIT_TEST_SUITE_END(); public: AppenderSkeleton* createAppenderSkeleton() const { return new log4cxx::net::XMLSocketAppender(); } void test_fluent_bit() { xml::DOMConfigurator::configure("input/xml/fluent-bit.xml"); auto log = Logger::getRootLogger(); for (int i = 0; i < 100; ++i) { LOG4CXX_INFO(log, "Message '" << i << "'"); } LOG4CXX_INFO(log, "Last message"); } }; LOGUNIT_TEST_SUITE_REGISTRATION(XMLSocketAppenderTestCase); apache-log4cxx-1.3.1/src/test/cpp/net/telnetappendertestcase.cpp0000644000175100001770000000656214721727031024275 0ustar runnerdocker/* * 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. */ #include #include #include "../appenderskeletontestcase.h" #include #include #include using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::net; /** Unit tests of log4cxx::TelnetAppender */ class TelnetAppenderTestCase : public AppenderSkeletonTestCase { LOGUNIT_TEST_SUITE(TelnetAppenderTestCase); // // tests inherited from AppenderSkeletonTestCase // LOGUNIT_TEST(testDefaultThreshold); LOGUNIT_TEST(testSetOptionThreshold); LOGUNIT_TEST(testActivateClose); LOGUNIT_TEST(testActivateSleepClose); LOGUNIT_TEST(testActivateWriteClose); LOGUNIT_TEST(testActivateWriteNoClose); LOGUNIT_TEST_SUITE_END(); enum { TEST_PORT = 1723 }; static LayoutPtr createLayout() { PatternLayoutPtr pl = std::make_shared(); pl->setConversionPattern( LOG4CXX_STR("%r [%t] %-5p - %m%n") ); return pl; } public: AppenderSkeleton* createAppenderSkeleton() const { return new log4cxx::net::TelnetAppender(); } void testActivateClose() { TelnetAppenderPtr appender(new TelnetAppender()); appender->setLayout(createLayout()); appender->setPort(TEST_PORT); Pool p; appender->activateOptions(p); appender->close(); } void testActivateSleepClose() { TelnetAppenderPtr appender(new TelnetAppender()); appender->setLayout(createLayout()); appender->setPort(TEST_PORT); Pool p; appender->activateOptions(p); std::this_thread::sleep_for( std::chrono::milliseconds( 100 ) ); appender->close(); } void testActivateWriteClose() { TelnetAppenderPtr appender(new TelnetAppender()); appender->setLayout(createLayout()); appender->setPort(TEST_PORT); Pool p; appender->activateOptions(p); LoggerPtr root(Logger::getRootLogger()); root->addAppender(appender); for (int i = 0; i < 50; i++) { LOG4CXX_INFO(root, "Hello, World " << i); } appender->close(); root->removeAppender(appender); } void testActivateWriteNoClose() { TelnetAppenderPtr appender(new TelnetAppender()); appender->setPort(TEST_PORT); appender->setMaxConnections(1); Pool p; appender->activateOptions(p); LoggerPtr root(Logger::getRootLogger()); root->addAppender(appender); for (int i = 0; i < 50; i++) { //#define ALLOW_TESTING_WITH_TELNET #ifdef ALLOW_TESTING_WITH_TELNET std::this_thread::sleep_for( std::chrono::milliseconds( 1000 ) ); #endif LOG4CXX_INFO(root, "Hello, World " << i); } } }; LOGUNIT_TEST_SUITE_REGISTRATION(TelnetAppenderTestCase); apache-log4cxx-1.3.1/src/test/cpp/net/socketappendertestcase.cpp0000644000175100001770000000521414721727031024263 0ustar runnerdocker/* * 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. */ #include "../appenderskeletontestcase.h" #include "apr.h" using namespace log4cxx; using namespace log4cxx::helpers; /** Unit tests of log4cxx::SocketAppender */ class SocketAppenderTestCase : public AppenderSkeletonTestCase { LOGUNIT_TEST_SUITE(SocketAppenderTestCase); // // tests inherited from AppenderSkeletonTestCase // LOGUNIT_TEST(testDefaultThreshold); LOGUNIT_TEST(testSetOptionThreshold); LOGUNIT_TEST(testInvalidHost); LOGUNIT_TEST_SUITE_END(); public: void setUp() { } void tearDown() { BasicConfigurator::resetConfiguration(); } AppenderSkeleton* createAppenderSkeleton() const { return new log4cxx::net::SocketAppender(); } void testInvalidHost(){ // log4cxx::net::SocketAppenderPtr appender = std::make_shared(); // log4cxx::PatternLayoutPtr layout = std::make_shared(LOG4CXX_STR("%m%n")); // log4cxx::helpers::ServerSocket serverSocket(4445); // appender->setLayout(layout); // appender->setRemoteHost(LOG4CXX_STR("localhost")); // appender->setReconnectionDelay(1); // appender->setPort(4445); // log4cxx::helpers::Pool pool; // appender->activateOptions(pool); // BasicConfigurator::configure(appender); // log4cxx::Logger::getRootLogger()->setLevel(log4cxx::Level::getAll()); // std::thread th1( [](){ // for( int x = 0; x < 3000; x++ ){ // LOG4CXX_INFO(Logger::getLogger(LOG4CXX_STR("test")), "Some message" ); // } // }); // std::thread th2( [](){ // for( int x = 0; x < 3000; x++ ){ // LOG4CXX_INFO(Logger::getLogger(LOG4CXX_STR("test")), "Some message" ); // } // }); // SocketPtr incomingSocket = serverSocket.accept(); // incomingSocket->close(); // // If we do not get here, we have deadlocked // th1.join(); // th2.join(); } }; LOGUNIT_TEST_SUITE_REGISTRATION(SocketAppenderTestCase); apache-log4cxx-1.3.1/src/test/cpp/net/socketserverstarter.cpp0000644000175100001770000001152014721727031023641 0ustar runnerdocker/* * 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. */ #include "../logunit.h" #include #include #include #include #include #include #include using namespace log4cxx; LOGUNIT_CLASS(SocketServerStarter) { LOGUNIT_TEST_SUITE(SocketServerStarter); LOGUNIT_TEST(startServer); LOGUNIT_TEST_SUITE_END(); public: void setUp() { } void tearDown() { } void startServer() { helpers::Pool p; apr_pool_t* pool = p.getAPRPool(); char* cmd = NULL; apr_status_t stat = apr_env_get(&cmd, "SOCKET_SERVER_COMMAND", pool); char* param_file = NULL; stat = apr_env_get(¶m_file, "SOCKET_SERVER_PARAMETER_FILE", pool); // prepare to launch the server // apr_proc_t server_pid; apr_procattr_t* attr = NULL; stat = apr_procattr_create(&attr, pool); if (stat != APR_SUCCESS) { LOGUNIT_FAIL("apr_procattr_create failed"); } stat = apr_procattr_io_set(attr, APR_NO_PIPE, APR_NO_PIPE, APR_NO_PIPE); if (stat != APR_SUCCESS) { LOGUNIT_FAIL("apr_procattr_io_set failed"); } //fprintf(stdout, "SOCKET_SERVER_COMMAND=%s\n", cmd); stat = apr_procattr_cmdtype_set(attr, APR_PROGRAM); if (stat != APR_SUCCESS) { LOGUNIT_FAIL("apr_procattr_cmdtype_set failed"); } if (!(cmd && *cmd) && !(param_file && *param_file)) { fputs("Either:\n", stderr); fputs(" The environment variable SOCKET_SERVER_COMMAND" " must contain the server process path" " followed by space separated command arguments\n", stderr); fputs("Or:\n", stderr); fputs(" The file named in the environment variable SOCKET_SERVER_PARAMETER_FILE" " must contain a line per argument starting with the server process path" " followed by lines containing command arguments\n", stderr); LOGUNIT_FAIL("Neither SOCKET_SERVER_COMMAND nor SOCKET_SERVER_PARAMETER_FILE available."); } if (cmd && *cmd) { // convert the space separated cmd string to the argument list // static const int MaxArgumentCount = 14; char** argv = (char**)apr_palloc(pool, (MaxArgumentCount + 1) * sizeof(*argv)); char* pcmd = apr_pstrdup(pool, cmd); int i = 0; for (; i < MaxArgumentCount && pcmd && *pcmd; ++i) { char separ = ' '; while (separ == *pcmd) { *pcmd = 0; ++pcmd; } if ('"' == *pcmd || '\'' == *pcmd) { separ = *pcmd; ++pcmd; } argv[i] = pcmd; if (NULL != (pcmd = strchr(pcmd, separ))) { *pcmd = 0; ++pcmd; while (' ' == *pcmd) { *pcmd = 0; ++pcmd; } } } argv[i] = 0; stat = apr_proc_create(&server_pid, argv[0], argv, NULL, attr, pool); if (stat == APR_SUCCESS) // Allow server time to load { apr_sleep(1000000); // 1 seconds } else { fprintf(stderr, "apr_proc_create failed to start %s\n", argv[0]); } } if (param_file && *param_file) { // Build the argument list from param_file // //fprintf(stderr, "Processing: %s\n", param_file); std::ifstream in(param_file); std::vector params; while (in) { params.push_back(std::string()); std::string& line = params.back(); std::getline(in, line); while (!line.empty() && (' ' == line[0] || '\t' == line[0])) { line.erase(0, 1); } while (!line.empty() && (' ' == line[line.size() - 1] || '\t' == line[line.size() - 1])) { line.erase(line.size() - 1, 1); } if (line.empty()) { params.pop_back(); } } const char** argv = (const char**)apr_palloc(pool, (params.size() + 1) * sizeof(*argv)); int i = 0; for (; i < params.size(); ++i) { argv[i] = params[i].c_str(); //fprintf(stderr, "argv[%i]: %s\n", i, argv[i]); } argv[i] = 0; stat = apr_proc_create(&server_pid, argv[0], argv, NULL, attr, pool); if (stat == APR_SUCCESS) // Allow server time to load { apr_sleep(1000000); // 1 seconds } else { fprintf(stderr, "apr_proc_create failed to start %s\n", argv[0]); } } LOGUNIT_ASSERT(stat == APR_SUCCESS); } }; LOGUNIT_TEST_SUITE_REGISTRATION(SocketServerStarter) apache-log4cxx-1.3.1/src/test/cpp/net/CMakeLists.txt0000644000175100001770000000251114721727031021551 0ustar runnerdocker# # 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. # # Tests defined in this directory if(LOG4CXX_NETWORKING_SUPPORT) set(NET_TESTS syslogappendertestcase telnetappendertestcase xmlsocketappendertestcase ) else() set(NET_TESTS "") endif() if(NOT LOG4CXX_DOMCONFIGURATOR_SUPPORT) list(REMOVE_ITEM NET_TESTS xmlsocketappendertestcase) endif() if(HAS_LIBESMTP) list(APPEND NET_TESTS smtpappendertestcase) endif(HAS_LIBESMTP) foreach(fileName IN LISTS NET_TESTS) add_executable(${fileName} "${fileName}.cpp") endforeach() set(ALL_LOG4CXX_TESTS ${ALL_LOG4CXX_TESTS} ${NET_TESTS} PARENT_SCOPE) apache-log4cxx-1.3.1/src/test/cpp/net/socketservertestcase.h0000644000175100001770000000170114721727031023435 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_NET_SOCKETSERVER_TESTCASE_H #define _LOG4CXX_NET_SOCKETSERVER_TESTCASE_H #define PORT 12345 #endif //_LOG4CXX_NET_SOCKETSERVER_TESTCASE_H apache-log4cxx-1.3.1/src/test/cpp/net/syslogappendertestcase.cpp0000644000175100001770000000273314721727031024316 0ustar runnerdocker/* * 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. */ #include #include #include "../appenderskeletontestcase.h" using namespace log4cxx; using namespace log4cxx::helpers; /** Unit tests of log4cxx::SyslogAppender */ class SyslogAppenderTestCase : public AppenderSkeletonTestCase { LOGUNIT_TEST_SUITE(SyslogAppenderTestCase); // // tests inherited from AppenderSkeletonTestCase // LOGUNIT_TEST(testDefaultThreshold); LOGUNIT_TEST(testSetOptionThreshold); LOGUNIT_TEST_SUITE_END(); public: AppenderSkeleton* createAppenderSkeleton() const { return new log4cxx::net::SyslogAppender(); } }; LOGUNIT_TEST_SUITE_REGISTRATION(SyslogAppenderTestCase); apache-log4cxx-1.3.1/src/test/cpp/net/smtpappendertestcase.cpp0000644000175100001770000001100414721727031023750 0ustar runnerdocker/* * 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. */ #define LOG4CXX_TEST 1 #include #include #include "../appenderskeletontestcase.h" #include #include #include #include namespace LOG4CXX_NS { namespace net { class MockTriggeringEventEvaluator : public virtual spi::TriggeringEventEvaluator { public: DECLARE_LOG4CXX_OBJECT(MockTriggeringEventEvaluator) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(MockTriggeringEventEvaluator) LOG4CXX_CAST_ENTRY(spi::TriggeringEventEvaluator) END_LOG4CXX_CAST_MAP() MockTriggeringEventEvaluator() { } bool isTriggeringEvent(const spi::LoggingEventPtr& event) override { return true; } private: MockTriggeringEventEvaluator(const MockTriggeringEventEvaluator&); MockTriggeringEventEvaluator& operator=(const MockTriggeringEventEvaluator&); }; } } using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::net; IMPLEMENT_LOG4CXX_OBJECT(MockTriggeringEventEvaluator) /** Unit tests of log4cxx::SocketAppender */ class SMTPAppenderTestCase : public AppenderSkeletonTestCase { LOGUNIT_TEST_SUITE(SMTPAppenderTestCase); // // tests inherited from AppenderSkeletonTestCase // LOGUNIT_TEST(testDefaultThreshold); LOGUNIT_TEST(testSetOptionThreshold); LOGUNIT_TEST(testTrigger); LOGUNIT_TEST(testInvalid); //#define LOG4CXX_TEST_EMAIL_AND_SMTP_HOST_ARE_IN_ENVIRONMENT_VARIABLES #ifdef LOG4CXX_TEST_EMAIL_AND_SMTP_HOST_ARE_IN_ENVIRONMENT_VARIABLES // This test requires the following environment variables: // LOG4CXX_TEST_EMAIL_RECIPIENT - where the email is sent // LOG4CXX_TEST_SMTP_HOST_NAME - the email server LOGUNIT_TEST(testValid); #endif LOGUNIT_TEST_SUITE_END(); public: AppenderSkeleton* createAppenderSkeleton() const { return new log4cxx::net::SMTPAppender(); } void setUp() { } void tearDown() { LogManager::resetConfiguration(); } /** * Tests that triggeringPolicy element will set evaluator. */ void testTrigger() { xml::DOMConfigurator::configure("input/xml/smtpAppender1.xml"); auto appender = log4cxx::cast(Logger::getRootLogger()->getAppender(LOG4CXX_STR("A1"))); LOGUNIT_ASSERT(appender); auto evaluator = appender->getEvaluator(); LOGUNIT_ASSERT(evaluator); LOGUNIT_ASSERT_EQUAL(true, evaluator->instanceof(MockTriggeringEventEvaluator::getStaticClass())); } void testInvalid() { auto appender = std::make_shared(); appender->setSMTPHost(LOG4CXX_STR("smtp.invalid")); appender->setTo(LOG4CXX_STR("you@example.invalid")); appender->setFrom(LOG4CXX_STR("me@example.invalid")); appender->setLayout(std::make_shared()); Pool p; appender->activateOptions(p); auto root = Logger::getRootLogger(); root->addAppender(appender); LOG4CXX_INFO(root, "Hello, World."); LOG4CXX_ERROR(root, "Sending Message"); // The DefaultEvaluator should trigger e-mail generation auto eh = dynamic_cast(appender->getErrorHandler().get()); LOGUNIT_ASSERT(eh); LOGUNIT_ASSERT(eh->errorReported()); } void testValid() { xml::DOMConfigurator::configure("input/xml/smtpAppenderValid.xml"); auto root = Logger::getRootLogger(); LOG4CXX_INFO(root, "Hello, World.\n\nThis paragraph should be preceeded by a blank line."); auto appender = log4cxx::cast(root->getAppender(LOG4CXX_STR("A1"))); LOGUNIT_ASSERT(appender); auto eh = dynamic_cast(appender->getErrorHandler().get()); LOGUNIT_ASSERT(eh); LOGUNIT_ASSERT(!eh->errorReported()); } }; LOGUNIT_TEST_SUITE_REGISTRATION(SMTPAppenderTestCase); apache-log4cxx-1.3.1/src/test/cpp/abts.cpp0000644000175100001770000002325214721727031017665 0ustar runnerdocker/* Copyright 2000-2004 Ryan Bloom * * 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. * * Portions of this file were taken from testall.c in the APR test suite, * written by members of the Apache Software Foundation. */ #include "abts.h" #include "abts_tests.h" #include "testutil.h" #define ABTS_STAT_SIZE 6 static char status[ABTS_STAT_SIZE] = {'|', '/', '-', '|', '\\', '-'}; static int curr_char; static int verbose = 0; static int exclude = 0; static int quiet = 0; static int list_tests = 0; const char** testlist = NULL; // defined in logunit.cpp abts_suite* abts_run_suites(abts_suite*); static int find_test_name(const char* testname) { int i; for (i = 0; testlist[i] != NULL; i++) { if (!strcmp(testlist[i], testname)) { return 1; } } return 0; } /* Determine if the test should be run at all */ static int should_test_run(const char* testname) { int found = 0; if (list_tests == 1) { return 0; } if (testlist == NULL) { return 1; } found = find_test_name(testname); if ((found && !exclude) || (!found && exclude)) { return 1; } return 0; } static void reset_status(void) { curr_char = 0; } static void update_status(void) { if (!quiet) { curr_char = (curr_char + 1) % ABTS_STAT_SIZE; fprintf(stdout, "\b%c", status[curr_char]); fflush(stdout); } } static void end_suite(abts_suite* suite) { if (suite != NULL) { sub_suite* last = suite->tail; if (!quiet) { fprintf(stdout, "\b"); fflush(stdout); } if (last->failed.size() == 0) { fprintf(stdout, "SUCCESS\n"); fflush(stdout); } else { fprintf(stdout, "FAILED %d of %d\n", (int)last->failed.size(), last->num_test); fflush(stdout); } } } abts_suite* abts_add_suite(abts_suite* suite, const char* suite_name_full) { sub_suite* subsuite; const char* p; const char* suite_name; curr_char = 0; /* Only end the suite if we actually ran it */ if (suite && suite->tail && !suite->tail->not_run) { end_suite(suite); } subsuite = new sub_suite(); subsuite->num_test = 0; subsuite->failed.clear(); subsuite->next = NULL; /* suite_name_full may be an absolute path depending on __FILE__ * expansion */ suite_name = strrchr(suite_name_full, '/'); if (suite_name) { suite_name++; } else { suite_name = suite_name_full; } p = strrchr(suite_name, '.'); if (p) { int length = p - suite_name; subsuite->name = std::string( suite_name, length ); } else { subsuite->name = suite_name; } if (list_tests) { fprintf(stdout, "%s\n", subsuite->name.c_str()); } subsuite->not_run = 0; if (suite == NULL) { suite = new abts_suite(); suite->head = subsuite; suite->tail = subsuite; } else { suite->tail->next = subsuite; suite->tail = subsuite; } if (!should_test_run(subsuite->name.c_str())) { subsuite->not_run = 1; return suite; } reset_status(); fprintf(stdout, (verbose ? "%s:\n" :"%-20s: "), subsuite->name.c_str()); update_status(); fflush(stdout); return suite; } void abts_run_test(abts_suite* ts, const char* name, test_func f, void* value) { abts_case tc; sub_suite* ss; if (!should_test_run(name)) { return; } ss = ts->tail; tc.failed = 0; tc.suite = ss; ss->num_test++; update_status(); if (verbose) { fprintf(stdout, " %s\n", name); fflush(stdout); } f(&tc, value); if (tc.failed) { ss->failed.push_back(name); } } static int report(abts_suite* suite) { size_t count = 0; sub_suite* dptr; if (suite && suite->tail && !suite->tail->not_run) { end_suite(suite); } for (dptr = suite->head; dptr; dptr = dptr->next) { count += dptr->failed.size(); } if (list_tests) { return 0; } if (count == 0) { printf("All tests passed.\n"); return 0; } dptr = suite->head; fprintf(stdout, "%-35s\t\tTotal\tFail\tFailed %%\n", "Failed Tests"); fprintf(stdout, "=======================================================================\n"); while (dptr != NULL) { if (dptr->failed.size() != 0) { float percent = ((float)dptr->failed.size() / (float)dptr->num_test); fprintf(stdout, "%-35s\t\t%5d\t%4d\t%6.2f%%\n", dptr->name.c_str(), dptr->num_test, (int)dptr->failed.size(), percent * 100); for( const char* failed_name : dptr->failed ){ fprintf(stdout, " %s\n", failed_name ); } } dptr = dptr->next; } return 1; } void abts_log_message(const char* fmt, ...) { va_list args; update_status(); if (verbose) { va_start(args, fmt); vfprintf(stderr, fmt, args); va_end(args); fprintf(stderr, "\n"); fflush(stderr); } } void abts_int_equal(abts_case* tc, const int expected, const int actual, int lineno) { update_status(); if (tc->failed) { return; } if (expected == actual) { return; } tc->failed = TRUE; if (verbose) { fprintf(stderr, "Line %d: expected <%d>, but saw <%d>\n", lineno, expected, actual); fflush(stderr); } } void abts_int_nequal(abts_case* tc, const int expected, const int actual, int lineno) { update_status(); if (tc->failed) { return; } if (expected != actual) { return; } tc->failed = TRUE; if (verbose) { fprintf(stderr, "Line %d: expected <%d>, but saw <%d>\n", lineno, expected, actual); fflush(stderr); } } void abts_size_equal(abts_case* tc, size_t expected, size_t actual, int lineno) { update_status(); if (tc->failed) { return; } if (expected == actual) { return; } tc->failed = TRUE; if (verbose) { /* Note that the comparison is type-exact, reporting must be a best-fit */ fprintf(stderr, "Line %d: expected %lu, but saw %lu\n", lineno, (unsigned long)expected, (unsigned long)actual); fflush(stderr); } } void abts_str_equal(abts_case* tc, const char* expected, const char* actual, int lineno) { update_status(); if (tc->failed) { return; } if (!expected && !actual) { return; } if (expected && actual) if (!strcmp(expected, actual)) { return; } tc->failed = TRUE; if (verbose) { fprintf(stderr, "Line %d: expected <%s>, but saw <%s>\n", lineno, expected, actual); fflush(stderr); } } void abts_str_nequal(abts_case* tc, const char* expected, const char* actual, size_t n, int lineno) { update_status(); if (tc->failed) { return; } if (!strncmp(expected, actual, n)) { return; } tc->failed = TRUE; if (verbose) { fprintf(stderr, "Line %d: expected <%s>, but saw <%s>\n", lineno, expected, actual); fflush(stderr); } } void abts_ptr_notnull(abts_case* tc, const void* ptr, int lineno) { update_status(); if (tc->failed) { return; } if (ptr != NULL) { return; } tc->failed = TRUE; if (verbose) { fprintf(stderr, "Line %d: Expected NULL, but saw <%p>\n", lineno, ptr); fflush(stderr); } } void abts_ptr_equal(abts_case* tc, const void* expected, const void* actual, int lineno) { update_status(); if (tc->failed) { return; } if (expected == actual) { return; } tc->failed = TRUE; if (verbose) { fprintf(stderr, "Line %d: expected <%p>, but saw <%p>\n", lineno, expected, actual); fflush(stderr); } } void abts_fail(abts_case* tc, const char* message, int lineno) { update_status(); if (tc->failed) { return; } tc->failed = TRUE; if (verbose) { fprintf(stderr, "Line %d: %s\n", lineno, message); fflush(stderr); } } void abts_assert(abts_case* tc, const char* message, int condition, int lineno) { update_status(); if (tc->failed) { return; } if (condition) { return; } tc->failed = TRUE; if (verbose) { fprintf(stderr, "Line %d: %s\n", lineno, message); fflush(stderr); } } void abts_true(abts_case* tc, int condition, int lineno) { update_status(); if (tc->failed) { return; } if (condition) { return; } tc->failed = TRUE; if (verbose) { fprintf(stderr, "Line %d: Condition is false, but expected true\n", lineno); fflush(stderr); } } void abts_not_impl(abts_case* tc, const char* message, int lineno) { update_status(); tc->suite->not_impl++; if (verbose) { fprintf(stderr, "Line %d: %s\n", lineno, message); fflush(stderr); } } int main(int argc, const char* const argv[]) { int rv = 0; int list_provided = 0; abts_suite* suite = NULL; initialize(); #if defined(_MSC_VER) quiet = 1; #else quiet = !isatty(STDOUT_FILENO); #endif for (int i = 1; i < argc; i++) { if (!strcmp(argv[i], "-v")) { verbose = 1; continue; } if (!strcmp(argv[i], "-x")) { exclude = 1; continue; } if (!strcmp(argv[i], "-l")) { list_tests = 1; continue; } if (!strcmp(argv[i], "-q")) { quiet = 1; continue; } if (argv[i][0] == '-') { fprintf(stderr, "Invalid option: `%s'\n", argv[i]); exit(1); } list_provided = 1; } if (list_provided) { /* Waste a little space here, because it is easier than counting the * number of tests listed. Besides it is at most three char *. */ testlist = (const char**) calloc(argc + 1, sizeof(char*)); for (int i = 1; i < argc; i++) { testlist[i - 1] = argv[i]; } } suite = abts_run_suites(suite); if (suite == 0) { fputs("No tests selected\n", stderr); } else { rv = report(suite); // // clean up suite // // We're about to exit, who cares about memory leaks? sub_suite* next; for (sub_suite* head = suite->head; head != NULL; head = next) { next = head->next; delete head; } delete suite; } return rv; } apache-log4cxx-1.3.1/src/test/cpp/eventsatexittest.cpp0000644000175100001770000000226214721727031022355 0ustar runnerdocker/* * 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. */ #include using namespace log4cxx; static struct Static { Static() { std::atexit([] { Logger::getRootLogger();// no crash is expected inside }); // ensures logger state is initialized Logger::getRootLogger(); } ~Static() { Logger::getRootLogger();// no crash is expected inside } } s_static; apache-log4cxx-1.3.1/src/test/cpp/filter/0000755000175100001770000000000014721727031017511 5ustar runnerdockerapache-log4cxx-1.3.1/src/test/cpp/filter/levelmatchfiltertest.cpp0000644000175100001770000000774014721727031024457 0ustar runnerdocker/* * 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. */ #include #include #include #include #include "../logunit.h" using namespace log4cxx; using namespace log4cxx::filter; using namespace log4cxx::spi; using namespace log4cxx::helpers; /** * Unit tests for LevelMatchFilter. */ LOGUNIT_CLASS(LevelMatchFilterTest) { LOGUNIT_TEST_SUITE(LevelMatchFilterTest); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST(test3); LOGUNIT_TEST(test4); LOGUNIT_TEST(test5); LOGUNIT_TEST_SUITE_END(); public: /** * Check that LevelMatchFilter.decide() returns Filter.ACCEPT when level matches. */ void test1() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("org.apache.log4j.filter.LevelMatchFilterTest"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); LevelMatchFilterPtr filter(new LevelMatchFilter()); filter->setLevelToMatch(LOG4CXX_STR("info")); Pool p; filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(Filter::ACCEPT, filter->decide(event)); } /** * Check that LevelMatchFilter.decide() returns Filter.DENY * when level matches and acceptOnMatch = false. */ void test2() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("org.apache.log4j.filter.LevelMatchFilterTest"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); LevelMatchFilterPtr filter(new LevelMatchFilter()); filter->setLevelToMatch(LOG4CXX_STR("info")); filter->setAcceptOnMatch(false); Pool p; filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(Filter::DENY, filter->decide(event)); } /** * Check that LevelMatchFilter.decide() returns Filter.NEUTRAL * when levelToMatch is unspecified. */ void test3() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("org.apache.log4j.filter.LevelMatchFilterTest"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); LevelMatchFilterPtr filter(new LevelMatchFilter()); Pool p; filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(Filter::NEUTRAL, filter->decide(event)); } /** * Check that LevelMatchFilter.decide() returns Filter.NEUTRAL * when event level is higher than level to match. */ void test4() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("org.apache.log4j.filter.LevelMatchFilterTest"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); LevelMatchFilterPtr filter(new LevelMatchFilter()); filter->setLevelToMatch(LOG4CXX_STR("debug")); Pool p; filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(Filter::NEUTRAL, filter->decide(event)); } /** * Check that LevelMatchFilter.decide() returns Filter.NEUTRAL * when event level is lower than level to match. */ void test5() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("org.apache.log4j.filter.LevelMatchFilterTest"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); LevelMatchFilterPtr filter(new LevelMatchFilter()); filter->setLevelToMatch(LOG4CXX_STR("warn")); Pool p; filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(Filter::NEUTRAL, filter->decide(event)); } }; LOGUNIT_TEST_SUITE_REGISTRATION(LevelMatchFilterTest); apache-log4cxx-1.3.1/src/test/cpp/filter/levelrangefiltertest.cpp0000644000175100001770000001116514721727031024453 0ustar runnerdocker/* * 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. */ #include #include #include #include #include "../logunit.h" using namespace log4cxx; using namespace log4cxx::filter; using namespace log4cxx::spi; using namespace log4cxx::helpers; /** * Unit tests for LevelRangeFilter. */ LOGUNIT_CLASS(LevelRangeFilterTest) { LOGUNIT_TEST_SUITE(LevelRangeFilterTest); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST(test3); LOGUNIT_TEST(test4); LOGUNIT_TEST(test5); LOGUNIT_TEST(test6); LOGUNIT_TEST_SUITE_END(); public: /** * Check that LevelRangefilter->decide() returns Filter::DENY * when event level is below min level. */ void test1() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("org.apache.log4j.Filter::LevelRangeFilterTest"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); LevelRangeFilterPtr filter(new LevelRangeFilter()); filter->setLevelMin(Level::getWarn()); Pool p; filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(Filter::DENY, filter->decide(event)); } /** * Check that LevelRangefilter->decide() returns Filter::DENY * when event level is above max level. */ void test2() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("org.apache.log4j.Filter::LevelRangeFilterTest"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); LevelRangeFilterPtr filter(new LevelRangeFilter()); filter->setLevelMax(Level::getDebug()); Pool p; filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(Filter::DENY, filter->decide(event)); } /** * Check that LevelRangefilter->decide() returns Filter::ACCEPT * when event level is above min level. */ void test3() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("org.apache.log4j.Filter::LevelRangeFilterTest"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); LevelRangeFilterPtr filter(new LevelRangeFilter()); filter->setLevelMin(Level::getDebug()); filter->setAcceptOnMatch(true); Pool p; filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(Filter::ACCEPT, filter->decide(event)); } /** * Check that LevelRangefilter->decide() returns Filter::ACCEPT * when event level is below max level. */ void test4() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("org.apache.log4j.Filter::LevelRangeFilterTest"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); LevelRangeFilterPtr filter(new LevelRangeFilter()); filter->setLevelMax(Level::getError()); filter->setAcceptOnMatch(true); Pool p; filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(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. */ void test5() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("org.apache.log4j.Filter::LevelRangeFilterTest"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); LevelRangeFilterPtr filter(new LevelRangeFilter()); filter->setLevelMin(Level::getDebug()); Pool p; filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(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. */ void test6() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("org.apache.log4j.Filter::LevelRangeFilterTest"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); LevelRangeFilterPtr filter(new LevelRangeFilter()); filter->setLevelMax(Level::getError()); Pool p; filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(Filter::NEUTRAL, filter->decide(event)); } }; LOGUNIT_TEST_SUITE_REGISTRATION(LevelRangeFilterTest); apache-log4cxx-1.3.1/src/test/cpp/filter/andfiltertest.cpp0000644000175100001770000001270614721727031023073 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include "../logunit.h" using namespace log4cxx; using namespace log4cxx::filter; using namespace log4cxx::spi; using namespace log4cxx::helpers; /** * Unit tests for AndFilter. */ LOGUNIT_CLASS(AndFilterTest) { LOGUNIT_TEST_SUITE(AndFilterTest); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST(test3); LOGUNIT_TEST(test4); LOGUNIT_TEST(test5); LOGUNIT_TEST(test6); LOGUNIT_TEST_SUITE_END(); public: /** * Check that AndFilter.decide() returns Filter.ACCEPT if no filters added. */ void test1() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("org.apache.log4j.filter.AndFilterTest"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); FilterPtr filter(new AndFilter()); Pool p; filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(Filter::ACCEPT, filter->decide(event)); } /** * Check that AndFilter.decide() returns Filter.ACCEPT if * only nested filter returns Filter.ACCEPT. */ void test2() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("org.apache.log4j.filter.AndFilterTest"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); AndFilterPtr filter(new AndFilter()); LevelMatchFilterPtr filter1(new LevelMatchFilter()); filter1->setLevelToMatch(LOG4CXX_STR("info")); Pool p; filter1->activateOptions(p); filter->addFilter(filter1); filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(Filter::ACCEPT, filter->decide(event)); } /** * Check that AndFilter.decide() returns Filter.ACCEPT if * two nested filters return Filter.ACCEPT. */ void test3() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("org.apache.log4j.filter.AndFilterTest"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); AndFilterPtr filter(new AndFilter()); LevelMatchFilterPtr filter1(new LevelMatchFilter()); filter1->setLevelToMatch(LOG4CXX_STR("info")); Pool p; filter1->activateOptions(p); filter->addFilter(filter1); LevelMatchFilterPtr filter2(new LevelMatchFilter()); filter2->setLevelToMatch(LOG4CXX_STR("info")); filter2->activateOptions(p); filter->addFilter(filter2); filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(Filter::ACCEPT, filter->decide(event)); } /** * Check that AndFilter.decide() returns Filter.DENY if * only nested filter returns Filter.ACCEPT * and acceptOnMatch is false. */ void test4() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("org.apache.log4j.filter.AndFilterTest"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); AndFilterPtr filter(new AndFilter()); LevelMatchFilterPtr filter1(new LevelMatchFilter()); filter1->setLevelToMatch(LOG4CXX_STR("info")); Pool p; filter1->activateOptions(p); filter->addFilter(filter1); filter->setAcceptOnMatch(false); filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(Filter::DENY, filter->decide(event)); } /** * Check that AndFilter.decide() returns Filter.NEUTRAL if * nested filters return Filter.ACCEPT and Filter.DENY. */ void test5() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("org.apache.log4j.filter.AndFilterTest"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); AndFilterPtr filter(new AndFilter()); LevelMatchFilterPtr filter1(new LevelMatchFilter()); filter1->setLevelToMatch(LOG4CXX_STR("info")); Pool p; filter1->activateOptions(p); filter->addFilter(filter1); FilterPtr filter2(new DenyAllFilter()); filter2->activateOptions(p); filter->addFilter(filter2); filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(Filter::NEUTRAL, filter->decide(event)); } /** * Check that AndFilter.decide() returns Filter.NEUTRAL if * nested filters return Filter.ACCEPT and Filter.NEUTRAL. */ void test6() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("org.apache.log4j.filter.AndFilterTest"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); AndFilterPtr filter(new AndFilter()); LevelMatchFilterPtr filter1(new LevelMatchFilter()); filter1->setLevelToMatch(LOG4CXX_STR("info")); Pool p; filter1->activateOptions(p); filter->addFilter(filter1); FilterPtr filter2(new StringMatchFilter()); filter2->activateOptions(p); filter->addFilter(filter2); filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(Filter::NEUTRAL, filter->decide(event)); } }; LOGUNIT_TEST_SUITE_REGISTRATION(AndFilterTest); apache-log4cxx-1.3.1/src/test/cpp/filter/locationinfofiltertest.cpp0000644000175100001770000000724314721727031025015 0ustar runnerdocker/* * 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. */ #include #include #include #include #include "../logunit.h" using namespace log4cxx; using namespace log4cxx::filter; using namespace log4cxx::spi; using namespace log4cxx::helpers; /** * Unit tests for LocationInfo. */ LOGUNIT_CLASS(LocationInfoFilterTest) { LOGUNIT_TEST_SUITE(LocationInfoFilterTest); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST(test3); LOGUNIT_TEST(test4); LOGUNIT_TEST_SUITE_END(); public: /** * Check that LocationInfoFilter.decide() returns Filter.NEUTRAL * when nothing is configured. */ void test1() { LocationInfo li("/path/to/foo.cpp", "foo.cpp", "exampleFun", 50); LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("LocationInfoFilter"), Level::getInfo(), LOG4CXX_STR("Hello, World"), li)); FilterPtr filter(new LocationInfoFilter()); Pool p; filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(Filter::NEUTRAL, filter->decide(event)); } /** * Check that LocationInfoFilter.decide() returns Filter.NEUTRAL * when line number does not match */ void test2() { LocationInfo li("/path/to/foo.cpp", "foo.cpp", "exampleFun", 50); LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("LocationInfoFilter"), Level::getInfo(), LOG4CXX_STR("Hello, World"), li)); LocationInfoFilterPtr filter(new LocationInfoFilter()); filter->setLineNumber(10); Pool p; filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(Filter::NEUTRAL, filter->decide(event)); } /** * Check that LocationInfoFilter.decide() returns Filter.ACCEPT * when the line number matches */ void test3() { LocationInfo li("/path/to/foo.cpp", "foo.cpp", "exampleFun", 50); LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("LocationInfoFilter"), Level::getInfo(), LOG4CXX_STR("Hello, World"), li)); LocationInfoFilterPtr filter(new LocationInfoFilter()); filter->setLineNumber(50); filter->setAcceptOnMatch(true); Pool p; filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(Filter::ACCEPT, filter->decide(event)); } /** * Check that LocationInfoFilter.decide() returns Filter.ACCEPT * when the line number and method name match */ void test4() { LocationInfo li("/path/to/foo.cpp", "foo.cpp", "exampleFun", 50); LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("LocationInfoFilter"), Level::getInfo(), LOG4CXX_STR("Hello, World"), li)); LocationInfoFilterPtr filter(new LocationInfoFilter()); filter->setLineNumber(50); filter->setMethodName(LOG4CXX_STR("exampleFun")); filter->setAcceptOnMatch(true); filter->setMustMatchAll(true); Pool p; filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(Filter::ACCEPT, filter->decide(event)); } }; LOGUNIT_TEST_SUITE_REGISTRATION(LocationInfoFilterTest); apache-log4cxx-1.3.1/src/test/cpp/filter/denyallfiltertest.cpp0000644000175100001770000000331314721727031023753 0ustar runnerdocker/* * 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. */ #include #include #include #include #include "../logunit.h" using namespace log4cxx; using namespace log4cxx::filter; using namespace log4cxx::spi; using namespace log4cxx::helpers; /** * Unit tests for DenyAllFilter. */ LOGUNIT_CLASS(DenyAllFilterTest) { LOGUNIT_TEST_SUITE(DenyAllFilterTest); LOGUNIT_TEST(test1); LOGUNIT_TEST_SUITE_END(); public: /** * Check that DenyAllFilter.decide() returns Filter.DENY. */ void test1() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("org.apache.log4j.filter.DenyAllFilterTest"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); FilterPtr filter(new DenyAllFilter()); Pool p; filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(Filter::DENY, filter->decide(event)); } }; LOGUNIT_TEST_SUITE_REGISTRATION(DenyAllFilterTest); apache-log4cxx-1.3.1/src/test/cpp/filter/loggermatchfiltertest.cpp0000644000175100001770000000651214721727031024623 0ustar runnerdocker/* * 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. */ #include #include #include #include #include "../logunit.h" using namespace log4cxx; using namespace log4cxx::filter; using namespace log4cxx::spi; using namespace log4cxx::helpers; /** * Unit tests for LoggerMatchFilter. */ LOGUNIT_CLASS(LoggerMatchFilterTest) { LOGUNIT_TEST_SUITE(LoggerMatchFilterTest); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST(test3); LOGUNIT_TEST(test4); LOGUNIT_TEST_SUITE_END(); public: /** * Check that LoggerMatchFilter::decide() with unspecified level * returns Filter::ACCEPT for root logger. */ void test1() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("root"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); FilterPtr filter(new LoggerMatchFilter()); Pool p; filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(Filter::ACCEPT, filter->decide(event)); } /** * Check that LoggerMatchFilter::decide() with unspecified level * returns Filter::DENY for root logger when accept on match is false. */ void test2() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("root"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); LoggerMatchFilterPtr filter(new LoggerMatchFilter()); filter->setAcceptOnMatch(false); Pool p; filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(Filter::DENY, filter->decide(event)); } /** * Check that LoggerMatchFilter::decide() with unspecified level * returns Filter::NEUTRAL for non-root logger. */ void test3() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("org.apache.log4j.filter.LoggerMatchFilterTest"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); FilterPtr filter(new LoggerMatchFilter()); Pool p; filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(Filter::NEUTRAL, filter->decide(event)); } /** * Check that LoggerMatchFilter::decide() * returns Filter::ACCEPT for matching logger. */ void test4() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("org.apache.log4j.filter.LoggerMatchFilterTest"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); LoggerMatchFilterPtr filter(new LoggerMatchFilter()); filter->setLoggerToMatch(LOG4CXX_STR("org.apache.log4j.filter.LoggerMatchFilterTest")); Pool p; filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(Filter::ACCEPT, filter->decide(event)); } }; LOGUNIT_TEST_SUITE_REGISTRATION(LoggerMatchFilterTest); apache-log4cxx-1.3.1/src/test/cpp/filter/stringmatchfiltertest.cpp0000644000175100001770000001006514721727031024650 0ustar runnerdocker/* * 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. */ #include #include #include #include #include "../logunit.h" using namespace log4cxx; using namespace log4cxx::filter; using namespace log4cxx::spi; using namespace log4cxx::helpers; /** * Unit tests for StringMatchFilter. */ LOGUNIT_CLASS(StringMatchFilterTest) { LOGUNIT_TEST_SUITE(StringMatchFilterTest); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST(test3); LOGUNIT_TEST(test4); LOGUNIT_TEST_SUITE_END(); public: /** * Check that StringMatchFilter.decide() returns Filter.NEUTRAL * when string to match is unspecified. */ void test1() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("org.apache.log4j.filter.StringMatchFilterTest"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); FilterPtr filter(new StringMatchFilter()); Pool p; filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(Filter::NEUTRAL, filter->decide(event)); } /** * Check that StringMatchFilter.decide() returns Filter.NEUTRAL * when string to match does not appear in message. */ void test2() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("org.apache.log4j.filter.StringMatchFilterTest"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); StringMatchFilterPtr filter(new StringMatchFilter()); filter->setStringToMatch(LOG4CXX_STR("Monde")); Pool p; filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(Filter::NEUTRAL, filter->decide(event)); } /** * Check that StringMatchFilter.decide() returns Filter.ACCEPT * when string to match does appear in message. */ void test3() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("org.apache.log4j.filter.StringMatchFilterTest"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); StringMatchFilterPtr filter(new StringMatchFilter()); filter->setStringToMatch(LOG4CXX_STR("World")); Pool p; filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(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. */ void test4() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("org.apache.log4j.filter.StringMatchFilterTest"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); StringMatchFilterPtr filter(new StringMatchFilter()); filter->setStringToMatch(LOG4CXX_STR("World")); filter->setAcceptOnMatch(false); Pool p; filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(Filter::DENY, filter->decide(event)); } /** * Check that StringMatchFilter.decide() returns Filter.NEUTRAL * when string to match does appear in message but differs in case. */ void test5() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("org.apache.log4j.filter.StringMatchFilterTest"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); StringMatchFilterPtr filter(new StringMatchFilter()); filter->setStringToMatch(LOG4CXX_STR("world")); Pool p; filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(Filter::NEUTRAL, filter->decide(event)); } }; LOGUNIT_TEST_SUITE_REGISTRATION(StringMatchFilterTest); apache-log4cxx-1.3.1/src/test/cpp/filter/CMakeLists.txt0000644000175100001770000000212114721727031022245 0ustar runnerdocker# # 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. # add_executable(filtertests andfiltertest.cpp denyallfiltertest.cpp levelmatchfiltertest.cpp levelrangefiltertest.cpp loggermatchfiltertest.cpp mapfiltertest.cpp stringmatchfiltertest.cpp locationinfofiltertest.cpp ) set(ALL_LOG4CXX_TESTS ${ALL_LOG4CXX_TESTS} filtertests PARENT_SCOPE) apache-log4cxx-1.3.1/src/test/cpp/filter/mapfiltertest.cpp0000644000175100001770000001205314721727031023101 0ustar runnerdocker/* * 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. */ #include #include #include #include #include "../logunit.h" using namespace log4cxx; using namespace log4cxx::filter; using namespace log4cxx::spi; using namespace log4cxx::helpers; /** * Unit tests for MapFilter. */ LOGUNIT_CLASS(MapFilterTest) { LOGUNIT_TEST_SUITE(MapFilterTest); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST(test3); LOGUNIT_TEST(test4); LOGUNIT_TEST_SUITE_END(); public: /** * Check that MapFilter.decide() returns Filter.NEUTRAL * when there are no map entries specified. */ void test1() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("MapFilterTest"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); FilterPtr filter(new MapFilter()); Pool p; filter->activateOptions(p); LOGUNIT_ASSERT_EQUAL(Filter::NEUTRAL, filter->decide(event)); } /** * Check that MapFilter.decide() returns Filter.NEUTRAL * when key/value does not match */ void test2() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("MapFilterTest"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); MDC::put(LOG4CXX_STR("my.ip"), LOG4CXX_STR("localhost")); MapFilterPtr filter(new MapFilter()); filter->setKeyValue(LOG4CXX_STR("my.ip"), LOG4CXX_STR("127.0.0.1")); Pool p; filter->activateOptions(p); filter->setAcceptOnMatch(true); LOGUNIT_ASSERT_EQUAL(Filter::NEUTRAL, filter->decide(event)); filter->setAcceptOnMatch(false); LOGUNIT_ASSERT_EQUAL(Filter::NEUTRAL, filter->decide(event)); } /** * Check that MapFilter.decide() returns Filter.ACCEPT or Filter.DENY * based on Accept on Match setting when key/value matches */ void test3() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("MapFilterTest"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); MDC::put(LOG4CXX_STR("my.ip"), LOG4CXX_STR("127.0.0.1")); MapFilterPtr filter(new MapFilter()); filter->setKeyValue(LOG4CXX_STR("my.ip"), LOG4CXX_STR("127.0.0.1")); Pool p; filter->activateOptions(p); filter->setAcceptOnMatch(true); LOGUNIT_ASSERT_EQUAL(Filter::ACCEPT, filter->decide(event)); filter->setAcceptOnMatch(false); LOGUNIT_ASSERT_EQUAL(Filter::DENY, filter->decide(event)); } /** * Check that MapFilter.decide() ANDs or ORs multiple key/values * based on operator setting */ void test4() { LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("MapFilterTest"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); MDC::put(LOG4CXX_STR("my.ip"), LOG4CXX_STR("127.0.0.1")); MDC::put(LOG4CXX_STR("my.name"), LOG4CXX_STR("Test")); MapFilterPtr filter(new MapFilter()); filter->setKeyValue(LOG4CXX_STR("my.ip"), LOG4CXX_STR("127.0.0.1")); filter->setKeyValue(LOG4CXX_STR("my.name"), LOG4CXX_STR("Unknown")); filter->setAcceptOnMatch(true); Pool p; filter->activateOptions(p); filter->setMustMatchAll(true); // AND T/F LOGUNIT_ASSERT_EQUAL(Filter::NEUTRAL, filter->decide(event)); // does not match second filter->setMustMatchAll(false); // OR T/F LOGUNIT_ASSERT_EQUAL(Filter::ACCEPT, filter->decide(event)); // matches first filter->setKeyValue(LOG4CXX_STR("my.name"), LOG4CXX_STR("Test")); filter->setMustMatchAll(true); // AND T/T LOGUNIT_ASSERT_EQUAL(Filter::ACCEPT, filter->decide(event)); // matches all filter->setMustMatchAll(false); // OR T/T LOGUNIT_ASSERT_EQUAL(Filter::ACCEPT, filter->decide(event)); // matches first filter->setKeyValue(LOG4CXX_STR("my.ip"), LOG4CXX_STR("localhost")); filter->setMustMatchAll(true); // AND F/T LOGUNIT_ASSERT_EQUAL(Filter::NEUTRAL, filter->decide(event)); // does not match first filter->setMustMatchAll(false); // OR F/T LOGUNIT_ASSERT_EQUAL(Filter::ACCEPT, filter->decide(event)); // matches second filter->setKeyValue(LOG4CXX_STR("my.name"), LOG4CXX_STR("Unkonwn")); filter->setMustMatchAll(true); // AND F/F LOGUNIT_ASSERT_EQUAL(Filter::NEUTRAL, filter->decide(event)); // does not match first filter->setMustMatchAll(false); // OR F/F LOGUNIT_ASSERT_EQUAL(Filter::NEUTRAL, filter->decide(event)); // matches none } }; LOGUNIT_TEST_SUITE_REGISTRATION(MapFilterTest); apache-log4cxx-1.3.1/src/test/cpp/hierarchythresholdtestcase.cpp0000644000175100001770000000737114721727031024367 0ustar runnerdocker/* * 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. */ #include #include #include "util/compare.h" #include "xml/xlevel.h" #include "logunit.h" #include "testchar.h" #include using namespace log4cxx; /** Test the configuration of the hierarchy-wide threshold. */ LOGUNIT_CLASS(HierarchyThresholdTestCase) { LOGUNIT_TEST_SUITE(HierarchyThresholdTestCase); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST(test3); LOGUNIT_TEST(test4); LOGUNIT_TEST(test5); LOGUNIT_TEST(test6); LOGUNIT_TEST(test7); LOGUNIT_TEST(test8); LOGUNIT_TEST_SUITE_END(); public: void setUp() { } void tearDown() { auto rep = logger->getLoggerRepository(); if (rep) { rep->resetConfiguration(); } } void test1() { PropertyConfigurator::configure(LOG4CXX_FILE("input/hierarchyThreshold1.properties")); common(); LOGUNIT_ASSERT(Compare::compare(TEMP, LOG4CXX_FILE("witness/hierarchyThreshold.1"))); } void test2() { PropertyConfigurator::configure(LOG4CXX_FILE("input/hierarchyThreshold2.properties")); common(); LOGUNIT_ASSERT(Compare::compare(TEMP, LOG4CXX_FILE("witness/hierarchyThreshold.2"))); } void test3() { PropertyConfigurator::configure(LOG4CXX_FILE("input/hierarchyThreshold3.properties")); common(); LOGUNIT_ASSERT(Compare::compare(TEMP, LOG4CXX_FILE("witness/hierarchyThreshold.3"))); } void test4() { PropertyConfigurator::configure(LOG4CXX_FILE("input/hierarchyThreshold4.properties")); common(); LOGUNIT_ASSERT(Compare::compare(TEMP, LOG4CXX_FILE("witness/hierarchyThreshold.4"))); } void test5() { PropertyConfigurator::configure(LOG4CXX_FILE("input/hierarchyThreshold5.properties")); common(); LOGUNIT_ASSERT(Compare::compare(TEMP, LOG4CXX_FILE("witness/hierarchyThreshold.5"))); } void test6() { PropertyConfigurator::configure(LOG4CXX_FILE("input/hierarchyThreshold6.properties")); common(); LOGUNIT_ASSERT(Compare::compare(TEMP, LOG4CXX_FILE("witness/hierarchyThreshold.6"))); } void test7() { PropertyConfigurator::configure(LOG4CXX_FILE("input/hierarchyThreshold7.properties")); common(); LOGUNIT_ASSERT(Compare::compare(TEMP, LOG4CXX_FILE("witness/hierarchyThreshold.7"))); } void test8() { PropertyConfigurator::configure(LOG4CXX_FILE("input/hierarchyThreshold8.properties")); common(); LOGUNIT_ASSERT(Compare::compare(TEMP, LOG4CXX_FILE("witness/hierarchyThreshold.8"))); } static void common() { logger->log(XLevel::getTrace(), LOG4CXX_TEST_STR("m0")); logger->debug(LOG4CXX_TEST_STR("m1")); logger->info(LOG4CXX_TEST_STR("m2")); logger->warn(LOG4CXX_TEST_STR("m3")); logger->error(LOG4CXX_TEST_STR("m4")); logger->fatal(LOG4CXX_TEST_STR("m5")); } private: static File TEMP; static LoggerPtr logger; }; File HierarchyThresholdTestCase::TEMP(LOG4CXX_FILE("output/hierarchythreshold")); LoggerPtr HierarchyThresholdTestCase::logger = Logger::getLogger(LOG4CXX_TEST_STR("HierarchyThresholdTestCase")); LOGUNIT_TEST_SUITE_REGISTRATION(HierarchyThresholdTestCase); apache-log4cxx-1.3.1/src/test/cpp/fileappendertestcase.cpp0000644000175100001770000000735314721727031023132 0ustar runnerdocker/* * 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. */ #include "fileappendertestcase.h" #include #include "insertwide.h" using namespace log4cxx; using namespace log4cxx::helpers; WriterAppender* FileAppenderAbstractTestCase::createWriterAppender() const { return createFileAppender(); } /** Unit tests of log4cxx::FileAppender */ class FileAppenderTestCase : public FileAppenderAbstractTestCase { LOGUNIT_TEST_SUITE(FileAppenderTestCase); // // tests inherited from AppenderSkeletonTestCase // LOGUNIT_TEST(testDefaultThreshold); LOGUNIT_TEST(testSetOptionThreshold); // tests defined here LOGUNIT_TEST(testSetDoubleBackslashes); LOGUNIT_TEST(testStripDuplicateBackslashes); LOGUNIT_TEST_SUITE_END(); public: FileAppender* createFileAppender() const { return new log4cxx::FileAppender(); } void testSetDoubleBackslashes() { FileAppender appender; appender.setOption(LOG4CXX_STR("FILE"), LOG4CXX_STR("output\\\\temp")); const File& file = appender.getFile(); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("output\\temp"), file.getPath()); } /** * Tests that double backslashes in filespecs are stripped * on calls to setOption. * */ void testStripDoubleBackslashes() { FileAppender appender; appender.setOption(LOG4CXX_STR("FILE"), LOG4CXX_STR("output\\\\temp")); const File& file = appender.getFile(); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("output\\temp"), file.getPath()); } /** * Tests stripDuplicateBackslashes * * */ void testStripDuplicateBackslashes() { LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("\\foo\\bar\\foo"), FileAppender::stripDuplicateBackslashes(LOG4CXX_STR("\\foo\\bar\\foo"))); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("\\foo\\bar\\foo\\"), FileAppender::stripDuplicateBackslashes(LOG4CXX_STR("\\\\foo\\\\bar\\\\foo\\\\"))); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("\\foo\\bar\\foo\\"), FileAppender::stripDuplicateBackslashes(LOG4CXX_STR("\\foo\\bar\\foo\\"))); // // UNC's should either start with two backslashes and contain additional singles // or four back slashes and addition doubles LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("\\\\foo\\bar\\foo"), FileAppender::stripDuplicateBackslashes(LOG4CXX_STR("\\\\\\\\foo\\\\bar\\\\foo"))); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("\\\\foo\\bar\\foo"), FileAppender::stripDuplicateBackslashes(LOG4CXX_STR("\\\\foo\\bar\\foo"))); // // it it starts with doubles but has no other path component // then it is a file path LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("\\foo.log"), FileAppender::stripDuplicateBackslashes(LOG4CXX_STR("\\\\foo.log"))); // // it it starts with quads but has no other path component // then it is a UNC LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("\\\\foo.log"), FileAppender::stripDuplicateBackslashes(LOG4CXX_STR("\\\\\\\\foo.log"))); } }; LOGUNIT_TEST_SUITE_REGISTRATION(FileAppenderTestCase); apache-log4cxx-1.3.1/src/test/cpp/benchmark/0000755000175100001770000000000014721727031020156 5ustar runnerdockerapache-log4cxx-1.3.1/src/test/cpp/benchmark/CMakeLists.txt0000644000175100001770000000576414721727031022732 0ustar runnerdocker# # 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. # option(BUILD_BENCHMARK_CHECKS "Build google benchmark checks" OFF) if( NOT BUILD_BENCHMARK_CHECKS ) return() endif() find_package(benchmark REQUIRED) set(BENCHMARK_TARGETS benchmark::benchmark benchmark::benchmark_main) set(LOG4CXX_HAS_FMT 0) if(NOT LOG4CXX_USE_STANDARD_FORMAT) find_package(fmt QUIET) if(fmt_FOUND) set(LOG4CXX_HAS_FMT 1) list(APPEND BENCHMARK_TARGETS fmt::fmt) endif() endif() add_executable(benchmark benchmark.cpp) # Note: we need to include the APR DLLs on our path so that the tests will run. # The way that CMake sets the environment is that it actually generates a secondary file, # CTestTestfile.cmake, which sets the final properties of the test. # However, this results in a secondary quirk to the running of the tests: CMake uses # a semicolon to deliminate entries in a list! Since the Windows PATH is semicolon-delimited # as well, CMake uses only the first entry in the list when setting the path. # So, we need to do a triple escape on the PATH that we want to set in order for CMake to # properly interpret the PATH if( WIN32 ) get_filename_component(APR_DLL_DIR "${APR_DLL}" DIRECTORY) get_filename_component(APR_UTIL_DLL_DIR "${APR_UTIL_DLL}" DIRECTORY) set(EXPAT_DLL_DIR "${EXPAT_LIB_DIR}/../bin") set(LOG4CXX_DLL_DIR "$>;") set(PATH_FOR_TESTS ${CMAKE_PROGRAM_PATH};${APR_DLL_DIR};${APR_UTIL_DLL_DIR};${LOG4CXX_DLL_DIR}\;) list(REMOVE_DUPLICATES PATH_FOR_TESTS) set(NORMAL_PATH $ENV{PATH}) set(ESCAPED_PATH "") foreach( ENTRY ${PATH_FOR_TESTS}${NORMAL_PATH} ) set(ESCAPED_PATH "${ESCAPED_PATH}${ENTRY}\\\;") endforeach() set_target_properties(benchmark PROPERTIES VS_DEBUGGER_ENVIRONMENT "LOG4CXX_BENCHMARK_THREAD_COUNT=4\nPATH=${ESCAPED_PATH}" ) else() add_custom_target(run-benchmarks COMMAND benchmark DEPENDS benchmark) endif( WIN32 ) target_compile_definitions(benchmark PRIVATE "LOG4CXX_HAS_FMT=${LOG4CXX_HAS_FMT}" ${LOG4CXX_COMPILE_DEFINITIONS} ${APR_COMPILE_DEFINITIONS} ${APR_UTIL_COMPILE_DEFINITIONS} ) target_include_directories(benchmark PRIVATE $) target_link_libraries(benchmark PRIVATE log4cxx ${APR_LIBRARIES} ${APR_SYSTEM_LIBS} Threads::Threads ${BENCHMARK_TARGETS}) apache-log4cxx-1.3.1/src/test/cpp/benchmark/benchmark.cpp0000644000175100001770000002535614721727031022627 0ustar runnerdocker#include #include #include #include #include #include #include #include #include #include #if LOG4CXX_USING_STD_FORMAT #include #elif LOG4CXX_HAS_FMT #include #endif #include #include #include #include using namespace log4cxx; class NullWriterAppender : public AppenderSkeleton { public: NullWriterAppender(const LayoutPtr& layout) { setLayout(layout); } void close() override {} bool requiresLayout() const override { return true; } void append(const spi::LoggingEventPtr& event, helpers::Pool& p) override { LogString buf; m_priv->layout->format(buf, event, p); } void activateOptions(helpers::Pool& /* pool */) override { } void setOption(const LogString& option, const LogString& value) override { } }; class BenchmarkFileAppender : public FileAppender { public: BenchmarkFileAppender(const LayoutPtr& layout) { setLayout(layout); auto tempDir = helpers::OptionConverter::getSystemProperty(LOG4CXX_STR("TEMP"), LOG4CXX_STR("/tmp")); setFile(tempDir + LOG4CXX_STR("/") + LOG4CXX_STR("benchmark.log")); setAppend(false); setBufferedIO(true); helpers::Pool p; activateOptions(p); } }; void disableThousandSeparatorsInJSON() { std::setlocale(LC_ALL, "C"); /* Set locale for C functions */ std::locale::global(std::locale("C")); /* set locale for C++ functions */ } class benchmarker : public ::benchmark::Fixture { public: // Attributes LoggerPtr m_logger = getLogger(); LoggerPtr m_asyncLogger = getAsyncLogger(); LoggerPtr m_fileLogger = getFileLogger(); public: // Class methods static int threadCount() { auto threadCount = helpers::StringHelper::toInt (helpers::OptionConverter::getSystemProperty (LOG4CXX_STR("LOG4CXX_BENCHMARK_THREAD_COUNT"), LOG4CXX_STR("0"))); if (threadCount <= 0) threadCount = std::thread::hardware_concurrency() - 2; return threadCount; } static double warmUpSeconds() { auto milliseconds = helpers::StringHelper::toInt (helpers::OptionConverter::getSystemProperty (LOG4CXX_STR("LOG4CXX_BENCHMARK_WARM_UP_MILLISECONDS"), LOG4CXX_STR("0"))); if (milliseconds <= 0) milliseconds = 100; return milliseconds / 1000; } static void setDefaultAppender() { auto r = LogManager::getLoggerRepository(); r->ensureIsConfigured([r]() { disableThousandSeparatorsInJSON(); auto writer = std::make_shared(std::make_shared(LOG4CXX_STR("%m%n"))); writer->setName(LOG4CXX_STR("NullAppender")); r->getRootLogger()->addAppender(writer); }); } static LoggerPtr getLogger(const LogString& pattern = LogString()) { static struct initializer { initializer() { setDefaultAppender(); } ~initializer() { LogManager::shutdown(); } } x; LogString name = LOG4CXX_STR("benchmark.fixture"); LoggerPtr result; auto r = LogManager::getLoggerRepository(); if (pattern.empty()) result = r->getLogger(name); else if (!(result = r->exists(name += LOG4CXX_STR(".") + pattern))) { result = r->getLogger(name); result->setAdditivity(false); result->setLevel(Level::getInfo()); auto writer = std::make_shared(std::make_shared(pattern)); writer->setName(LOG4CXX_STR("NullAppender.") + pattern); result->addAppender(writer); } return result; } static LoggerPtr getAsyncLogger() { LogString name = LOG4CXX_STR("benchmark.fixture.async"); auto r = LogManager::getLoggerRepository(); LoggerPtr result = r->exists(name); if (!result) { setDefaultAppender(); auto writer = std::make_shared(); writer->setLayout(std::make_shared(LOG4CXX_STR("%m%n"))); auto asyncAppender = std::make_shared(); asyncAppender->addAppender(writer); asyncAppender->setBlocking(false); result = r->getLogger(name); result->setAdditivity(false); result->setLevel(Level::getInfo()); result->addAppender(asyncAppender); } return result; } static LoggerPtr getFileLogger() { LogString name = LOG4CXX_STR("benchmark.fixture.file"); auto r = LogManager::getLoggerRepository(); LoggerPtr result; if (!(result = r->exists(name))) { result = r->getLogger(name); result->setAdditivity(false); result->setLevel(Level::getInfo()); auto writer = std::make_shared(std::make_shared(LOG4CXX_STR("%d %m%n"))); writer->setName(LOG4CXX_STR("FileAppender")); writer->setBufferedIO(true); helpers::Pool p; writer->activateOptions(p); result->addAppender(writer); } return result; } }; BENCHMARK_DEFINE_F(benchmarker, logDisabledTrace)(benchmark::State& state) { m_logger->setLevel(Level::getDebug()); for (auto _ : state) { LOG4CXX_TRACE( m_logger, LOG4CXX_STR("Hello: static string message")); } } BENCHMARK_REGISTER_F(benchmarker, logDisabledTrace)->Name("Testing disabled logging request")->MinWarmUpTime(benchmarker::warmUpSeconds()); BENCHMARK_REGISTER_F(benchmarker, logDisabledTrace)->Name("Testing disabled logging request")->Threads(benchmarker::threadCount()); BENCHMARK_DEFINE_F(benchmarker, logShortString)(benchmark::State& state) { m_logger->setLevel(Level::getInfo()); for (auto _ : state) { LOG4CXX_INFO(m_logger, LOG4CXX_STR("Hello")); } } BENCHMARK_REGISTER_F(benchmarker, logShortString)->Name("Appending 5 char string using MessageBuffer, pattern: %m%n"); BENCHMARK_REGISTER_F(benchmarker, logShortString)->Name("Appending 5 char string using MessageBuffer, pattern: %m%n")->Threads(benchmarker::threadCount()); BENCHMARK_DEFINE_F(benchmarker, logLongString)(benchmark::State& state) { m_logger->setLevel(Level::getInfo()); for (auto _ : state) { LOG4CXX_INFO( m_logger, LOG4CXX_STR("Hello: this is a long static string message")); } } BENCHMARK_REGISTER_F(benchmarker, logLongString)->Name("Appending 49 char string using MessageBuffer, pattern: %m%n"); BENCHMARK_REGISTER_F(benchmarker, logLongString)->Name("Appending 49 char string using MessageBuffer, pattern: %m%n")->Threads(benchmarker::threadCount()); BENCHMARK_DEFINE_F(benchmarker, logIntValueMessageBuffer)(benchmark::State& state) { int x = 0; for (auto _ : state) { LOG4CXX_INFO( m_logger, "Hello: message number " << ++x); } } BENCHMARK_REGISTER_F(benchmarker, logIntValueMessageBuffer)->Name("Appending int value using MessageBuffer, pattern: %m%n"); BENCHMARK_REGISTER_F(benchmarker, logIntValueMessageBuffer)->Name("Appending int value using MessageBuffer, pattern: %m%n")->Threads(benchmarker::threadCount()); BENCHMARK_DEFINE_F(benchmarker, logIntPlusFloatMessageBuffer)(benchmark::State& state) { int x = 0; for (auto _ : state) { auto f = static_cast(rand()) / static_cast(RAND_MAX); LOG4CXX_INFO( m_logger, "Hello: message number " << ++x << " pseudo-random float " << std::setprecision(3) << std::fixed << f); } } BENCHMARK_REGISTER_F(benchmarker, logIntPlusFloatMessageBuffer)->Name("Appending int+float using MessageBuffer, pattern: %m%n"); BENCHMARK_REGISTER_F(benchmarker, logIntPlusFloatMessageBuffer)->Name("Appending int+float using MessageBuffer, pattern: %m%n")->Threads(benchmarker::threadCount()); template void logWithConversionPattern(benchmark::State& state, Args&&... args) { auto args_tuple = std::make_tuple(std::move(args)...); LogString conversionPattern = std::get<0>(args_tuple); auto logger = benchmarker::getLogger(conversionPattern); int x = 0; for (auto _ : state) { LOG4CXX_INFO( logger, LOG4CXX_STR("Hello: msg number ") << ++x); } } BENCHMARK_CAPTURE(logWithConversionPattern, DateMessage, LOG4CXX_STR("[%d] %m%n"))->Name("Appending int value using MessageBuffer, pattern: [%d] %m%n"); BENCHMARK_CAPTURE(logWithConversionPattern, DateClassLevelMessage, LOG4CXX_STR("[%d] [%c] [%p] %m%n"))->Name("Appending int value using MessageBuffer, pattern: [%d] [%c] [%p] %m%n"); #if LOG4CXX_USING_STD_FORMAT || LOG4CXX_HAS_FMT BENCHMARK_DEFINE_F(benchmarker, logLongStringFMT)(benchmark::State& state) { for (auto _ : state) { LOG4CXX_INFO_FMT(m_logger, "Hello: this is a long static string message", 0); } } BENCHMARK_REGISTER_F(benchmarker, logLongStringFMT)->Name("Appending 49 char string using FMT, pattern: %m%n"); BENCHMARK_REGISTER_F(benchmarker, logLongStringFMT)->Name("Appending 49 char string using FMT, pattern: %m%n")->Threads(benchmarker::threadCount()); BENCHMARK_DEFINE_F(benchmarker, logIntValueFMT)(benchmark::State& state) { int x = 0; for (auto _ : state) { LOG4CXX_INFO_FMT(m_logger, "Hello: msg number {}", ++x); } } BENCHMARK_REGISTER_F(benchmarker, logIntValueFMT)->Name("Appending int value using FMT, pattern: %m%n"); BENCHMARK_REGISTER_F(benchmarker, logIntValueFMT)->Name("Appending int value using FMT, pattern: %m%n")->Threads(benchmarker::threadCount()); BENCHMARK_DEFINE_F(benchmarker, logIntPlusFloatValueFMT)(benchmark::State& state) { int x = 0; for (auto _ : state) { auto f = static_cast(rand()) / static_cast(RAND_MAX); LOG4CXX_INFO_FMT(m_logger, "Hello: msg number {} pseudo-random float {:.3f}", ++x, f); } } BENCHMARK_REGISTER_F(benchmarker, logIntPlusFloatValueFMT)->Name("Appending int+float using FMT, pattern: %m%n"); BENCHMARK_REGISTER_F(benchmarker, logIntPlusFloatValueFMT)->Name("Appending int+float using FMT, pattern: %m%n")->Threads(benchmarker::threadCount()); #endif BENCHMARK_DEFINE_F(benchmarker, asyncIntPlusFloatValueMessageBuffer)(benchmark::State& state) { int x = 0; for (auto _ : state) { auto f = static_cast(rand()) / static_cast(RAND_MAX); LOG4CXX_INFO( m_asyncLogger, "Hello: message number " << ++x << " pseudo-random float " << std::setprecision(3) << std::fixed << f); } } BENCHMARK_REGISTER_F(benchmarker, asyncIntPlusFloatValueMessageBuffer)->Name("Async, Sending int+float using MessageBuffer"); BENCHMARK_REGISTER_F(benchmarker, asyncIntPlusFloatValueMessageBuffer)->Name("Async, Sending int+float using MessageBuffer")->Threads(benchmarker::threadCount()); BENCHMARK_DEFINE_F(benchmarker, fileIntPlusFloatValueMessageBuffer)(benchmark::State& state) { int x = 0; for (auto _ : state) { auto f = static_cast(rand()) / static_cast(RAND_MAX); LOG4CXX_INFO( m_fileLogger, "Hello: message number " << ++x << " pseudo-random float " << std::setprecision(3) << std::fixed << f); } } BENCHMARK_REGISTER_F(benchmarker, fileIntPlusFloatValueMessageBuffer)->Name("Logging int+float using MessageBuffer, pattern: %d %m%n"); BENCHMARK_REGISTER_F(benchmarker, fileIntPlusFloatValueMessageBuffer)->Name("Logging int+float using MessageBuffer, pattern: %d %m%n")->Threads(benchmarker::threadCount()); BENCHMARK_MAIN(); apache-log4cxx-1.3.1/src/test/cpp/rolling/0000755000175100001770000000000014721727031017672 5ustar runnerdockerapache-log4cxx-1.3.1/src/test/cpp/rolling/sizebasedrollingtest.cpp0000644000175100001770000003010014721727031024630 0ustar runnerdocker/* * 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. */ #include "../util/compare.h" #include "../insertwide.h" #include "../logunit.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace log4cxx; using namespace log4cxx::filter; using namespace log4cxx::helpers; using namespace log4cxx::rolling; /** * * Do not forget to call activateOptions when configuring programatically. * * * */ LOGUNIT_CLASS(SizeBasedRollingTest) { LOGUNIT_TEST_SUITE(SizeBasedRollingTest); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST(test3); LOGUNIT_TEST(test4); LOGUNIT_TEST(test5); LOGUNIT_TEST(test6); LOGUNIT_TEST_SUITE_END(); LoggerPtr root; LoggerPtr logger; public: void setUp() { BasicConfigurator::configure(std::make_shared ( LOG4CXX_STR("%d %level %c -%m%n") )); root = Logger::getRootLogger(); logger = Logger::getLogger("org.apache.log4j.rolling.SizeBasedRollingTest"); } void tearDown() { LogManager::shutdown(); } void common(LoggerPtr & logger1, int /*sleep*/) { char msg[] = { 'H', 'e', 'l', 'l', 'o', '-', '-', '-', 'N', 0 }; // Write exactly 10 bytes with each log for (int i = 0; i < 25; i++) { if (i < 10) { msg[8] = '0' + i; } else if (i < 100) { msg[7] = '0' + i / 10; msg[8] = '0' + i % 10; } LOG4CXX_DEBUG(logger1, msg); } } /** * Tests that the lack of an explicit active file will use the * low index as the active file. * */ void test1() { PatternLayoutPtr layout = PatternLayoutPtr(new PatternLayout(LOG4CXX_STR("%m\n"))); RollingFileAppenderPtr rfa = RollingFileAppenderPtr(new RollingFileAppender()); rfa->setName(LOG4CXX_STR("ROLLING")); rfa->setAppend(false); rfa->setLayout(layout); FixedWindowRollingPolicyPtr swrp = FixedWindowRollingPolicyPtr(new FixedWindowRollingPolicy()); SizeBasedTriggeringPolicyPtr sbtp = SizeBasedTriggeringPolicyPtr(new SizeBasedTriggeringPolicy()); sbtp->setMaxFileSize(100); swrp->setMinIndex(0); swrp->setFileNamePattern(LOG4CXX_STR("output/sizeBased-test1.%i")); Pool p; swrp->activateOptions(p); rfa->setRollingPolicy(swrp); rfa->setTriggeringPolicy(sbtp); rfa->activateOptions(p); root->addAppender(rfa); common(logger, 0); LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test1.0").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test1.1").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test1.2").exists(p)); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sizeBased-test1.0"), File("witness/rolling/sbr-test2.log"))); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sizeBased-test1.1"), File("witness/rolling/sbr-test2.0"))); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sizeBased-test1.2"), File("witness/rolling/sbr-test2.1"))); } /** * Test basic rolling functionality with explicit setting of FileAppender.file. */ void test2() { PatternLayoutPtr layout = PatternLayoutPtr(new PatternLayout(LOG4CXX_STR("%m\n"))); RollingFileAppenderPtr rfa = RollingFileAppenderPtr(new RollingFileAppender()); rfa->setName(LOG4CXX_STR("ROLLING")); rfa->setAppend(false); rfa->setLayout(layout); rfa->setFile(LOG4CXX_STR("output/sizeBased-test2.log")); FixedWindowRollingPolicyPtr swrp = FixedWindowRollingPolicyPtr(new FixedWindowRollingPolicy()); SizeBasedTriggeringPolicyPtr sbtp = SizeBasedTriggeringPolicyPtr(new SizeBasedTriggeringPolicy()); sbtp->setMaxFileSize(100); swrp->setMinIndex(0); swrp->setFileNamePattern(LOG4CXX_STR("output/sizeBased-test2.%i")); Pool p; swrp->activateOptions(p); rfa->setRollingPolicy(swrp); rfa->setTriggeringPolicy(sbtp); rfa->activateOptions(p); root->addAppender(rfa); common(logger, 0); LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test2.log").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test2.0").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test2.1").exists(p)); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sizeBased-test2.log"), File("witness/rolling/sbr-test2.log"))); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sizeBased-test2.0"), File("witness/rolling/sbr-test2.0"))); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sizeBased-test2.1"), File("witness/rolling/sbr-test2.1"))); } /** * Same as testBasic but also with GZ compression. */ void test3() { PatternLayoutPtr layout = PatternLayoutPtr(new PatternLayout(LOG4CXX_STR("%m\n"))); RollingFileAppenderPtr rfa = RollingFileAppenderPtr(new RollingFileAppender()); rfa->setAppend(false); rfa->setLayout(layout); FixedWindowRollingPolicyPtr fwrp = FixedWindowRollingPolicyPtr(new FixedWindowRollingPolicy()); SizeBasedTriggeringPolicyPtr sbtp = SizeBasedTriggeringPolicyPtr(new SizeBasedTriggeringPolicy()); sbtp->setMaxFileSize(100); fwrp->setMinIndex(0); rfa->setFile(LOG4CXX_STR("output/sbr-test3.log")); fwrp->setFileNamePattern(LOG4CXX_STR("output/sbr-test3.%i.gz")); Pool p; fwrp->activateOptions(p); rfa->setRollingPolicy(fwrp); rfa->setTriggeringPolicy(sbtp); rfa->activateOptions(p); root->addAppender(rfa); common(logger, 100); LOGUNIT_ASSERT_EQUAL(true, File("output/sbr-test3.log").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/sbr-test3.0.gz").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/sbr-test3.1.gz").exists(p)); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sbr-test3.log"), File("witness/rolling/sbr-test3.log"))); LOGUNIT_ASSERT_EQUAL(File("witness/rolling/sbr-test3.0.gz").length(p), File("output/sbr-test3.0.gz").length(p)); LOGUNIT_ASSERT_EQUAL(File("witness/rolling/sbr-test3.1.gz").length(p), File("output/sbr-test3.1.gz").length(p)); } /** * Test basic rolling functionality with bogus path in file name pattern. */ void test4() { PatternLayoutPtr layout = PatternLayoutPtr(new PatternLayout(LOG4CXX_STR("%m\n"))); RollingFileAppenderPtr rfa = RollingFileAppenderPtr(new RollingFileAppender()); rfa->setName(LOG4CXX_STR("ROLLING")); rfa->setAppend(false); rfa->setLayout(layout); rfa->setFile(LOG4CXX_STR("output/sizeBased-test4.log")); FixedWindowRollingPolicyPtr swrp = FixedWindowRollingPolicyPtr(new FixedWindowRollingPolicy()); SizeBasedTriggeringPolicyPtr sbtp = SizeBasedTriggeringPolicyPtr(new SizeBasedTriggeringPolicy()); swrp->setCreateIntermediateDirectories(false); sbtp->setMaxFileSize(100); swrp->setMinIndex(0); // // test4 directory should not exists. Should cause all rollover attempts to fail. // swrp->setFileNamePattern(LOG4CXX_STR("output/test4/sizeBased-test4.%i")); Pool p; swrp->activateOptions(p); rfa->setRollingPolicy(swrp); rfa->setTriggeringPolicy(sbtp); rfa->activateOptions(p); root->addAppender(rfa); common(logger, 0); LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test4.log").exists(p)); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sizeBased-test4.log"), File("witness/rolling/sbr-test4.log"))); } /** * Checking handling of rename failures due to other access * to the indexed files. */ void test5() { PatternLayoutPtr layout = PatternLayoutPtr(new PatternLayout(LOG4CXX_STR("%m\n"))); RollingFileAppenderPtr rfa = RollingFileAppenderPtr(new RollingFileAppender()); rfa->setName(LOG4CXX_STR("ROLLING")); rfa->setAppend(false); rfa->setLayout(layout); rfa->setFile(LOG4CXX_STR("output/sizeBased-test5.log")); FixedWindowRollingPolicyPtr swrp = FixedWindowRollingPolicyPtr(new FixedWindowRollingPolicy()); SizeBasedTriggeringPolicyPtr sbtp = SizeBasedTriggeringPolicyPtr(new SizeBasedTriggeringPolicy()); swrp->setCreateIntermediateDirectories(false); sbtp->setMaxFileSize(100); swrp->setMinIndex(0); swrp->setFileNamePattern(LOG4CXX_STR("output/sizeBased-test5.%i")); Pool p; swrp->activateOptions(p); rfa->setRollingPolicy(swrp); rfa->setTriggeringPolicy(sbtp); rfa->activateOptions(p); root->addAppender(rfa); // // put stray file about locked file FileOutputStream os1(LOG4CXX_STR("output/sizeBased-test5.1"), false); os1.close(p); FileOutputStream os0(LOG4CXX_STR("output/sizeBased-test5.0"), false); common(logger, 0); os0.close(p); if (File("output/sizeBased-test5.3").exists(p)) { // // looks like platform where open files can be renamed // LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test5.log").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test5.0").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test5.1").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test5.2").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test5.3").exists(p)); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sizeBased-test5.log"), File("witness/rolling/sbr-test2.log"))); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sizeBased-test5.0"), File("witness/rolling/sbr-test2.0"))); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sizeBased-test5.1"), File("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. LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test5.log").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test5.0").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/sizeBased-test5.2").exists(p)); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sizeBased-test5.log"), File("witness/rolling/sbr-test4.log"))); } } /** * Same as testBasic but also with GZ compression. */ void test6() { PatternLayoutPtr layout = PatternLayoutPtr(new PatternLayout(LOG4CXX_STR("%m\n"))); RollingFileAppenderPtr rfa = RollingFileAppenderPtr(new RollingFileAppender()); rfa->setAppend(false); rfa->setLayout(layout); FixedWindowRollingPolicyPtr fwrp = FixedWindowRollingPolicyPtr(new FixedWindowRollingPolicy()); SizeBasedTriggeringPolicyPtr sbtp = SizeBasedTriggeringPolicyPtr(new SizeBasedTriggeringPolicy()); sbtp->setMaxFileSize(100); fwrp->setMinIndex(0); rfa->setFile(LOG4CXX_STR("output/sbr-test6.log")); fwrp->setFileNamePattern(LOG4CXX_STR("output/sbr-test6.%i.zip")); Pool p; fwrp->activateOptions(p); rfa->setRollingPolicy(fwrp); rfa->setTriggeringPolicy(sbtp); rfa->activateOptions(p); root->addAppender(rfa); common(logger, 100); LOGUNIT_ASSERT_EQUAL(true, File("output/sbr-test6.log").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/sbr-test6.0.zip").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/sbr-test6.1.zip").exists(p)); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/sbr-test6.log"), File("witness/rolling/sbr-test3.log"))); } }; LOGUNIT_TEST_SUITE_REGISTRATION(SizeBasedRollingTest); apache-log4cxx-1.3.1/src/test/cpp/rolling/filenamepatterntestcase.cpp0000644000175100001770000001310414721727031025307 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include "../util/compare.h" #include "../logunit.h" #include "../insertwide.h" #include using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::pattern; /** * Tests for FileNamePattern. * * * * */ LOGUNIT_CLASS(FileNamePatternTestCase) { LOGUNIT_TEST_SUITE(FileNamePatternTestCase); LOGUNIT_TEST(testFormatInteger1); LOGUNIT_TEST(testFormatInteger2); LOGUNIT_TEST(testFormatInteger3); LOGUNIT_TEST(testFormatInteger4); LOGUNIT_TEST(testFormatInteger5); LOGUNIT_TEST(testFormatInteger6); LOGUNIT_TEST(testFormatInteger7); LOGUNIT_TEST(testFormatInteger8); LOGUNIT_TEST(testFormatInteger9); LOGUNIT_TEST(testFormatInteger10); LOGUNIT_TEST(testFormatInteger11); LOGUNIT_TEST(testFormatDate1); // // TODO: Problem with timezone offset // LOGUNIT_TEST(testFormatDate2); // LOGUNIT_TEST(testFormatDate3); LOGUNIT_TEST(testFormatDate4); LOGUNIT_TEST(testFormatDate5); LOGUNIT_TEST_SUITE_END(); public: LogString format(const LogString & pattern, const ObjectPtr & obj) { std::vector converters; std::vector fields; PatternMap rules; rules.insert(PatternMap::value_type(LOG4CXX_STR("d"), (PatternConstructor) FileDatePatternConverter::newInstance)); rules.insert(PatternMap::value_type(LOG4CXX_STR("i"), (PatternConstructor) IntegerPatternConverter::newInstance)); PatternParser::parse(pattern, converters, fields, rules); LogString result; Pool pool; std::vector::const_iterator fieldIter = fields.begin(); for (std::vector::const_iterator converterIter = converters.begin(); converterIter != converters.end(); converterIter++, fieldIter++) { LogString::size_type i = result.length(); (*converterIter)->format(obj, result, pool); (*fieldIter)->format(i, result); } return result; } void assertDatePattern(const LogString & pattern, int year, int month, int day, int hour, int min, const LogString & expected) { apr_time_exp_t tm; memset(&tm, 0, sizeof(tm)); apr_time_exp_lt(&tm, 0); // set tm_gmtoff tm.tm_min = min; tm.tm_hour = hour; tm.tm_mday = day; tm.tm_mon = month; tm.tm_year = year - 1900; apr_time_t n; apr_time_exp_gmt_get(&n, &tm); ObjectPtr obj(new Date(n)); LOGUNIT_ASSERT_EQUAL(expected, format(pattern, obj)); } void assertIntegerPattern(const LogString & pattern, int value, const LogString & expected) { ObjectPtr obj(new Integer(value)); LOGUNIT_ASSERT_EQUAL(expected, format(pattern, obj)); } void testFormatInteger1() { assertIntegerPattern(LOG4CXX_STR("t"), 3, LOG4CXX_STR("t")); } void testFormatInteger2() { assertIntegerPattern(LOG4CXX_STR("foo"), 3, LOG4CXX_STR("foo")); } void testFormatInteger3() { assertIntegerPattern(LOG4CXX_STR("foo%"), 3, LOG4CXX_STR("foo%")); } void testFormatInteger4() { assertIntegerPattern(LOG4CXX_STR("%ifoo"), 3, LOG4CXX_STR("3foo")); } void testFormatInteger5() { assertIntegerPattern(LOG4CXX_STR("foo%ixixo"), 3, LOG4CXX_STR("foo3xixo")); } void testFormatInteger6() { assertIntegerPattern(LOG4CXX_STR("foo%i.log"), 3, LOG4CXX_STR("foo3.log")); } void testFormatInteger7() { assertIntegerPattern(LOG4CXX_STR("foo.%i.log"), 3, LOG4CXX_STR("foo.3.log")); } void testFormatInteger8() { assertIntegerPattern(LOG4CXX_STR("%ifoo%"), 3, LOG4CXX_STR("3foo%")); } void testFormatInteger9() { assertIntegerPattern(LOG4CXX_STR("%ifoo%%"), 3, LOG4CXX_STR("3foo%")); } void testFormatInteger10() { assertIntegerPattern(LOG4CXX_STR("%%foo"), 3, LOG4CXX_STR("%foo")); } void testFormatInteger11() { assertIntegerPattern(LOG4CXX_STR("foo%ibar%i"), 3, LOG4CXX_STR("foo3bar3")); } void testFormatDate1() { assertDatePattern(LOG4CXX_STR("foo%d{yyyy.MM.dd}"), 2003, 4, 20, 17, 55, LOG4CXX_STR("foo2003.05.20")); } void testFormatDate2() { assertDatePattern(LOG4CXX_STR("foo%d{yyyy.MM.dd HH:mm}"), 2003, 4, 20, 17, 55, LOG4CXX_STR("foo2003.05.20 17:55")); } void testFormatDate3() { assertDatePattern(LOG4CXX_STR("%d{yyyy.MM.dd HH:mm} foo"), 2003, 4, 20, 17, 55, LOG4CXX_STR("2003.05.20 17:55 foo")); } void testFormatDate4() { assertDatePattern(LOG4CXX_STR("foo%dyyyy.MM.dd}"), 2003, 4, 20, 17, 55, LOG4CXX_STR("foo2003-05-20yyyy.MM.dd}")); } void testFormatDate5() { assertDatePattern(LOG4CXX_STR("foo%d{yyyy.MM.dd"), 2003, 4, 20, 17, 55, LOG4CXX_STR("foo2003-05-20{yyyy.MM.dd")); } }; // // See bug LOGCXX-204 // #if !defined(_MSC_VER) || _MSC_VER > 1200 LOGUNIT_TEST_SUITE_REGISTRATION(FileNamePatternTestCase); #endif apache-log4cxx-1.3.1/src/test/cpp/rolling/timebasedrollingtest.cpp0000644000175100001770000005547014721727031024635 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #include #include #include #include #include "../util/compare.h" #include "../logunit.h" #include #include #include #ifndef INT64_C #define INT64_C(x) x ## LL #endif // We often need one and the same date pattern, but in different contexts, to either easily embed it // into other string literals or as an object. While macros are hard to debug, embedding into string // literals is easier this way, because the compiler can automatically collaps them, and if we have // one macro already, a second for a similar purpose shouldn't hurt as well. #define DATE_PATTERN "yyyy-MM-dd_HH_mm_ss" #define DATE_PATTERN_STR LogString(LOG4CXX_STR("yyyy-MM-dd_HH_mm_ss")) #define PATTERN_LAYOUT LOG4CXX_STR("%c{1} - %m%n") #define DIR_PRE_OUTPUT "output/rolling/tbr-" #define DIR_PRE_WITNESS "witness/rolling/tbr-" using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::rolling; /** * 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
 * 
*/ LOGUNIT_CLASS(TimeBasedRollingTest) { LOGUNIT_TEST_SUITE(TimeBasedRollingTest); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST(test3); LOGUNIT_TEST(test4); LOGUNIT_TEST(test5); LOGUNIT_TEST(test6); LOGUNIT_TEST(test7); LOGUNIT_TEST(rollIntoDir); LOGUNIT_TEST_SUITE_END(); private: LoggerPtr logger; log4cxx_time_t current_time; /** * Build file names with timestamps. *

* This method builds some file names based on a hard coded date pattern, while the important * thing is that the used time is "now" for the first and one additional second into the future * for each subsequent file name. The method is used to build names which are expected to get * created by loggers afterwards, so the existence of those files can be checked easily. *

*

* The given {@code prefix} is for the file name only, we hard code "output" as directory. *

*

* Using {@code startInFuture} the caller can specify if the first created file name uses "now" * or already starts one second in the future. This depends on what the caller wants to check: * If it is the existence of specially named files and the caller uses some generic log file to * start with, it's most likely that the first file name to checks needs to be in the future, * because new files are only created with subsequent log statements. The first goes to the * generically named file, afterwards the test sleeps a bit and the next statement is creating * the first file to check for. During the time between those two calls the current second and * therefore "now" could have easily past and the first file name will never be found, because * the rolling appender creates it with a newer "now", at least one second in the future. *

* @param[in,out] pool * @param[in] prefix * @param[in] fnames * @param[in,opt] compressed * @param[in,opt] startInFuture */ template void buildTsFnames( Pool& pool, const LogString& prefix, LogString (&fnames)[N], bool compressed = false, bool startInFuture = false) { SimpleDateFormat sdf(DATE_PATTERN_STR); log4cxx_time_t now(current_time); LogString ext(compressed ? LOG4CXX_STR(".gz") : LOG4CXX_STR("")); now += startInFuture ? APR_USEC_PER_SEC : 0; for (size_t i = 0; i < N; ++i) { fnames[i].assign(LogString(LOG4CXX_STR("" DIR_PRE_OUTPUT)) + prefix); sdf.format(fnames[i], now, pool); fnames[i].append(ext); now += APR_USEC_PER_SEC; } } /** * Log some msg and sleep. *

* Most tests need to log some message to some files and sleep afterwards, to spread the msgs * over time and timestamp based named files. This method handles this for all tests to not need * to replicate the same code AND deals with the fact that the logigng statements should contain * the original src function and line. For that to work each caller needs to provide us the * additional information and we redefine LOG4CXX_LOCATION to use that provided data instead of * that from the compiler when a log statement is issued. While this is a bit ugly, because we * need to duplicate the definition of LOG4CXX_LOCATION, it is easier than to duplicate the code * for logging and sleeping per test in this file. *

*

* The given wait factor is always multiplied with 1 second and the result is waited for, so a * caller needs to e.g. provide {@code 0.5} if it needs log statements to distribute over given * files, resulting in two statements per file. If the caller needs indivdual file to check for * their existence, {@code 1} can be provided, which ensures that we wait for at least the next * second. *

*

* It is important the the caller provides aus with {@code __LOG4CXX_FUNC__} instead of only * {@code __FUNC__} or such, because the latter is compiler specific and log4cxx already deals * with such things. *

*

* We had macro wrappers around this method dealing with such things in the past, but as args * where added, those become more and more difficult to maintain properly and therefore removed. *

* @param[in,out] pool * @param[in] howOften * @param[in] srcFunc * @param[in] srcLine * @param[in,opt] startWith * @param[in] waitFactor */ void logMsgAndSleep( Pool& pool, size_t howOften, std::string srcFunc, size_t srcLine, size_t startWith = 0, float waitFactor = 0.5) { #undef LOG4CXX_LOCATION #define LOG4CXX_LOCATION ::log4cxx::spi::LocationInfo( \ __FILE__, \ __FILE__, \ srcFunc.c_str(), \ srcLine) for (size_t i = startWith; i < startWith + howOften; ++i) { std::string message("Hello---"); message.append(pool.itoa(i)); LOG4CXX_DEBUG(logger, message); current_time += (APR_USEC_PER_SEC * waitFactor); } #undef LOG4CXX_LOCATION #define LOG4CXX_LOCATION ::log4cxx::spi::LocationInfo( \ __FILE__, \ __FILE__, \ __LOG4CXX_FUNC__, \ __LINE__) } /** * Check witness by comparing file contents. *

* This method checks the witness for some test by comparing the contents of the given file used * by that test. To find the corresponding witness, the prefix of the test needs to be provided, * which is some unique part of the file name to use, while we hard code the parent dir and * other non changing parts of the name. *

*

* We don't use a wrapper macro this time because the src line should have the same name in all * compilers and is easily to add for the caller. *

* @param[in,out] pool * @param[in] prefix * @param[in] fname * @param[in] witnessIdx * @param[in] srcLine */ void compareWitness( Pool& pool, const LogString& prefix, const LogString& fname, size_t witnessIdx, size_t srcLine) { LogString witness(LOG4CXX_STR("" DIR_PRE_WITNESS)); witness.append(prefix); StringHelper::toString(witnessIdx, pool, witness); //std::wcerr << L"Comparing file: " << fname << L"\n"; //std::wcerr << L"Comparing witness: " << witness << L"\n"; LOGUNIT_ASSERT_SRCL(Compare::compare(fname, File(witness)), srcLine); } /** * Check witnesses by comparing file contents. *

* This method is a wrapper around {@link compareWitness}, used to iterate over all files from a * given test. *

* @param[in,out] pool * @param[in] prefix * @param[in] fnames * @param[in] srcLine */ template void compareWitnesses( Pool& pool, const LogString& prefix, LogString (&fnames)[N], size_t srcLine) { for (int i = 0; i < N; ++i) { this->compareWitness(pool, prefix, fnames[i], i, srcLine); } } /** * Check existing files. *

* This method checks that the first N - 1 files of the given array actually exist and compares * the last one by content to some witness. *

*

* We don't use a wrapper macro this time because the src line should have the same name in all * compilers and is easily to add for the caller. *

* @param[in,out] pool * @param[in] prefix * @param[in] fnames * @param[in] witnessIdx * @param[in] srcLine */ template void checkFilesExist( Pool& pool, const LogString& prefix, LogString (&fnames)[N], size_t witnessIdx, size_t srcLine) { for (int i = 0; i < N - 1; ++i) { //std::wcerr << L"Check: " << fnames[i] << L"\n"; LOGUNIT_ASSERT_EQUAL_SRCL(true, File(fnames[i]).exists(pool), srcLine); } this->compareWitness(pool, prefix, fnames[witnessIdx], witnessIdx, srcLine); } /** * Let the current second pass. *

* This method assures that the current second and some additional time gets passed before * returning. *

* @param[in,opt] millis */ void delayUntilNextSecond() { current_time += APR_USEC_PER_SEC; } /** * Let the current second pass with some msg. *

* This method works exactly like {@link delayUntilNextSecond(size_t)}, but additionally prints * a message before and after the wait on STDOUT for debugging purposes. *

* @param[in,opt] millis */ void delayUntilNextSecondWithMsg() { std::cout << "Advancing one second\n"; delayUntilNextSecond(); } /** * Delete generic log file. *

* Some tests use generic log file names which may already be available during subsequent calls * to the test and influence their behavior, e.g. because RollingFileAppender uses the last * modification time of already existing files to create its internal name. Such a date might be * from the arbitrary past, but most of the tests assume operations like rollovers within a few * seconds around "new". Those assumptions will fail for older existing files. This method can * be used to delete those files, while documenting the problem at the same time. *

* @param[in,out] pool * @param[in] path */ void delGenericLogFile( Pool& pool, LogString path) { File(path).deleteFile(pool); } /** * Set the current time for each individual test methhod run. *

* There's at least one test running multiple other tests WITHIN the same lifecycle of * {@code setUp} and {@code tearDown}, but each of the test methods need the same current time * to start with. So this method can be used to set that and is simply used by {@code setUp} * as well. *

*/ void setUpCurrTime() { //current_time = log4cxx::helpers::Date::currentTime(); // Start at "about" now. //current_time -= (current_time % APR_USEC_PER_SEC); // Go to the top of the second //current_time++; // Need to not be at the top of a second for rollover logic to work correctly current_time = 1; // Start at about unix epoch } public: log4cxx_time_t currentTime() { return current_time; } void setUp() { BasicConfigurator::configure(std::make_shared ( LOG4CXX_STR("%d{ABSOLUTE} [%t] %level %c{2}#%M:%L - %m%n") )); this->logger = LogManager::getLogger("org.apache.log4j.TimeBasedRollingTest"); this->setUpCurrTime(); helpers::Date::setGetCurrentTimeFunction( std::bind( &TimeBasedRollingTest::currentTime, this ) ); } void tearDown() { LogManager::shutdown(); } /** * Test rolling without compression, activeFileName left blank, no stop/start. */ void test1() { Pool pool; const size_t nrOfFnames(4); LogString fnames[nrOfFnames]; PatternLayoutPtr layout( new PatternLayout(PATTERN_LAYOUT)); RollingFileAppenderPtr rfa( new RollingFileAppender()); rfa->setAppend(false); rfa->setLayout(layout); TimeBasedRollingPolicyPtr tbrp(new TimeBasedRollingPolicy()); tbrp->setFileNamePattern(LOG4CXX_STR("" DIR_PRE_OUTPUT "test1-%d{" DATE_PATTERN "}")); tbrp->activateOptions(pool); rfa->setRollingPolicy(tbrp); rfa->activateOptions(pool); logger->addAppender(rfa); this->buildTsFnames<4>(pool, LOG4CXX_STR("test1-"), fnames); this->delayUntilNextSecondWithMsg(); this->logMsgAndSleep( pool, nrOfFnames + 1, __LOG4CXX_FUNC__, __LINE__); this->compareWitnesses<4>( pool, LOG4CXX_STR("test1."), fnames, __LINE__); } /** * No compression, with stop/restart, activeFileName left blank. */ void test2() { Pool pool; const size_t nrOfFnames(4); LogString fnames[nrOfFnames]; PatternLayoutPtr layout1(new PatternLayout(PATTERN_LAYOUT)); RollingFileAppenderPtr rfa1( new RollingFileAppender()); rfa1->setAppend(false); rfa1->setLayout(layout1); TimeBasedRollingPolicyPtr tbrp1(new TimeBasedRollingPolicy()); tbrp1->setFileNamePattern(LOG4CXX_STR("" DIR_PRE_OUTPUT "test2-%d{" DATE_PATTERN "}")); tbrp1->activateOptions(pool); rfa1->setRollingPolicy(tbrp1); rfa1->activateOptions(pool); logger->addAppender(rfa1); this->buildTsFnames<4>(pool, LOG4CXX_STR("test2-"), fnames); this->delayUntilNextSecondWithMsg(); this->logMsgAndSleep(pool, 3, __LOG4CXX_FUNC__, __LINE__); logger->removeAppender(rfa1); rfa1->close(); PatternLayoutPtr layout2(new PatternLayout(PATTERN_LAYOUT)); RollingFileAppenderPtr rfa2( new RollingFileAppender()); rfa2->setLayout(layout2); TimeBasedRollingPolicyPtr tbrp2 = TimeBasedRollingPolicyPtr(new TimeBasedRollingPolicy()); tbrp2->setFileNamePattern(LOG4CXX_STR("" DIR_PRE_OUTPUT "test2-%d{" DATE_PATTERN "}")); tbrp2->activateOptions(pool); rfa2->setRollingPolicy(tbrp2); rfa2->activateOptions(pool); rfa2->setAppend(false); logger->addAppender(rfa2); this->logMsgAndSleep( pool, 2, __LOG4CXX_FUNC__, __LINE__, 3); this->compareWitnesses<4>( pool, LOG4CXX_STR("test2."), fnames, __LINE__); } /** * With compression, activeFileName left blank, no stop/restart. */ void test3() { Pool pool; const size_t nrOfFnames(4); LogString fnames[nrOfFnames]; PatternLayoutPtr layout( new PatternLayout(PATTERN_LAYOUT)); RollingFileAppenderPtr rfa( new RollingFileAppender()); rfa->setAppend(false); rfa->setLayout(layout); TimeBasedRollingPolicyPtr tbrp = TimeBasedRollingPolicyPtr(new TimeBasedRollingPolicy()); tbrp->setFileNamePattern(LogString(LOG4CXX_STR("" DIR_PRE_OUTPUT "test3-%d{" DATE_PATTERN "}.gz"))); tbrp->activateOptions(pool); rfa->setRollingPolicy(tbrp); rfa->activateOptions(pool); logger->addAppender(rfa); this->buildTsFnames<4>(pool, LOG4CXX_STR("test3-"), fnames, true); fnames[nrOfFnames - 1].resize(fnames[nrOfFnames - 1].size() - 3); this->delayUntilNextSecondWithMsg(); this->logMsgAndSleep( pool, nrOfFnames + 1, __LOG4CXX_FUNC__, __LINE__); this->checkFilesExist<4>( pool, LOG4CXX_STR("test3."), fnames, nrOfFnames - 1, __LINE__); } /** * Without compression, activeFileName set, with stop/restart * * Note: because this test stops and restarts, it is not possible to use the * date pattern in the filenames, as log4cxx will use the file's last modified * time when rolling over and determining the new filename. */ void test4() { Pool pool; const size_t nrOfFnames(4); const size_t nrOfLogMsgs(((nrOfFnames - 1) * 2) - 1); LogString fnames[nrOfFnames]; PatternLayoutPtr layout1(new PatternLayout(PATTERN_LAYOUT)); RollingFileAppenderPtr rfa1( new RollingFileAppender()); rfa1->setLayout(layout1); TimeBasedRollingPolicyPtr tbrp1 = TimeBasedRollingPolicyPtr(new TimeBasedRollingPolicy()); tbrp1->setFileNamePattern(LOG4CXX_STR("" DIR_PRE_OUTPUT "test4-%d{" DATE_PATTERN "}")); tbrp1->activateOptions(pool); rfa1->setFile(LOG4CXX_STR("" DIR_PRE_OUTPUT "test4.log")); rfa1->setRollingPolicy(tbrp1); rfa1->activateOptions(pool); logger->addAppender(rfa1); this->delGenericLogFile(pool, rfa1->getFile()); this->buildTsFnames<4>(pool, LOG4CXX_STR("test4-"), fnames); fnames[0].assign(rfa1->getFile()); this->delayUntilNextSecondWithMsg(); this->logMsgAndSleep(pool, nrOfLogMsgs, __LOG4CXX_FUNC__, __LINE__); logger->removeAppender(rfa1); rfa1->close(); PatternLayoutPtr layout2(new PatternLayout(PATTERN_LAYOUT)); RollingFileAppenderPtr rfa2( new RollingFileAppender()); rfa2->setLayout(layout2); TimeBasedRollingPolicyPtr tbrp2 = TimeBasedRollingPolicyPtr(new TimeBasedRollingPolicy()); tbrp2->setFileNamePattern(LOG4CXX_STR("" DIR_PRE_OUTPUT "test4-%d{" DATE_PATTERN "}")); tbrp2->activateOptions(pool); rfa2->setFile(rfa1->getFile()); rfa2->setRollingPolicy(tbrp2); rfa2->activateOptions(pool); logger->addAppender(rfa2); // The one file not checked is the active file from the old appender reused by the new one // and rolled over afterwards. The problem is that because the reused file exists already, // it doesn't get an expected fname, but the last write time instead. Though, should be safe // enough to not check that special file. this->logMsgAndSleep(pool, 2, __LOG4CXX_FUNC__, __LINE__, nrOfLogMsgs); this->compareWitness(pool, LOG4CXX_STR("test4."), fnames[0], 0, __LINE__); this->compareWitness(pool, LOG4CXX_STR("test4."), fnames[1], 1, __LINE__); this->compareWitness(pool, LOG4CXX_STR("test4."), fnames[2], 2, __LINE__); } /** * No compression, activeFileName set, without stop/restart. */ void test5() { Pool pool; const size_t nrOfFnames(4); const size_t nrOfLogMsgs((nrOfFnames * 2) - 1); LogString fnames[nrOfFnames]; PatternLayoutPtr layout( new PatternLayout(PATTERN_LAYOUT)); RollingFileAppenderPtr rfa( new RollingFileAppender()); rfa->setLayout(layout); TimeBasedRollingPolicyPtr tbrp = TimeBasedRollingPolicyPtr(new TimeBasedRollingPolicy()); tbrp->setFileNamePattern(LOG4CXX_STR("" DIR_PRE_OUTPUT "test5-%d{" DATE_PATTERN "}")); rfa->setFile(LOG4CXX_STR("" DIR_PRE_OUTPUT "test5.log")); tbrp->activateOptions(pool); rfa->setRollingPolicy(tbrp); rfa->activateOptions(pool); logger->addAppender(rfa); this->delGenericLogFile(pool, rfa->getFile()); this->buildTsFnames<4>(pool, LOG4CXX_STR("test5-"), fnames); fnames[0].assign(rfa->getFile()); this->delayUntilNextSecondWithMsg(); this->logMsgAndSleep( pool, nrOfLogMsgs, __LOG4CXX_FUNC__, __LINE__); this->compareWitnesses<4>( pool, LOG4CXX_STR("test5."), fnames, __LINE__); } /** * With compression, activeFileName set, no stop/restart. */ void test6() { Pool pool; const size_t nrOfFnames(4); const size_t nrOfLogMsgs((nrOfFnames * 2) - 1); LogString fnames[nrOfFnames]; PatternLayoutPtr layout( new PatternLayout(PATTERN_LAYOUT)); RollingFileAppenderPtr rfa( new RollingFileAppender()); rfa->setAppend(false); rfa->setLayout(layout); TimeBasedRollingPolicyPtr tbrp = TimeBasedRollingPolicyPtr(new TimeBasedRollingPolicy()); tbrp->setFileNamePattern(LogString(LOG4CXX_STR("" DIR_PRE_OUTPUT "test6-%d{" DATE_PATTERN "}.gz"))); rfa->setFile(LOG4CXX_STR("" DIR_PRE_OUTPUT "test6.log")); tbrp->activateOptions(pool); rfa->setRollingPolicy(tbrp); rfa->activateOptions(pool); logger->addAppender(rfa); this->delGenericLogFile(pool, rfa->getFile()); this->buildTsFnames<4>(pool, LOG4CXX_STR("test6-"), fnames, true); fnames[0].assign(rfa->getFile()); this->delayUntilNextSecondWithMsg(); this->logMsgAndSleep( pool, nrOfLogMsgs, __LOG4CXX_FUNC__, __LINE__); this->checkFilesExist( pool, LOG4CXX_STR("test6."), fnames, 0, __LINE__); } /** * Repeat some tests with generic file names. *

* This test calls some tests which use generic file names and will only work properly if those * got deleted before running the test during setup. *

*/ void test7() { typedef void (TimeBasedRollingTest::*Test)(); typedef std::vector Tests; Tests tests(10); size_t numTest = 0; tests.at(4) = &TimeBasedRollingTest::test4; tests.at(5) = &TimeBasedRollingTest::test5; tests.at(6) = &TimeBasedRollingTest::test6; for (size_t numTest = 1; numTest < tests.size(); ++numTest) { Test test(tests.at(numTest)); if (!test) { continue; } this->setUpCurrTime(); (this->*test)(); } } void rollIntoDir() { Pool pool; const size_t nrOfFnames(4); const size_t nrOfLogMsgs((nrOfFnames * 2) - 1); LogString fnames[nrOfFnames]; PatternLayoutPtr layout( new PatternLayout(PATTERN_LAYOUT)); RollingFileAppenderPtr rfa( new RollingFileAppender()); rfa->setLayout(layout); rfa->setFile(LOG4CXX_STR("" DIR_PRE_OUTPUT "rollIntoDir.log")); std::random_device dev; std::mt19937 rng(dev()); std::uniform_int_distribution dist(1,100000); LogString filenamePattern = LOG4CXX_STR("" DIR_PRE_OUTPUT); LogString dirNumber; StringHelper::toString(dist(rng), dirNumber); LogString directoryName = LOG4CXX_STR("tbr-rollIntoDir-"); directoryName.append( dirNumber ); filenamePattern.append( directoryName ); LogString filenamePatternPrefix = filenamePattern; filenamePattern.append( LOG4CXX_STR("/file-%d{" DATE_PATTERN "}") ); TimeBasedRollingPolicyPtr tbrp(new TimeBasedRollingPolicy()); tbrp->setFileNamePattern(filenamePattern); tbrp->activateOptions(pool); rfa->setRollingPolicy(tbrp); rfa->activateOptions(pool); logger->addAppender(rfa); const logchar* prefix = directoryName.append(LOG4CXX_STR("/file-")).data(); this->delGenericLogFile(pool, rfa->getFile()); this->buildTsFnames<4>(pool, prefix, fnames); fnames[0].assign(rfa->getFile()); this->delayUntilNextSecondWithMsg(); this->logMsgAndSleep( pool, nrOfLogMsgs, __LOG4CXX_FUNC__, __LINE__); this->checkFilesExist( pool, LOG4CXX_STR("test6."), fnames, 0, __LINE__); } }; LOGUNIT_TEST_SUITE_REGISTRATION(TimeBasedRollingTest); apache-log4cxx-1.3.1/src/test/cpp/rolling/rollingfileappenderpropertiestest.cpp0000644000175100001770000001670214721727031027446 0ustar runnerdocker/* * 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. */ #include "../util/compare.h" #include "../insertwide.h" #include "../logunit.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace log4cxx; using namespace log4cxx::filter; using namespace log4cxx::helpers; using namespace log4cxx::rolling; /** * */ LOGUNIT_CLASS(RollingFileAppenderPropertiesTest) { LOGUNIT_TEST_SUITE(RollingFileAppenderPropertiesTest); LOGUNIT_TEST(testIsOptionHandler); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST(test3); LOGUNIT_TEST(test4); LOGUNIT_TEST(testRollingFromProperties); LOGUNIT_TEST_SUITE_END(); public: void setUp() { } void tearDown() { LogManager::shutdown(); } /** * Test basic rolling functionality. */ void test1() { PropertyConfigurator::configure(File("input/rolling/obsoleteRFA1.properties")); // Make sure that the configured values are what we expect auto appender = LogManager::getRootLogger()->getAppender(LOG4CXX_STR("testAppender")); LOGUNIT_ASSERT(appender); auto rfa = cast(appender); LOGUNIT_ASSERT(rfa); LOGUNIT_ASSERT_EQUAL(3, rfa->getMaxBackupIndex()); LOGUNIT_ASSERT_EQUAL(100, static_cast(rfa->getMaximumFileSize())); logchar msg[] = { 'H', 'e', 'l', 'l', 'o', '-', '-', '-', '?', 0}; auto logger = Logger::getLogger("RollingFileAppenderTest"); // Write exactly 10 bytes with each log for (int i = 0; i < 25; i++) { apr_sleep(100000); if (i < 10) { msg[8] = (logchar) ('0' + i); LOG4CXX_DEBUG(logger, msg); } else if (i < 100) { msg[7] = (logchar) ('0' + i / 10); msg[8] = (logchar) ('0' + i % 10); LOG4CXX_DEBUG(logger, msg); } } Pool p; LOGUNIT_ASSERT_EQUAL(true, File("output/obsoleteRFA-test1.log").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/obsoleteRFA-test1.log.1").exists(p)); } /** * Test basic rolling functionality. */ void test2() { auto layout = std::make_shared (LOG4CXX_STR("%m\n")); auto rfa = std::make_shared(); rfa->setName(LOG4CXX_STR("ROLLING")); rfa->setLayout(layout); rfa->setOption(LOG4CXX_STR("append"), LOG4CXX_STR("false")); rfa->setMaximumFileSize(100); rfa->setFile(LOG4CXX_STR("output/obsoleteRFA-test2.log")); Pool p; rfa->activateOptions(p); auto root = Logger::getRootLogger(); root->addAppender(rfa); logchar msg[] = { 'H', 'e', 'l', 'l', 'o', '-', '-', '-', '?', 0}; auto logger = Logger::getLogger("org.apache.logj4.ObsoleteRollingFileAppenderTest"); // Write exactly 10 bytes with each log for (int i = 0; i < 25; i++) { apr_sleep(100000); if (i < 10) { msg[8] = (logchar) ('0' + i); LOG4CXX_DEBUG(logger, msg); } else if (i < 100) { msg[7] = (logchar) ('0' + i / 10); msg[8] = (logchar) ('0' + i % 10); LOG4CXX_DEBUG(logger, msg); } } LOGUNIT_ASSERT_EQUAL(true, File("output/obsoleteRFA-test2.log").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/obsoleteRFA-test2.log.1").exists(p)); } /** * Test propertyfile configured time based rolling functionality. */ void test3() { PropertyConfigurator::configure(File("input/rolling/obsoleteDRFA1.properties")); int preCount = getFileCount("output", LOG4CXX_STR("obsoleteDRFA-test1.log.")); LoggerPtr logger(Logger::getLogger("DailyRollingFileAppenderTest")); char msg[11]; strncpy(msg, "Hello---??", sizeof(msg)); for (int i = 0; i < 25; i++) { apr_sleep(100000); msg[8] = (char) ('0' + (i / 10)); msg[9] = (char) ('0' + (i % 10)); LOG4CXX_DEBUG(logger, msg); } int postCount = getFileCount("output", LOG4CXX_STR("obsoleteDRFA-test1.log.")); LOGUNIT_ASSERT_EQUAL(true, postCount > preCount); } /** * Test programatically configured time based rolling functionality. */ void test4() { PatternLayoutPtr layout(new PatternLayout(LOG4CXX_STR("%m%n"))); auto rfa = std::make_shared(); rfa->setName(LOG4CXX_STR("ROLLING")); rfa->setLayout(layout); rfa->setAppend(false); rfa->setFile(LOG4CXX_STR("output/obsoleteDRFA-test2.log")); rfa->setDatePattern(LOG4CXX_STR("'.'yyyy-MM-dd-HH_mm_ss")); Pool p; rfa->activateOptions(p); LoggerPtr root(Logger::getRootLogger()); root->addAppender(rfa); LoggerPtr logger(Logger::getLogger("ObsoleteDailyRollingAppenderTest")); int preCount = getFileCount("output", LOG4CXX_STR("obsoleteDRFA-test2.log.")); char msg[11]; strncpy(msg, "Hello---??", sizeof(msg)); for (int i = 0; i < 25; i++) { apr_sleep(100000); msg[8] = (char) ('0' + i / 10); msg[9] = (char) ('0' + i % 10); LOG4CXX_DEBUG(logger, msg); } int postCount = getFileCount("output", LOG4CXX_STR("obsoleteDRFA-test2.log.")); LOGUNIT_ASSERT_EQUAL(true, postCount > preCount); } /** * Tests if class is declared to support the OptionHandler interface. * See LOGCXX-136. */ void testIsOptionHandler() { auto rfa = std::make_shared(); LOGUNIT_ASSERT_EQUAL(true, rfa->instanceof(log4cxx::spi::OptionHandler::getStaticClass())); } void testRollingFromProperties(){ // Load the properties from the file and make sure that the configured values are // what we expect PropertyConfigurator::configure(LOG4CXX_FILE("input/rolling/rollingFileAppenderFromProperties.properties")); auto appender = LogManager::getRootLogger()->getAppender(LOG4CXX_STR("FILE")); LOGUNIT_ASSERT(appender); auto rfa = cast(appender); LOGUNIT_ASSERT(rfa); FixedWindowRollingPolicyPtr fixedWindowRolling = cast(rfa->getRollingPolicy()); LOGUNIT_ASSERT(fixedWindowRolling); auto sizeBasedPolicy = cast(rfa->getTriggeringPolicy()); LOGUNIT_ASSERT(sizeBasedPolicy); LOGUNIT_ASSERT_EQUAL(3, fixedWindowRolling->getMaxIndex()); LOGUNIT_ASSERT_EQUAL(100, static_cast(sizeBasedPolicy->getMaxFileSize())); } private: static int getFileCount(const char* dir, const LogString & initial) { Pool p; std::vector files(File(dir).list(p)); int count = 0; for (size_t i = 0; i < files.size(); i++) { if (StringHelper::startsWith(files[i], initial)) { count++; } } return count; } }; LOGUNIT_TEST_SUITE_REGISTRATION(RollingFileAppenderPropertiesTest); apache-log4cxx-1.3.1/src/test/cpp/rolling/filterbasedrollingtest.cpp0000644000175100001770000001052314721727031025152 0ustar runnerdocker/* * 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. */ #include "../util/compare.h" #include "../logunit.h" #include "../insertwide.h" #include #include #include #include #include #include #include #include #include using namespace log4cxx; using namespace log4cxx::rolling; using namespace log4cxx::filter; using namespace log4cxx::helpers; /** * * Tests of rolling file appender with a filter based triggering policy. * * * * */ LOGUNIT_CLASS(FilterBasedRollingTest) { LOGUNIT_TEST_SUITE(FilterBasedRollingTest); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST_SUITE_END(); public: void tearDown() { LogManager::getLoggerRepository()->resetConfiguration(); } /** * Test basic rolling functionality using configuration file. */ void test1() { #if LOG4CXX_HAS_DOMCONFIGURATOR log4cxx::xml::DOMConfigurator::configure( "./input/rolling/filter1.xml" /*, LogManager::getLoggerRepository() */); common(LOG4CXX_STR("output/filterBased-test1")); #endif } /** * Test basic rolling functionality using explicit configuration. * @remarks Test fails when run immediately after test1. */ void test2() { LayoutPtr layout(new PatternLayout(LOG4CXX_STR("%m\n"))); RollingFileAppenderPtr rfa(new RollingFileAppender()); rfa->setName(LOG4CXX_STR("ROLLING")); rfa->setLayout(layout); FixedWindowRollingPolicyPtr swrp(new FixedWindowRollingPolicy()); FilterBasedTriggeringPolicyPtr fbtp(new FilterBasedTriggeringPolicy()); LevelRangeFilterPtr rf(new LevelRangeFilter()); rf->setLevelMin(Level::getInfo()); fbtp->addFilter(rf); Pool p; fbtp->activateOptions(p); swrp->setMinIndex(0); rfa->setFile(LOG4CXX_STR("output/filterBased-test2.log")); rfa->setAppend(false); swrp->setFileNamePattern(LOG4CXX_STR("output/filterBased-test2.%i")); swrp->activateOptions(p); rfa->setRollingPolicy(swrp); rfa->setTriggeringPolicy(fbtp); rfa->activateOptions(p); Logger::getRootLogger()->addAppender(rfa); Logger::getRootLogger()->setLevel(Level::getDebug()); common(LOG4CXX_STR("output/filterBased-test2")); } private: /** * Common aspects of test1 and test2 */ void common(const LogString & baseName) { LoggerPtr logger(Logger::getLogger("org.apache.log4j.rolling.FilterBasedRollingTest")); // Write exactly 10 bytes with each log for (int i = 0; i < 25; i++) { char msg[10]; #if defined(__STDC_LIB_EXT1__) || defined(__STDC_SECURE_LIB__) strcpy_s(msg, sizeof msg, "Hello---?"); #else strcpy(msg, "Hello---?"); #endif if (i < 10) { msg[8] = (char) ('0' + i); LOG4CXX_DEBUG(logger, msg); } else if (i < 100) { msg[7] = (char) ('0' + (i / 10)); msg[8] = (char) ('0' + (i % 10)); if ((i % 10) == 0) { LOG4CXX_WARN(logger, msg); } else { LOG4CXX_DEBUG(logger, msg); } } } // // test was constructed to mimic SizeBasedRollingTest.test2 // LOGUNIT_ASSERT_EQUAL(true, Compare::compare(baseName + LOG4CXX_STR(".log"), LogString(LOG4CXX_STR("witness/rolling/sbr-test2.log")))); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(baseName + LOG4CXX_STR(".0"), LogString(LOG4CXX_STR("witness/rolling/sbr-test2.0")))); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(baseName + LOG4CXX_STR(".1"), LogString(LOG4CXX_STR("witness/rolling/sbr-test2.1")))); } }; LOGUNIT_TEST_SUITE_REGISTRATION(FilterBasedRollingTest); apache-log4cxx-1.3.1/src/test/cpp/rolling/CMakeLists.txt0000644000175100001770000000224214721727031022432 0ustar runnerdocker# # 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. # # Tests defined in this directory set(ROLLING_TESTS filenamepatterntestcase filterbasedrollingtest manualrollingtest sizebasedrollingtest timebasedrollingtest rollingfileappenderpropertiestest ) foreach(fileName IN LISTS ROLLING_TESTS) add_executable(${fileName} "${fileName}.cpp") endforeach() set(ALL_LOG4CXX_TESTS ${ALL_LOG4CXX_TESTS} ${ROLLING_TESTS} PARENT_SCOPE) apache-log4cxx-1.3.1/src/test/cpp/rolling/manualrollingtest.cpp0000644000175100001770000002606214721727031024150 0ustar runnerdocker/* * 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. */ #include "../util/compare.h" #include "../insertwide.h" #include "../logunit.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace log4cxx; using namespace log4cxx::filter; using namespace log4cxx::helpers; using namespace log4cxx::rolling; /** * Tests of explicit manual rolling of RollingFileAppenders. * * * */ LOGUNIT_CLASS(ManualRollingTest) { LOGUNIT_TEST_SUITE(ManualRollingTest); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); // TODO: Compression not yet implemented // LOGUNIT_TEST(test3); LOGUNIT_TEST(test4); LOGUNIT_TEST(test5); LOGUNIT_TEST(create_directories); LOGUNIT_TEST_SUITE_END(); LoggerPtr root; LoggerPtr logger; public: void setUp() { logger = Logger::getLogger("org.apache.log4j.rolling.ManualRollingTest"); root = Logger::getRootLogger(); } void tearDown() { LogManager::shutdown(); } void common(RollingFileAppenderPtr & rfa, Pool & pool, LoggerPtr & logger1) { char msg[] = { 'H', 'e', 'l', 'l', 'o', '-', '-', '-', 'N', 0 }; // Write exactly 10 bytes with each log for (int i = 0; i < 25; i++) { if (i < 10) { msg[8] = '0' + i; } else if (i < 100) { int digit = i % 10; if (digit == 0) { rfa->rollover(pool); } msg[7] = '0' + i / 10; msg[8] = '0' + digit; } LOG4CXX_DEBUG(logger1, msg); } } /** * Tests that the lack of an explicit active file will use the * low index as the active file. * */ void test1() { PatternLayoutPtr layout = PatternLayoutPtr(new PatternLayout(LOG4CXX_STR("%m\n"))); RollingFileAppenderPtr rfa = RollingFileAppenderPtr(new RollingFileAppender()); rfa->setName(LOG4CXX_STR("ROLLING")); rfa->setAppend(false); rfa->setLayout(layout); FixedWindowRollingPolicyPtr swrp = FixedWindowRollingPolicyPtr(new FixedWindowRollingPolicy()); swrp->setMinIndex(0); swrp->setFileNamePattern(LOG4CXX_STR("output/manual-test1.%i")); Pool p; swrp->activateOptions(p); rfa->setRollingPolicy(swrp); rfa->activateOptions(p); root->addAppender(rfa); common(rfa, p, logger); LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test1.0").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test1.1").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test1.2").exists(p)); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test1.0"), File("witness/rolling/sbr-test2.log"))); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test1.1"), File("witness/rolling/sbr-test2.0"))); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test1.2"), File("witness/rolling/sbr-test2.1"))); } /** * Test basic rolling functionality with explicit setting of FileAppender.file. */ void test2() { PatternLayoutPtr layout = PatternLayoutPtr(new PatternLayout(LOG4CXX_STR("%m\n"))); RollingFileAppenderPtr rfa = RollingFileAppenderPtr(new RollingFileAppender()); rfa->setName(LOG4CXX_STR("ROLLING")); rfa->setAppend(false); rfa->setLayout(layout); rfa->setFile(LOG4CXX_STR("output/manual-test2.log")); Pool p; rfa->activateOptions(p); root->addAppender(rfa); common(rfa, p, logger); LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test2.log").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test2.log.1").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test2.log.2").exists(p)); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test2.log"), File("witness/rolling/sbr-test2.log"))); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test2.log.1"), File("witness/rolling/sbr-test2.0"))); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test2.log.2"), File("witness/rolling/sbr-test2.1"))); } /** * Same as testBasic but also with GZ compression. */ void test3() { PatternLayoutPtr layout = PatternLayoutPtr(new PatternLayout(LOG4CXX_STR("%m\n"))); RollingFileAppenderPtr rfa = RollingFileAppenderPtr(new RollingFileAppender()); rfa->setAppend(false); rfa->setLayout(layout); FixedWindowRollingPolicyPtr fwrp = FixedWindowRollingPolicyPtr(new FixedWindowRollingPolicy()); fwrp->setMinIndex(0); rfa->setFile(LOG4CXX_STR("output/manual-test3.log")); fwrp->setFileNamePattern(LOG4CXX_STR("output/sbr-test3.%i.gz")); Pool p; fwrp->activateOptions(p); rfa->setRollingPolicy(fwrp); rfa->activateOptions(p); root->addAppender(rfa); common(rfa, p, logger); LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test3.log").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test3.0.gz").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test3.1.gz").exists(p)); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test3.log"), File("witness/rolling/sbr-test3.log"))); LOGUNIT_ASSERT_EQUAL(File("witness/rolling/sbr-test3.0.gz").length(p), File("output/manual-test3.0.gz").length(p)); LOGUNIT_ASSERT_EQUAL(File("witness/rolling/sbr-test3.1.gz").length(p), File("output/manual-test3.1.gz").length(p)); } /** * Test basic rolling functionality with bogus path in file name pattern. */ void test4() { PatternLayoutPtr layout = PatternLayoutPtr(new PatternLayout(LOG4CXX_STR("%m\n"))); RollingFileAppenderPtr rfa = RollingFileAppenderPtr(new RollingFileAppender()); rfa->setName(LOG4CXX_STR("ROLLING")); rfa->setAppend(false); rfa->setLayout(layout); rfa->setFile(LOG4CXX_STR("output/manual-test4.log")); FixedWindowRollingPolicyPtr swrp = FixedWindowRollingPolicyPtr(new FixedWindowRollingPolicy()); swrp->setCreateIntermediateDirectories(false); swrp->setMinIndex(0); // // test4 directory should not exists. Should cause all rollover attempts to fail. // swrp->setFileNamePattern(LOG4CXX_STR("output/test4/manual-test4.%i")); Pool p; swrp->activateOptions(p); rfa->setRollingPolicy(swrp); rfa->activateOptions(p); root->addAppender(rfa); common(rfa, p, logger); LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test4.log").exists(p)); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test4.log"), File("witness/rolling/sbr-test4.log"))); } /** * Checking handling of rename failures due to other access * to the indexed files. */ void test5() { PatternLayoutPtr layout = PatternLayoutPtr(new PatternLayout(LOG4CXX_STR("%m\n"))); RollingFileAppenderPtr rfa = RollingFileAppenderPtr(new RollingFileAppender()); rfa->setName(LOG4CXX_STR("ROLLING")); rfa->setAppend(false); rfa->setLayout(layout); rfa->setFile(LOG4CXX_STR("output/manual-test5.log")); FixedWindowRollingPolicyPtr swrp = FixedWindowRollingPolicyPtr(new FixedWindowRollingPolicy()); swrp->setMinIndex(0); swrp->setFileNamePattern(LOG4CXX_STR("output/manual-test5.%i")); Pool p; swrp->activateOptions(p); rfa->setRollingPolicy(swrp); rfa->activateOptions(p); root->addAppender(rfa); // // put stray file about locked file FileOutputStream os1(LOG4CXX_STR("output/manual-test5.1"), false); os1.close(p); FileOutputStream os0(LOG4CXX_STR("output/manual-test5.0"), false); common(rfa, p, logger); os0.close(p); if (File("output/manual-test5.3").exists(p)) { // // looks like platform where open files can be renamed // LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test5.log").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test5.0").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test5.1").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test5.2").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test5.3").exists(p)); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test5.log"), File("witness/rolling/sbr-test2.log"))); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test5.0"), File("witness/rolling/sbr-test2.0"))); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test5.1"), File("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. LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test5.log").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test5.0").exists(p)); LOGUNIT_ASSERT_EQUAL(true, File("output/manual-test5.2").exists(p)); LOGUNIT_ASSERT_EQUAL(true, Compare::compare(File("output/manual-test5.log"), File("witness/rolling/sbr-test4.log"))); } } void create_directories() { PatternLayoutPtr layout = PatternLayoutPtr(new PatternLayout(LOG4CXX_STR("%m\n"))); RollingFileAppenderPtr rfa = RollingFileAppenderPtr(new RollingFileAppender()); rfa->setName(LOG4CXX_STR("ROLLING")); rfa->setAppend(false); rfa->setLayout(layout); rfa->setFile(LOG4CXX_STR("output/create-directory-file.log")); FixedWindowRollingPolicyPtr swrp = FixedWindowRollingPolicyPtr(new FixedWindowRollingPolicy()); swrp->setMinIndex(0); std::random_device dev; std::mt19937 rng(dev()); std::uniform_int_distribution dist(1,100000); LogString filenamePattern = LOG4CXX_STR("output/directory-"); LogString dirNumber; StringHelper::toString(dist(rng), dirNumber); filenamePattern.append( dirNumber ); LogString filenamePatternPrefix = filenamePattern; filenamePattern.append( LOG4CXX_STR("/file-%i.gz") ); swrp->setFileNamePattern(filenamePattern); Pool p; swrp->activateOptions(p); rfa->setRollingPolicy(swrp); rfa->activateOptions(p); root->addAppender(rfa); common(rfa, p, logger); LOGUNIT_ASSERT_EQUAL(true, File(filenamePatternPrefix + LOG4CXX_STR("/file-0.gz")).exists(p)); LOGUNIT_ASSERT_EQUAL(true, File(filenamePatternPrefix + LOG4CXX_STR("/file-1.gz")).exists(p)); } }; LOGUNIT_TEST_SUITE_REGISTRATION(ManualRollingTest); apache-log4cxx-1.3.1/src/test/cpp/fileappendertestcase.h0000644000175100001770000000221614721727031022570 0ustar runnerdocker/* * 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. */ #include #include "writerappendertestcase.h" /** An abstract set of tests for inclusion in concrete appender test case */ class FileAppenderAbstractTestCase : public WriterAppenderTestCase { public: log4cxx::WriterAppender* createWriterAppender() const; virtual log4cxx::FileAppender* createFileAppender() const = 0; }; apache-log4cxx-1.3.1/src/test/cpp/asyncappendertestcase.cpp0000644000175100001770000002763214721727031023332 0ustar runnerdocker/* * 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. */ #define NOMINMAX #include "logunit.h" #include #include #include #include "vectorappender.h" #include #include "appenderskeletontestcase.h" #include #include #include #include #include "testchar.h" #include #include #include #include #include using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::spi; class NullPointerAppender : public AppenderSkeleton { public: NullPointerAppender() { } /** * @{inheritDoc} */ void append(const spi::LoggingEventPtr&, log4cxx::helpers::Pool&) override { throw NullPointerException(LOG4CXX_STR("Intentional NullPointerException")); } void close() override { } bool requiresLayout() const override { return false; } }; /** * Vector appender that can be explicitly blocked. */ class BlockableVectorAppender : public VectorAppender { private: std::mutex blocker; public: /** * Create new instance. */ BlockableVectorAppender() { } /** * {@inheritDoc} */ void append(const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& p) override { std::lock_guard lock( blocker ); VectorAppender::append(event, p); // // if fatal, echo messages for testLoggingInDispatcher // if (event->getLevel() == Level::getInfo()) { LoggerPtr logger = Logger::getLoggerLS(event->getLoggerName()); LOG4CXX_LOGLS(logger, Level::getError(), event->getMessage()); LOG4CXX_LOGLS(logger, Level::getWarn(), event->getMessage()); LOG4CXX_LOGLS(logger, Level::getInfo(), event->getMessage()); LOG4CXX_LOGLS(logger, Level::getDebug(), event->getMessage()); } } std::mutex& getBlocker() { return blocker; } }; LOG4CXX_PTR_DEF(BlockableVectorAppender); /** * Tests of AsyncAppender. */ class AsyncAppenderTestCase : public AppenderSkeletonTestCase { LOGUNIT_TEST_SUITE(AsyncAppenderTestCase); // // tests inherited from AppenderSkeletonTestCase // LOGUNIT_TEST(testDefaultThreshold); LOGUNIT_TEST(testSetOptionThreshold); LOGUNIT_TEST(closeTest); LOGUNIT_TEST(test2); LOGUNIT_TEST(testEventFlush); LOGUNIT_TEST(testMultiThread); LOGUNIT_TEST(testBadAppender); LOGUNIT_TEST(testBufferOverflowBehavior); #if LOG4CXX_HAS_DOMCONFIGURATOR LOGUNIT_TEST(testConfiguration); #endif LOGUNIT_TEST_SUITE_END(); #ifdef _DEBUG struct Fixture { Fixture() { helpers::LogLog::setInternalDebugging(true); } } suiteFixture; #endif public: void setUp() { AppenderSkeletonTestCase::setUp(); } void tearDown() { LogManager::shutdown(); AppenderSkeletonTestCase::tearDown(); } AppenderSkeleton* createAppenderSkeleton() const { return new AsyncAppender(); } // this test checks whether it is possible to write to a closed AsyncAppender void closeTest() { LoggerPtr root = Logger::getRootLogger(); LayoutPtr layout = LayoutPtr(new SimpleLayout()); VectorAppenderPtr vectorAppender = VectorAppenderPtr(new VectorAppender()); AsyncAppenderPtr asyncAppender = AsyncAppenderPtr(new AsyncAppender()); asyncAppender->setName(LOG4CXX_STR("async-CloseTest")); asyncAppender->addAppender(vectorAppender); root->addAppender(asyncAppender); root->debug(LOG4CXX_TEST_STR("m1")); asyncAppender->close(); root->debug(LOG4CXX_TEST_STR("m2")); const std::vector& v = vectorAppender->getVector(); LOGUNIT_ASSERT_EQUAL((size_t) 1, v.size()); } // this test checks whether appenders embedded within an AsyncAppender are also // closed void test2() { LoggerPtr root = Logger::getRootLogger(); LayoutPtr layout = SimpleLayoutPtr(new SimpleLayout()); VectorAppenderPtr vectorAppender = VectorAppenderPtr(new VectorAppender()); AsyncAppenderPtr asyncAppender = AsyncAppenderPtr(new AsyncAppender()); asyncAppender->setName(LOG4CXX_STR("async-test2")); asyncAppender->addAppender(vectorAppender); root->addAppender(asyncAppender); root->debug(LOG4CXX_TEST_STR("m1")); asyncAppender->close(); root->debug(LOG4CXX_TEST_STR("m2")); const std::vector& v = vectorAppender->getVector(); LOGUNIT_ASSERT_EQUAL((size_t) 1, v.size()); LOGUNIT_ASSERT(vectorAppender->isClosed()); } // this test checks all messages are delivered when an AsyncAppender is closed void testEventFlush() { size_t LEN = 200; // Larger than default buffer size (128) LoggerPtr root = Logger::getRootLogger(); VectorAppenderPtr vectorAppender = VectorAppenderPtr(new VectorAppender()); vectorAppender->setMillisecondDelay(1); AsyncAppenderPtr asyncAppender = AsyncAppenderPtr(new AsyncAppender()); asyncAppender->setName(LOG4CXX_STR("async-testEventFlush")); asyncAppender->addAppender(vectorAppender); root->addAppender(asyncAppender); for (size_t i = 0; i < LEN; i++) { LOG4CXX_DEBUG(root, "message" << i); } asyncAppender->close(); root->debug(LOG4CXX_STR("m2")); const std::vector& v = vectorAppender->getVector(); LOGUNIT_ASSERT_EQUAL(LEN, v.size()); Pool p; for (size_t i = 0; i < LEN; i++) { LogString m(LOG4CXX_STR("message")); StringHelper::toString(i, p, m); LOGUNIT_ASSERT(v[i]->getMessage() == m); } LOGUNIT_ASSERT_EQUAL(true, vectorAppender->isClosed()); } // this test checks all messages are delivered from multiple threads void testMultiThread() { int LEN = 2000; // Larger than default buffer size (128) auto threadCount = std::max(static_cast(std::thread::hardware_concurrency() - 1), 2); auto root = Logger::getRootLogger(); auto vectorAppender = std::make_shared(); auto asyncAppender = std::make_shared(); asyncAppender->setName(LOG4CXX_STR("async-testMultiThread")); asyncAppender->addAppender(vectorAppender); root->addAppender(asyncAppender); std::vector threads; for ( int x = 0; x < threadCount; x++ ) { threads.emplace_back([root, LEN]() { for (int i = 0; i < LEN; i++) { LOG4CXX_DEBUG(root, "message" << i); } }); } for ( auto& thr : threads ) { if ( thr.joinable() ) { thr.join(); } } asyncAppender->close(); const std::vector& v = vectorAppender->getVector(); LOGUNIT_ASSERT_EQUAL(LEN*threadCount, (int)v.size()); std::map perThreadCount; std::vector msgCount(LEN, 0); for (auto m : v) { auto i = StringHelper::toInt(m->getMessage().substr(7)); LOGUNIT_ASSERT(0 <= i); LOGUNIT_ASSERT(i < LEN); ++msgCount[i]; ++perThreadCount[m->getThreadName()]; } LOGUNIT_ASSERT_EQUAL(threadCount, (int)perThreadCount.size()); for (auto& item : perThreadCount) { LOGUNIT_ASSERT_EQUAL(item.second, LEN); } for (size_t i = 0; i < LEN; i++) LOGUNIT_ASSERT_EQUAL(msgCount[i], threadCount); } /** * Checks that async will switch a bad appender to another appender. */ void testBadAppender() { AppenderPtr nullPointerAppender(new NullPointerAppender()); AsyncAppenderPtr asyncAppender(new AsyncAppender()); asyncAppender->setName(LOG4CXX_STR("async-testBadAppender")); asyncAppender->addAppender(nullPointerAppender); asyncAppender->setBufferSize(5); Pool p; asyncAppender->activateOptions(p); LoggerPtr root = Logger::getRootLogger(); root->addAppender(asyncAppender); varia::FallbackErrorHandlerPtr errorHandler(new varia::FallbackErrorHandler()); errorHandler->setAppender(asyncAppender); VectorAppenderPtr vectorAppender(new VectorAppender()); vectorAppender->setName(LOG4CXX_STR("async-memoryAppender")); errorHandler->setBackupAppender(vectorAppender); errorHandler->setLogger(root); asyncAppender->setErrorHandler(errorHandler); LOG4CXX_INFO(root, "Message"); std::this_thread::sleep_for( std::chrono::milliseconds( 30 ) ); LOGUNIT_ASSERT(errorHandler->errorReported()); LOG4CXX_INFO(root, "Message"); auto& v = vectorAppender->getVector(); LOGUNIT_ASSERT(0 < v.size()); } /** * Tests behavior when the the async buffer overflows. */ void testBufferOverflowBehavior() { BlockableVectorAppenderPtr blockableAppender = BlockableVectorAppenderPtr(new BlockableVectorAppender()); blockableAppender->setName(LOG4CXX_STR("async-blockableVector")); AsyncAppenderPtr async = AsyncAppenderPtr(new AsyncAppender()); async->setName(LOG4CXX_STR("async-testBufferOverflowBehavior")); async->addAppender(blockableAppender); async->setBufferSize(5); async->setLocationInfo(true); async->setBlocking(false); Pool p; async->activateOptions(p); LoggerPtr rootLogger = Logger::getRootLogger(); rootLogger->addAppender(async); LOG4CXX_INFO(rootLogger, "Hello, World"); // This causes the dispatch thread creation std::this_thread::sleep_for( std::chrono::milliseconds( 10 ) ); // Wait for the dispatch thread to be ready { std::lock_guard sync(blockableAppender->getBlocker()); for (int i = 0; i < 140; i++) { LOG4CXX_INFO(rootLogger, "Hello, World"); } LOG4CXX_ERROR(rootLogger, "That's all folks."); } async->close(); const std::vector& events = blockableAppender->getVector(); LOGUNIT_ASSERT(!events.empty()); LoggingEventPtr initialEvent = events.front(); LoggingEventPtr discardEvent = events.back(); LOGUNIT_ASSERT(initialEvent->getMessage() == LOG4CXX_STR("Hello, World")); LOGUNIT_ASSERT(discardEvent->getMessage().substr(0, 10) == LOG4CXX_STR("Discarded ")); LOGUNIT_ASSERT_EQUAL(log4cxx::spi::LocationInfo::getLocationUnavailable().getClassName(), discardEvent->getLocationInformation().getClassName()); } #if LOG4CXX_HAS_DOMCONFIGURATOR void testConfiguration() { log4cxx::xml::DOMConfigurator::configure("input/xml/asyncAppender1.xml"); AsyncAppenderPtr asyncAppender = log4cxx::cast(Logger::getRootLogger()->getAppender(LOG4CXX_STR("ASYNC"))); LOGUNIT_ASSERT(!(asyncAppender == 0)); LOGUNIT_ASSERT_EQUAL(100, asyncAppender->getBufferSize()); LOGUNIT_ASSERT_EQUAL(false, asyncAppender->getBlocking()); LOGUNIT_ASSERT_EQUAL(true, asyncAppender->getLocationInfo()); AppenderList nestedAppenders(asyncAppender->getAllAppenders()); // TODO: // test seems to work okay, but have not found a working way to // get a reference to the nested vector appender // // LOGUNIT_ASSERT_EQUAL((size_t) 1, nestedAppenders.size()); // VectorAppenderPtr vectorAppender(nestedAppenders[0]); // LOGUNIT_ASSERT(0 != vectorAppender); LoggerPtr root(Logger::getRootLogger()); size_t LEN = 20; for (size_t i = 0; i < LEN; i++) { LOG4CXX_DEBUG(root, "message" << i); } asyncAppender->close(); // const std::vector& v = vectorAppender->getVector(); // LOGUNIT_ASSERT_EQUAL(LEN, v.size()); // LOGUNIT_ASSERT_EQUAL(true, vectorAppender->isClosed()); } #endif }; LOGUNIT_TEST_SUITE_REGISTRATION(AsyncAppenderTestCase); apache-log4cxx-1.3.1/src/test/cpp/abts_tests.h0000644000175100001770000000163514721727031020555 0ustar runnerdocker/* 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. */ #ifndef APR_TEST_INCLUDES #define APR_TEST_INCLUDES #include "abts.h" #include "testutil.h" #endif /* APR_TEST_INCLUDES */ apache-log4cxx-1.3.1/src/test/cpp/vectorappender.cpp0000644000175100001770000000241414721727031021752 0ustar runnerdocker/* * 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. */ #include "vectorappender.h" #include using namespace log4cxx; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(VectorAppender) void VectorAppender::append(const spi::LoggingEventPtr& event, Pool& /*p*/) { if (0 < this->appendMillisecondDelay) std::this_thread::sleep_for( std::chrono::milliseconds( this->appendMillisecondDelay ) ); this->vector.push_back(event); } void VectorAppender::close() { if (m_priv->closed) { return; } m_priv->closed = true; } apache-log4cxx-1.3.1/src/test/cpp/pattern/0000755000175100001770000000000014721727031017701 5ustar runnerdockerapache-log4cxx-1.3.1/src/test/cpp/pattern/num343patternconverter.h0000644000175100001770000000245214721727031024434 0ustar runnerdocker/* * 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. */ #include #include namespace LOG4CXX_NS { namespace pattern { class Num343PatternConverter : public LoggingEventPatternConverter { public: DECLARE_LOG4CXX_OBJECT(Num343PatternConverter) Num343PatternConverter(); static PatternConverterPtr newInstance( const std::vector& options); protected: void format( const log4cxx::spi::LoggingEventPtr& event, LogString& toAppendTo, log4cxx::helpers::Pool& pool) const override; }; } } apache-log4cxx-1.3.1/src/test/cpp/pattern/num343patternconverter.cpp0000644000175100001770000000264114721727031024767 0ustar runnerdocker/* * 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. */ #include #include "num343patternconverter.h" using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::pattern; IMPLEMENT_LOG4CXX_OBJECT(Num343PatternConverter) Num343PatternConverter::Num343PatternConverter() : LoggingEventPatternConverter(LOG4CXX_STR("Num343"), LOG4CXX_STR("num343")) { } PatternConverterPtr Num343PatternConverter::newInstance( const std::vector&) { return PatternConverterPtr(new Num343PatternConverter()); } void Num343PatternConverter::format( const spi::LoggingEventPtr&, LogString& sbuf, Pool&) const { sbuf.append(LOG4CXX_STR("343")); } apache-log4cxx-1.3.1/src/test/cpp/pattern/colorstartpatternconvertertest.cpp0000644000175100001770000001746014721727031027037 0ustar runnerdocker/* * 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. */ #include #include #include #include #include "../testchar.h" #include "../insertwide.h" #include "../logunit.h" #include #include #include #define LOG4CXX_TEST 1 #include #include using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::spi; using namespace log4cxx::pattern; LOGUNIT_CLASS(ColorStartPatternConverterTestCase) { LOGUNIT_TEST_SUITE(ColorStartPatternConverterTestCase); LOGUNIT_TEST(testParseForeground); LOGUNIT_TEST(testParseBackground); LOGUNIT_TEST(testParseForegroundAndBackground); LOGUNIT_TEST(testParseUnbalancedParens1); LOGUNIT_TEST(testParseUnbalancedParens2); LOGUNIT_TEST(testParseUnbalancedParens3); LOGUNIT_TEST(testANSICode); LOGUNIT_TEST(testInvalidANSICode); LOGUNIT_TEST(testUnterminatedANSICode); LOGUNIT_TEST(testForegroundBackgroundBlink); LOGUNIT_TEST(testClearColor); LOGUNIT_TEST_SUITE_END(); public: void setUp() { } void tearDown() { } void testParseForeground() { ColorStartPatternConverter colorPatternConverter; LogString outputString; Pool p; LoggingEventPtr event= LoggingEventPtr(new LoggingEvent( LOG4CXX_STR("org.foobar"), Level::getInfo(), LOG4CXX_STR("msg 1"), LOG4CXX_LOCATION)); colorPatternConverter.setInfoColor(LOG4CXX_STR("fg(red)")); colorPatternConverter.format(event, outputString, p); LOGUNIT_ASSERT_EQUAL(LOG4CXX_STR("\x1b[;31m"), outputString); } void testParseBackground() { ColorStartPatternConverter colorPatternConverter; LogString outputString; Pool p; LoggingEventPtr event= LoggingEventPtr(new LoggingEvent( LOG4CXX_STR("org.foobar"), Level::getInfo(), LOG4CXX_STR("msg 1"), LOG4CXX_LOCATION)); colorPatternConverter.setInfoColor(LOG4CXX_STR("bg(red)")); colorPatternConverter.format(event, outputString, p); LOGUNIT_ASSERT_EQUAL(LOG4CXX_STR("\x1b[;41m"), outputString); } void testParseForegroundAndBackground() { ColorStartPatternConverter colorPatternConverter; LogString outputString; Pool p; LoggingEventPtr event= LoggingEventPtr(new LoggingEvent( LOG4CXX_STR("org.foobar"), Level::getInfo(), LOG4CXX_STR("msg 1"), LOG4CXX_LOCATION)); colorPatternConverter.setInfoColor(LOG4CXX_STR("fg(green)|bg(red)")); colorPatternConverter.format(event, outputString, p); LOGUNIT_ASSERT_EQUAL(LOG4CXX_STR("\x1b[;32;41m"), outputString); } void testParseUnbalancedParens1(){ ColorStartPatternConverter colorPatternConverter; LogString outputString; Pool p; LoggingEventPtr event= LoggingEventPtr(new LoggingEvent( LOG4CXX_STR("org.foobar"), Level::getInfo(), LOG4CXX_STR("msg 1"), LOG4CXX_LOCATION)); colorPatternConverter.setInfoColor(LOG4CXX_STR("fg(green))")); colorPatternConverter.format(event, outputString, p); LOGUNIT_ASSERT_EQUAL(LOG4CXX_STR("\x1b[m"), outputString); } void testParseUnbalancedParens2(){ ColorStartPatternConverter colorPatternConverter; LogString outputString; Pool p; LoggingEventPtr event= LoggingEventPtr(new LoggingEvent( LOG4CXX_STR("org.foobar"), Level::getInfo(), LOG4CXX_STR("msg 1"), LOG4CXX_LOCATION)); colorPatternConverter.setInfoColor(LOG4CXX_STR("fg(green")); colorPatternConverter.format(event, outputString, p); LOGUNIT_ASSERT_EQUAL(LOG4CXX_STR("\x1b[m"), outputString); } void testParseUnbalancedParens3(){ ColorStartPatternConverter colorPatternConverter; LogString outputString; Pool p; LoggingEventPtr event= LoggingEventPtr(new LoggingEvent( LOG4CXX_STR("org.foobar"), Level::getInfo(), LOG4CXX_STR("msg 1"), LOG4CXX_LOCATION)); colorPatternConverter.setInfoColor(LOG4CXX_STR("fg(green|bg(red)")); colorPatternConverter.format(event, outputString, p); // The background should be parsed correctly, but since the foreground // is bad it will not work LOGUNIT_ASSERT_EQUAL(LOG4CXX_STR("\x1b[;41m"), outputString); } void testANSICode(){ ColorStartPatternConverter colorPatternConverter; LogString outputString; Pool p; LoggingEventPtr event= LoggingEventPtr(new LoggingEvent( LOG4CXX_STR("org.foobar"), Level::getInfo(), LOG4CXX_STR("msg 1"), LOG4CXX_LOCATION)); colorPatternConverter.setInfoColor(LOG4CXX_STR("\\x1b[34;40m")); colorPatternConverter.format(event, outputString, p); LOGUNIT_ASSERT_EQUAL(LOG4CXX_STR("\x1b[34;40m"), outputString); } void testInvalidANSICode(){ ColorStartPatternConverter colorPatternConverter; LogString outputString; Pool p; LoggingEventPtr event= LoggingEventPtr(new LoggingEvent( LOG4CXX_STR("org.foobar"), Level::getInfo(), LOG4CXX_STR("msg 1"), LOG4CXX_LOCATION)); colorPatternConverter.setInfoColor(LOG4CXX_STR("\\x1b")); colorPatternConverter.format(event, outputString, p); LOGUNIT_ASSERT_EQUAL(LOG4CXX_STR(""), outputString); } void testUnterminatedANSICode(){ ColorStartPatternConverter colorPatternConverter; LogString outputString; Pool p; LoggingEventPtr event= LoggingEventPtr(new LoggingEvent( LOG4CXX_STR("org.foobar"), Level::getInfo(), LOG4CXX_STR("msg 1"), LOG4CXX_LOCATION)); colorPatternConverter.setInfoColor(LOG4CXX_STR("\\x1b[31")); colorPatternConverter.format(event, outputString, p); LOGUNIT_ASSERT_EQUAL(LOG4CXX_STR(""), outputString); } void testForegroundBackgroundBlink(){ ColorStartPatternConverter colorPatternConverter; LogString outputString; Pool p; LoggingEventPtr event= LoggingEventPtr(new LoggingEvent( LOG4CXX_STR("org.foobar"), Level::getInfo(), LOG4CXX_STR("msg 1"), LOG4CXX_LOCATION)); colorPatternConverter.setInfoColor(LOG4CXX_STR("fg(white)|bg(black)|blinking")); colorPatternConverter.format(event, outputString, p); LOGUNIT_ASSERT_EQUAL(LOG4CXX_STR("\x1b[;37;40;5m"), outputString); } void testClearColor(){ ColorStartPatternConverter colorPatternConverter; LogString outputString; Pool p; LoggingEventPtr event= LoggingEventPtr(new LoggingEvent( LOG4CXX_STR("org.foobar"), Level::getInfo(), LOG4CXX_STR("msg 1"), LOG4CXX_LOCATION)); colorPatternConverter.setInfoColor(LOG4CXX_STR("fg(white)|bg(black)|blinking")); colorPatternConverter.setInfoColor(LOG4CXX_STR("")); colorPatternConverter.format(event, outputString, p); LOGUNIT_ASSERT_EQUAL(LOG4CXX_STR(""), outputString); } }; #if !defined(_MSC_VER) || _MSC_VER > 1200 LOGUNIT_TEST_SUITE_REGISTRATION(ColorStartPatternConverterTestCase); #endif apache-log4cxx-1.3.1/src/test/cpp/pattern/patternparsertestcase.cpp0000644000175100001770000002147314721727031025042 0ustar runnerdocker/* * 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. */ #include #include #include #include #include "num343patternconverter.h" #include "../testchar.h" #include "../insertwide.h" #include "../logunit.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define LOG4CXX_TEST 1 #include #include #ifdef _WIN32 #include #endif using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::spi; using namespace log4cxx::pattern; #define RULES_PUT(spec, cls) \ map.insert(PatternMap::value_type(LOG4CXX_STR(spec), (PatternConstructor) cls ::newInstance)) LOGUNIT_CLASS(PatternParserTestCase) { LOGUNIT_TEST_SUITE(PatternParserTestCase); LOGUNIT_TEST(testNewWord); LOGUNIT_TEST(testNewWord2); LOGUNIT_TEST(testBogusWord1); LOGUNIT_TEST(testBogusWord2); LOGUNIT_TEST(testBasic1); LOGUNIT_TEST(testBasic2); LOGUNIT_TEST(testMultiOption); LOGUNIT_TEST(testThreadUsername); LOGUNIT_TEST_SUITE_END(); LoggingEventPtr event; public: void setUp() { LogString threadName = LOG4CXX_STR("log4cxx-thr"); #if LOG4CXX_HAS_PTHREAD_SETNAME && !(defined(_WIN32) && defined(_LIBCPP_VERSION)) LOG4CXX_ENCODE_CHAR(sthreadName, threadName); if( pthread_setname_np( pthread_self(), sthreadName.c_str() ) < 0 ){ LOGLOG_ERROR( LOG4CXX_STR("unable to set thread name") ); } #elif defined(_WIN32) LOG4CXX_ENCODE_WCHAR(wthreadName, threadName); HRESULT hr = SetThreadDescription(GetCurrentThread(), wthreadName.c_str()); if(FAILED(hr)){ LOGLOG_ERROR( LOG4CXX_STR("unable to set thread name") ); } #else threadName = LOG4CXX_STR("(noname)"); #endif event = LoggingEventPtr(new LoggingEvent( LOG4CXX_STR("org.foobar"), Level::getInfo(), LOG4CXX_STR("msg 1"), LOG4CXX_LOCATION)); } void tearDown() { } PatternMap getFormatSpecifiers() { PatternMap map; RULES_PUT("c", LoggerPatternConverter); RULES_PUT("logger", LoggerPatternConverter); RULES_PUT("C", ClassNamePatternConverter); RULES_PUT("class", ClassNamePatternConverter); RULES_PUT("d", DatePatternConverter); RULES_PUT("date", DatePatternConverter); RULES_PUT("F", FileLocationPatternConverter); RULES_PUT("file", FileLocationPatternConverter); RULES_PUT("l", FullLocationPatternConverter); RULES_PUT("L", LineLocationPatternConverter); RULES_PUT("line", LineLocationPatternConverter); RULES_PUT("m", MessagePatternConverter); RULES_PUT("message", MessagePatternConverter); RULES_PUT("n", LineSeparatorPatternConverter); RULES_PUT("M", MethodLocationPatternConverter); RULES_PUT("method", MethodLocationPatternConverter); RULES_PUT("p", LevelPatternConverter); RULES_PUT("level", LevelPatternConverter); RULES_PUT("r", RelativeTimePatternConverter); RULES_PUT("relative", RelativeTimePatternConverter); RULES_PUT("t", ThreadPatternConverter); RULES_PUT("thread", ThreadPatternConverter); RULES_PUT("T", ThreadUsernamePatternConverter); RULES_PUT("threadname", ThreadUsernamePatternConverter); RULES_PUT("x", NDCPatternConverter); RULES_PUT("ndc", NDCPatternConverter); RULES_PUT("X", PropertiesPatternConverter); RULES_PUT("properties", PropertiesPatternConverter); RULES_PUT("throwable", ThrowableInformationPatternConverter); return map; } void assertFormattedEquals(const LogString & pattern, const PatternMap & patternMap, const LogString & expected) { std::vector converters; std::vector fields; PatternParser::parse(pattern, converters, fields, patternMap); Pool p; LogString actual; std::vector::const_iterator fieldIter = fields.begin(); for (std::vector::const_iterator converterIter = converters.begin(); converterIter != converters.end(); converterIter++, fieldIter++) { auto fieldStart = static_cast(actual.length()); (*converterIter)->format(event, actual, p); (*fieldIter)->format(fieldStart, actual); } LOGUNIT_ASSERT_EQUAL(expected, actual); } void testNewWord() { PatternMap testRules(getFormatSpecifiers()); testRules.insert( PatternMap::value_type(LOG4CXX_STR("z343"), (PatternConstructor) Num343PatternConverter::newInstance)); assertFormattedEquals(LOG4CXX_STR("%z343"), testRules, LOG4CXX_STR("343")); } /* Test whether words starting with the letter 'n' are treated differently, * which was previously the case by mistake. */ void testNewWord2() { PatternMap testRules(getFormatSpecifiers()); testRules.insert( PatternMap::value_type(LOG4CXX_STR("n343"), (PatternConstructor) Num343PatternConverter::newInstance)); assertFormattedEquals(LOG4CXX_STR("%n343"), testRules, LOG4CXX_STR("343")); } void testBogusWord1() { assertFormattedEquals(LOG4CXX_STR("%, foobar"), getFormatSpecifiers(), LOG4CXX_STR("%, foobar")); } void testBogusWord2() { assertFormattedEquals(LOG4CXX_STR("xyz %, foobar"), getFormatSpecifiers(), LOG4CXX_STR("xyz %, foobar")); } void testBasic1() { assertFormattedEquals(LOG4CXX_STR("hello %-5level - %m%n"), getFormatSpecifiers(), LogString(LOG4CXX_STR("hello INFO - msg 1")) + LOG4CXX_EOL); } void testBasic2() { Pool pool; RelativeTimeDateFormat relativeFormat; LogString expected; relativeFormat.format(expected, event->getTimeStamp(), pool); expected.append(LOG4CXX_STR(" INFO [")); expected.append(event->getThreadName()); expected.append(LOG4CXX_STR("] org.foobar - msg 1")); expected.append(LOG4CXX_EOL); assertFormattedEquals(LOG4CXX_STR("%relative %-5level [%thread] %logger - %m%n"), getFormatSpecifiers(), expected); } void testMultiOption() { Pool pool; SimpleDateFormat dateFormat(LOG4CXX_STR("HH:mm:ss")); LogString localTime; dateFormat.format(localTime, event->getTimeStamp(), pool); dateFormat.setTimeZone(TimeZone::getGMT()); LogString utcTime; dateFormat.format(utcTime, event->getTimeStamp(), pool); LogString expected(utcTime); expected.append(1, LOG4CXX_STR(' ')); expected.append(localTime); expected.append(LOG4CXX_STR(" org.foobar - msg 1")); assertFormattedEquals(LOG4CXX_STR("%d{HH:mm:ss}{GMT} %d{HH:mm:ss} %c - %m"), getFormatSpecifiers(), expected); } void testThreadUsername() { Pool pool; RelativeTimeDateFormat relativeFormat; LogString expected; relativeFormat.format(expected, event->getTimeStamp(), pool); expected.append(LOG4CXX_STR(" INFO [")); expected.append(event->getThreadUserName()); expected.append(LOG4CXX_STR("] org.foobar - msg 1")); expected.append(LOG4CXX_EOL); assertFormattedEquals(LOG4CXX_STR("%relative %-5level [%threadname] %logger - %m%n"), getFormatSpecifiers(), expected); } }; // // See bug LOGCXX-204 // #if !defined(_MSC_VER) || _MSC_VER > 1200 LOGUNIT_TEST_SUITE_REGISTRATION(PatternParserTestCase); #endif apache-log4cxx-1.3.1/src/test/cpp/pattern/CMakeLists.txt0000644000175100001770000000175614721727031022452 0ustar runnerdocker# # 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. # add_executable(patternparsertestcase patternparsertestcase.cpp num343patternconverter.cpp colorstartpatternconvertertest.cpp ) set(ALL_LOG4CXX_TESTS ${ALL_LOG4CXX_TESTS} patternparsertestcase PARENT_SCOPE) apache-log4cxx-1.3.1/src/test/cpp/multithreadtest.cpp0000644000175100001770000000670414721727031022161 0ustar runnerdocker/* * 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. */ #include "logunit.h" #include #include #include #include #include #include #include #include #include using namespace log4cxx; //#define TEST_WITH_FLUENT_BIT #ifdef TEST_WITH_FLUENT_BIT #include #include class MyAppender : public net::XMLSocketAppender { public: MyAppender() : net::XMLSocketAppender(LOG4CXX_STR("127.0.0.1"), 5170) { auto layout = std::make_shared(); layout->setThreadInfo(true); setLayout(layout); } }; #else class MyAppender : public FileAppender { public: MyAppender() { auto tempDir = helpers::OptionConverter::getSystemProperty(LOG4CXX_STR("TEMP"), LOG4CXX_STR("/tmp")); setFile(tempDir + LOG4CXX_STR("/") + LOG4CXX_STR("multithread_test.log")); setLayout(std::make_shared(LOG4CXX_STR("%d [%t] %-5p %.16c - %m%n"))); setAppend(false); setBufferedIO(true); helpers::Pool p; activateOptions(p); } }; #endif static void multithread_logger( int times ) { /* * An explanation on this test: according to LOGCXX-322, calling * exit(0) (or equivalent) from a secondary thread causes a segfault. * * In order to do this somewhat reliably, we generate a pseudo-random * number in each thread that will call the exit() function from that thread. * Sadly this is not a 100% reliable way of generating a hit on std::exit, * but given enough iterations and enough threads it seems to be working just * fine. */ static std::once_flag exiting; LoggerPtr logger = LogManager::getLogger( "test.multithreaded" ); std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> distribution( 100, times ); for ( int x = 0; x < times; x++ ) { LOG4CXX_INFO( logger, "This is test message " << x ); if ( distribution(gen) == x ) { LOG4CXX_INFO( logger, "Exiting"); std::call_once(exiting, std::exit, 0); } } } LOGUNIT_CLASS(MultithreadTest) { LOGUNIT_TEST_SUITE(MultithreadTest); LOGUNIT_TEST(testMultithreadedLoggers); LOGUNIT_TEST_SUITE_END(); public: void setUp() { Logger::getRootLogger()->removeAllAppenders(); Logger::getRootLogger()->addAppender( std::make_shared() ); } void tearDown() { } void testMultithreadedLoggers() { std::vector threads; for ( int x = 0; x < 6; x++ ) { std::thread thr( multithread_logger, 20000 ); threads.push_back( std::move(thr) ); } for ( std::thread& thr : threads ) { if ( thr.joinable() ) { thr.join(); } } } }; LOGUNIT_TEST_SUITE_REGISTRATION(MultithreadTest); apache-log4cxx-1.3.1/src/test/cpp/fileappendertest.cpp0000644000175100001770000000476514721727031022302 0ustar runnerdocker/* * 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. */ #include #include #include #include "logunit.h" using namespace log4cxx; using namespace log4cxx::helpers; /** * * FileAppender tests. */ LOGUNIT_CLASS(FileAppenderTest) { LOGUNIT_TEST_SUITE(FileAppenderTest); LOGUNIT_TEST(testDirectoryCreation); LOGUNIT_TEST(testgetSetThreshold); LOGUNIT_TEST(testIsAsSevereAsThreshold); LOGUNIT_TEST_SUITE_END(); public: /** * Tests that any necessary directories are attempted to * be created if they don't exist. See bug 9150. * */ void testDirectoryCreation() { File newFile(LOG4CXX_STR("output/newdir/temp.log")); Pool p; newFile.deleteFile(p); File newDir(LOG4CXX_STR("output/newdir")); newDir.deleteFile(p); FileAppenderPtr wa(new FileAppender()); wa->setFile(LOG4CXX_STR("output/newdir/temp.log")); wa->setLayout(PatternLayoutPtr(new PatternLayout(LOG4CXX_STR("%m%n")))); wa->activateOptions(p); LOGUNIT_ASSERT(File(LOG4CXX_STR("output/newdir/temp.log")).exists(p)); } /** * Tests getThreshold and setThreshold. */ void testgetSetThreshold() { FileAppenderPtr appender = FileAppenderPtr(new FileAppender()); LevelPtr debug = Level::getDebug(); // // different from log4j where threshold is null. // LOGUNIT_ASSERT_EQUAL(Level::getAll(), appender->getThreshold()); appender->setThreshold(debug); LOGUNIT_ASSERT_EQUAL(debug, appender->getThreshold()); } /** * Tests isAsSevereAsThreshold. */ void testIsAsSevereAsThreshold() { FileAppenderPtr appender = FileAppenderPtr(new FileAppender()); LevelPtr debug = Level::getDebug(); LOGUNIT_ASSERT(appender->isAsSevereAsThreshold(debug)); } }; LOGUNIT_TEST_SUITE_REGISTRATION(FileAppenderTest); apache-log4cxx-1.3.1/src/test/cpp/levelchangetestcase.cpp0000644000175100001770000000746414721727031022754 0ustar runnerdocker /* * 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. */ #include #include #include #include "logunit.h" using namespace log4cxx; namespace { class CountingAppender : public AppenderSkeleton { public: int count; CountingAppender() : count(0) {} void close() override {} void append(const spi::LoggingEventPtr& /*event*/, helpers::Pool& /*p*/) override { count++; } bool requiresLayout() const override { return true; } LogString getName() const override { return LOG4CXX_STR("counter"); } }; LoggerPtr getLogger(const LogString& name = LogString()) { auto r = LogManager::getLoggerRepository(); r->ensureIsConfigured([r]() { r->getRootLogger()->addAppender(std::make_shared()); }); return name.empty() ? r->getRootLogger() : r->getLogger(name); } } // anonymous namespace // A mocked worker class ComplexProcessing { public: LoggerPtr logger = getLogger(LOG4CXX_STR("ComplexProcessing")); void DoStep1() { LOG4CXX_DEBUG(logger, "Step 1 message"); } void DoStep2() { LOG4CXX_DEBUG(logger, "Step 2 message"); } void DoStep3() { LOG4CXX_DEBUG(logger, "Step 3 message"); } }; static ComplexProcessing processor; LOGUNIT_CLASS(LevelChangeTestCase) { LOGUNIT_TEST_SUITE(LevelChangeTestCase); LOGUNIT_TEST(testLevelChange); LOGUNIT_TEST_SUITE_END(); #ifdef _DEBUG struct Fixture { Fixture() { helpers::LogLog::setInternalDebugging(true); } } suiteFixture; #endif public: void setUp() { // Disable DEBUG output from ComplexProcessing processor.logger->setLevel(Level::getInfo()); } void testLevelChange() { auto appender = dynamic_cast(getLogger()->getAppender(LOG4CXX_STR("counter")).get()); LOGUNIT_ASSERT(appender); auto myLogger = getLogger(LOG4CXX_STR("Controller")); myLogger->setLevel(Level::getDebug()); // Check this debug request is sent to the appender LOG4CXX_DEBUG(myLogger, "Start test"); auto initialCount = appender->count; LOGUNIT_ASSERT_EQUAL(initialCount, 1); // Check the ComplexProcessing debug request is not sent to the appender processor.DoStep1(); LOGUNIT_ASSERT_EQUAL(appender->count, initialCount); { LevelChange ctx(getLogger(LOG4CXX_STR("ComplexProcessing")), myLogger); processor.DoStep2(); // Check the ComplexProcessing debug request was sent to the appender LOGUNIT_ASSERT_EQUAL(appender->count, initialCount + 1); } // Check the ComplexProcessing debug request is not sent to the appender processor.DoStep1(); LOGUNIT_ASSERT_EQUAL(appender->count, initialCount + 1); { LevelChange ctx(LOG4CXX_STR("ComplexProcessing"), myLogger); processor.DoStep2(); // Check the ComplexProcessing debug request was sent to the appender LOGUNIT_ASSERT_EQUAL(appender->count, initialCount + 2); } // Check the ComplexProcessing debug request is no longer sent to the appender auto finalCount = appender->count; processor.DoStep3(); LOGUNIT_ASSERT_EQUAL(appender->count, finalCount); } }; LOGUNIT_TEST_SUITE_REGISTRATION(LevelChangeTestCase); apache-log4cxx-1.3.1/src/test/cpp/l7dtestcase.cpp0000644000175100001770000000631614721727031021160 0ustar runnerdocker/* * 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. */ #include #include #include #include #include "util/compare.h" #include #include #include "testchar.h" #include "logunit.h" #include typedef std::basic_ostringstream StringBuffer; using namespace log4cxx; using namespace log4cxx::helpers; LOGUNIT_CLASS(L7dTestCase) { LOGUNIT_TEST_SUITE(L7dTestCase); LOGUNIT_TEST(test1); LOGUNIT_TEST_SUITE_END(); LoggerPtr root; ResourceBundlePtr bundles[3]; public: void setUp() { Locale localeUS(LOG4CXX_STR("en"), LOG4CXX_STR("US")); bundles[0] = ResourceBundle::getBundle(LOG4CXX_STR("L7D"), localeUS); LOGUNIT_ASSERT(bundles[0] != 0); Locale localeFR(LOG4CXX_STR("fr"), LOG4CXX_STR("FR")); bundles[1] = ResourceBundle::getBundle(LOG4CXX_STR("L7D"), localeFR); LOGUNIT_ASSERT(bundles[1] != 0); Locale localeCH(LOG4CXX_STR("fr"), LOG4CXX_STR("CH")); bundles[2] = ResourceBundle::getBundle(LOG4CXX_STR("L7D"), localeCH); LOGUNIT_ASSERT(bundles[2] != 0); root = Logger::getRootLogger(); } void tearDown() { auto rep = root->getLoggerRepository(); if (rep) { rep->resetConfiguration(); } } void test1() { PropertyConfigurator::configure(LOG4CXX_FILE("input/l7d1.properties")); log4cxx::helpers::Pool pool; for (int i = 0; i < 3; i++) { root->setResourceBundle(bundles[i]); LOG4CXX_L7DLOG(root, Level::getDebug(), LOG4CXX_TEST_STR("bogus1")); LOG4CXX_L7DLOG(root, Level::getInfo(), LOG4CXX_TEST_STR("test")); LOG4CXX_L7DLOG(root, Level::getWarn(), LOG4CXX_TEST_STR("hello_world")); StringBuffer os; os << (i + 1); LOG4CXX_L7DLOG2(root, Level::getDebug(), LOG4CXX_TEST_STR("msg1"), os.str().c_str(), LOG4CXX_TEST_STR("log4j")); LOG4CXX_L7DLOG2(root, Level::getError(), LOG4CXX_TEST_STR("bogusMsg"), os.str().c_str(), LOG4CXX_TEST_STR("log4j")); LOG4CXX_L7DLOG2(root, Level::getError(), LOG4CXX_TEST_STR("msg1"), os.str().c_str(), LOG4CXX_TEST_STR("log4j")); LOG4CXX_L7DLOG(root, Level::getInfo(), LOG4CXX_TEST_STR("bogus2")); LOG4CXX_L7DLOG3(root, Level::getError(), LOG4CXX_TEST_STR("msg3"), os.str().c_str(), LOG4CXX_TEST_STR("log4j"), LOG4CXX_TEST_STR("log4cxx")); } LOGUNIT_ASSERT(Compare::compare(LOG4CXX_FILE("output/l7d1"), LOG4CXX_FILE("witness/l7d.1"))); } }; LOGUNIT_TEST_SUITE_REGISTRATION(L7dTestCase); apache-log4cxx-1.3.1/src/test/cpp/varia/0000755000175100001770000000000014721727031017326 5ustar runnerdockerapache-log4cxx-1.3.1/src/test/cpp/varia/levelrangefiltertestcase.cpp0000644000175100001770000001610014721727031025116 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include "../util/compare.h" #include #include #include #include "../testchar.h" #include "../logunit.h" #include using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::filter; LOGUNIT_CLASS(LevelRangeFilterTestCase) { LOGUNIT_TEST_SUITE(LevelRangeFilterTestCase); LOGUNIT_TEST(accept); LOGUNIT_TEST(neutral); LOGUNIT_TEST_SUITE_END(); LoggerPtr root; LoggerPtr logger; public: void setUp() { root = Logger::getRootLogger(); root->removeAllAppenders(); logger = Logger::getLogger(LOG4CXX_TEST_STR("test")); } void tearDown() { auto rep = root->getLoggerRepository(); if (rep) { rep->resetConfiguration(); } } void accept() { // set up appender LayoutPtr layout = LayoutPtr(new SimpleLayout()); AppenderPtr appender = AppenderPtr(new FileAppender(layout, ACCEPT_FILE, false)); // create LevelMatchFilter LevelRangeFilterPtr rangeFilter = LevelRangeFilterPtr(new LevelRangeFilter()); // set it to accept on a match rangeFilter->setAcceptOnMatch(true); // attach match filter to appender appender->addFilter(rangeFilter); // set appender on root and set level to debug root->addAppender(appender); root->setLevel(Level::getDebug()); int passCount = 0; LogString sbuf(LOG4CXX_STR("pass ")); Pool pool; StringHelper::toString(passCount, pool, sbuf); sbuf.append(LOG4CXX_STR("; no min or max set")); common(sbuf); passCount++; // test with a min set rangeFilter->setLevelMin(Level::getWarn()); sbuf.assign(LOG4CXX_STR("pass ")); StringHelper::toString(passCount, pool, sbuf); sbuf.append(LOG4CXX_STR("; min set to WARN, max not set")); common(sbuf); passCount++; // create a clean filter appender->clearFilters(); rangeFilter = LevelRangeFilterPtr(new LevelRangeFilter()); appender->addFilter(rangeFilter); //test with max set rangeFilter->setLevelMax(Level::getWarn()); sbuf.assign(LOG4CXX_STR("pass ")); StringHelper::toString(passCount, pool, sbuf); sbuf.append(LOG4CXX_STR("; min not set, max set to WARN")); common(sbuf); passCount++; LevelPtr levelArray[] = { Level::getDebug(), Level::getInfo(), Level::getWarn(), Level::getError(), Level::getFatal() }; int length = sizeof(levelArray) / sizeof(levelArray[0]); for (int x = 0; x < length; x++) { // set the min level to match rangeFilter->setLevelMin(levelArray[x]); for (int y = length - 1; y >= 0; y--) { // set max level to match rangeFilter->setLevelMax(levelArray[y]); sbuf.assign(LOG4CXX_STR("pass ")); StringHelper::toString(passCount, pool, sbuf); sbuf.append(LOG4CXX_STR("; filter set to accept between ")); sbuf.append(levelArray[x]->toString()); sbuf.append(LOG4CXX_STR(" and ")); sbuf.append(levelArray[y]->toString()); sbuf.append(LOG4CXX_STR(" msgs")); common(sbuf); // increment passCount passCount++; } } LOGUNIT_ASSERT(Compare::compare(ACCEPT_FILE, ACCEPT_WITNESS)); } void neutral() { // set up appender LayoutPtr layout = LayoutPtr(new SimpleLayout()); AppenderPtr appender = AppenderPtr(new FileAppender(layout, NEUTRAL_FILE, false)); // create LevelMatchFilter LevelRangeFilterPtr rangeFilter = LevelRangeFilterPtr(new LevelRangeFilter()); // set it to accept on a match rangeFilter->setAcceptOnMatch(true); // attach match filter to appender appender->addFilter(rangeFilter); // set appender on root and set level to debug root->addAppender(appender); root->setLevel(Level::getDebug()); int passCount = 0; LogString sbuf(LOG4CXX_STR("pass ")); Pool pool; StringHelper::toString(passCount, pool, sbuf); // test with no min or max set sbuf.append(LOG4CXX_STR("; no min or max set")); common(sbuf); passCount++; // test with a min set rangeFilter->setLevelMin(Level::getWarn()); sbuf.assign(LOG4CXX_STR("pass ")); StringHelper::toString(passCount, pool, sbuf); sbuf.append(LOG4CXX_STR("; min set to WARN, max not set")); common(sbuf); passCount++; // create a clean filter appender->clearFilters(); rangeFilter = LevelRangeFilterPtr(new LevelRangeFilter()); appender->addFilter(rangeFilter); //test with max set rangeFilter->setLevelMax(Level::getWarn()); sbuf.assign(LOG4CXX_STR("pass ")); StringHelper::toString(passCount, pool, sbuf); sbuf.append(LOG4CXX_STR("; min not set, max set to WARN")); common(sbuf); passCount++; LevelPtr levelArray[] = { Level::getDebug(), Level::getInfo(), Level::getWarn(), Level::getError(), Level::getFatal() }; int length = sizeof(levelArray) / sizeof(levelArray[0]); for (int x = 0; x < length; x++) { // set the min level to match rangeFilter->setLevelMin(levelArray[x]); for (int y = length - 1; y >= 0; y--) { // set max level to match rangeFilter->setLevelMax(levelArray[y]); sbuf.assign(LOG4CXX_STR("pass ")); StringHelper::toString(passCount, pool, sbuf); sbuf.append(LOG4CXX_STR("; filter set to accept between ")); sbuf.append(levelArray[x]->toString()); sbuf.append(LOG4CXX_STR(" and ")); sbuf.append(levelArray[y]->toString()); sbuf.append(LOG4CXX_STR(" msgs")); common(sbuf); // increment passCount passCount++; } } LOGUNIT_ASSERT(Compare::compare(NEUTRAL_FILE, NEUTRAL_WITNESS)); } void common(const LogString & msg) { logger->debug(msg); logger->info(msg); logger->warn(msg); logger->error(msg); logger->fatal(msg); } private: static const LogString ACCEPT_FILE; static const LogString ACCEPT_WITNESS; static const LogString NEUTRAL_FILE; static const LogString NEUTRAL_WITNESS; }; const LogString LevelRangeFilterTestCase::ACCEPT_FILE(LOG4CXX_STR("output/LevelRangeFilter_accept")); const LogString LevelRangeFilterTestCase::ACCEPT_WITNESS(LOG4CXX_STR("witness/LevelRangeFilter_accept")); const LogString LevelRangeFilterTestCase::NEUTRAL_FILE(LOG4CXX_STR("output/LevelRangeFilter_neutral")); const LogString LevelRangeFilterTestCase::NEUTRAL_WITNESS(LOG4CXX_STR("witness/LevelRangeFilter_neutral")); LOGUNIT_TEST_SUITE_REGISTRATION(LevelRangeFilterTestCase); apache-log4cxx-1.3.1/src/test/cpp/varia/errorhandlertestcase.cpp0000644000175100001770000001101614721727031024254 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include "../logunit.h" #include "../util/transformer.h" #include "../util/compare.h" #include "../util/controlfilter.h" #include "../util/linenumberfilter.h" #include using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::xml; LOGUNIT_CLASS(ErrorHandlerTestCase) { LOGUNIT_TEST_SUITE(ErrorHandlerTestCase); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST_SUITE_END(); LoggerPtr root; LoggerPtr logger; #ifdef _DEBUG struct Fixture { Fixture() { helpers::LogLog::setInternalDebugging(true); } } suiteFixture; #endif public: void setUp() { root = Logger::getRootLogger(); logger = Logger::getLogger("test"); } void tearDown() { auto rep = logger->getLoggerRepository(); if (rep) { rep->resetConfiguration(); } } void test1() { DOMConfigurator::configure("input/xml/fallback1.xml"); AppenderPtr appender = root->getAppender(LOG4CXX_STR("PRIMARY")); FileAppenderPtr primary = log4cxx::cast(appender); log4cxx::varia::FallbackErrorHandlerPtr eh; log4cxx::spi::ErrorHandlerPtr errHandle = primary->getErrorHandler(); eh = log4cxx::cast(errHandle); LOGUNIT_ASSERT(eh != 0); common(); LOGUNIT_ASSERT(eh->errorReported()); std::string TEST1_PAT = "FALLBACK - (root|test) - Message {0-9}"; ControlFilter cf; cf << TEST1_PAT; LineNumberFilter lineNumberFilter; std::vector filters; filters.push_back(&cf); filters.push_back(&lineNumberFilter); try { Transformer::transform("output/fallback1", "output/fallbackfiltered1", filters); } catch (UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare("output/fallbackfiltered1", "witness/fallback1")); } void test2() { DOMConfigurator::configure("input/xml/fallback2.xml"); AppenderPtr appender = root->getAppender(LOG4CXX_STR("PRIMARY")); FileAppenderPtr primary = log4cxx::cast(appender); log4cxx::varia::FallbackErrorHandlerPtr eh; log4cxx::spi::ErrorHandlerPtr errHandle = primary->getErrorHandler(); eh = log4cxx::cast(errHandle); LOGUNIT_ASSERT(eh != 0); eh->setLogger(logger); common(); LOGUNIT_ASSERT(eh->errorReported()); std::string TEST1_PAT = "FALLBACK - (root|test) - Message {0-9}"; ControlFilter cf; cf << TEST1_PAT; LineNumberFilter lineNumberFilter; std::vector filters; filters.push_back(&cf); filters.push_back(&lineNumberFilter); try { Transformer::transform("output/fallback2", "output/fallbackfiltered2", filters); } catch (UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare("output/fallbackfiltered2", "witness/fallback1")); } void common() { int i = -1; LOG4CXX_DEBUG(logger, "Message " << ++i); LOG4CXX_DEBUG(root, "Message " << i); LOG4CXX_INFO(logger, "Message " << ++i); LOG4CXX_INFO(root, "Message " << i); LOG4CXX_WARN(logger, "Message " << ++i); LOG4CXX_WARN(root, "Message " << i); LOG4CXX_ERROR(logger, "Message " << ++i); LOG4CXX_ERROR(root, "Message " << i); LOG4CXX_FATAL(logger, "Message " << ++i); LOG4CXX_FATAL(root, "Message " << i); LOG4CXX_DEBUG(logger, "Message " << ++i); LOG4CXX_DEBUG(root, "Message " << i); LOG4CXX_ERROR(logger, "Message " << ++i); LOG4CXX_ERROR(root, "Message " << i); } }; LOGUNIT_TEST_SUITE_REGISTRATION(ErrorHandlerTestCase) apache-log4cxx-1.3.1/src/test/cpp/varia/CMakeLists.txt0000644000175100001770000000226314721727031022071 0ustar runnerdocker# # 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. # # Tests defined in this directory set(VARIA_TESTS errorhandlertestcase levelmatchfiltertestcase levelrangefiltertestcase ) if(NOT LOG4CXX_DOMCONFIGURATOR_SUPPORT) list(REMOVE_ITEM VARIA_TESTS errorhandlertestcase) endif() foreach(fileName IN LISTS VARIA_TESTS) add_executable(${fileName} "${fileName}.cpp") endforeach() set(ALL_LOG4CXX_TESTS ${ALL_LOG4CXX_TESTS} ${VARIA_TESTS} PARENT_SCOPE) apache-log4cxx-1.3.1/src/test/cpp/varia/levelmatchfiltertestcase.cpp0000644000175100001770000001171114721727031025121 0ustar runnerdocker/* * 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. */ #include "../logunit.h" #include #include #include #include #include #include #include #include #include #include #include "../util/compare.h" #include "../testchar.h" using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::filter; LOGUNIT_CLASS(LevelMatchFilterTestCase) { LOGUNIT_TEST_SUITE(LevelMatchFilterTestCase); LOGUNIT_TEST(accept); LOGUNIT_TEST(deny); LOGUNIT_TEST_SUITE_END(); LoggerPtr root; LoggerPtr logger; public: void setUp() { root = Logger::getRootLogger(); root->removeAllAppenders(); logger = Logger::getLogger(LOG4CXX_TEST_STR("test")); } void tearDown() { auto rep = root->getLoggerRepository(); if (rep) { rep->resetConfiguration(); } } void accept() { // set up appender LayoutPtr layout = LayoutPtr(new SimpleLayout()); AppenderPtr appender = AppenderPtr(new FileAppender(layout, ACCEPT_FILE, false)); // create LevelMatchFilter LevelMatchFilterPtr matchFilter = LevelMatchFilterPtr(new LevelMatchFilter()); // attach match filter to appender appender->addFilter(matchFilter); // attach DenyAllFilter to end of filter chain to deny neutral // (non matching) messages spi::FilterPtr filter(new DenyAllFilter()); appender->addFilter(filter); // set appender on root and set level to debug root->addAppender(appender); root->setLevel(Level::getDebug()); LevelPtr levelArray[] = { Level::getDebug(), Level::getInfo(), Level::getWarn(), Level::getError(), Level::getFatal() }; int length = sizeof(levelArray) / sizeof(levelArray[0]); Pool pool; for (int x = 0; x < length; x++) { // set the level to match matchFilter->setLevelToMatch(levelArray[x]->toString()); LogString sbuf(LOG4CXX_STR("pass ")); StringHelper::toString(x, pool, sbuf); sbuf.append(LOG4CXX_STR("; filter set to accept only ")); sbuf.append(levelArray[x]->toString()); sbuf.append(LOG4CXX_STR(" msgs")); common(sbuf); } LOGUNIT_ASSERT(Compare::compare(ACCEPT_FILE, ACCEPT_WITNESS)); } void deny() { // set up appender LayoutPtr layout = LayoutPtr(new SimpleLayout()); AppenderPtr appender = AppenderPtr(new FileAppender(layout, DENY_FILE, false)); // create LevelMatchFilter, set to deny matches LevelMatchFilterPtr matchFilter = LevelMatchFilterPtr(new LevelMatchFilter()); matchFilter->setAcceptOnMatch(false); // attach match filter to appender appender->addFilter(matchFilter); // set appender on root and set level to debug root->addAppender(appender); root->setLevel(Level::getDebug()); LevelPtr levelArray[] = { Level::getDebug(), Level::getInfo(), Level::getWarn(), Level::getError(), Level::getFatal() }; int length = sizeof(levelArray) / sizeof(levelArray[0]); Pool pool; for (int x = 0; x < length; x++) { // set the level to match matchFilter->setLevelToMatch(levelArray[x]->toString()); LogString sbuf(LOG4CXX_STR("pass ")); StringHelper::toString(x, pool, sbuf); sbuf.append(LOG4CXX_STR("; filter set to deny only ")); sbuf.append(levelArray[x]->toString()); sbuf.append(LOG4CXX_STR(" msgs")); common(sbuf); } LOGUNIT_ASSERT(Compare::compare(DENY_FILE, DENY_WITNESS)); } void common(const LogString & msg) { logger->debug(msg); logger->info(msg); logger->warn(msg); logger->error(msg); logger->fatal(msg); } private: static const LogString ACCEPT_FILE; static const LogString ACCEPT_WITNESS; static const LogString DENY_FILE; static const LogString DENY_WITNESS; }; const LogString LevelMatchFilterTestCase::ACCEPT_FILE(LOG4CXX_STR("output/LevelMatchFilter_accept")); const LogString LevelMatchFilterTestCase::ACCEPT_WITNESS(LOG4CXX_STR("witness/LevelMatchFilter_accept")); const LogString LevelMatchFilterTestCase::DENY_FILE(LOG4CXX_STR("output/LevelMatchFilter_deny")); const LogString LevelMatchFilterTestCase::DENY_WITNESS(LOG4CXX_STR("witness/LevelMatchFilter_deny")); LOGUNIT_TEST_SUITE_REGISTRATION(LevelMatchFilterTestCase); apache-log4cxx-1.3.1/src/test/cpp/consoleappendertestcase.cpp0000644000175100001770000000340614721727031023650 0ustar runnerdocker/* * 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. */ #include #include "logunit.h" #include "writerappendertestcase.h" using namespace log4cxx; using namespace log4cxx::helpers; /** Unit tests of ConsoleAppender. */ class ConsoleAppenderTestCase : public WriterAppenderTestCase { LOGUNIT_TEST_SUITE(ConsoleAppenderTestCase); // // tests inherited from AppenderSkeletonTestCase // LOGUNIT_TEST(testDefaultThreshold); LOGUNIT_TEST(testSetOptionThreshold); LOGUNIT_TEST(testNoLayout); LOGUNIT_TEST_SUITE_END(); public: WriterAppender* createWriterAppender() const { return new log4cxx::ConsoleAppender(); } void testNoLayout() { Pool p; ConsoleAppenderPtr appender(new ConsoleAppender()); appender->activateOptions(p); LoggerPtr logger(Logger::getRootLogger()); logger->addAppender(appender); LOG4CXX_INFO(logger, "No layout specified for ConsoleAppender"); logger->removeAppender(appender); } }; LOGUNIT_TEST_SUITE_REGISTRATION(ConsoleAppenderTestCase); apache-log4cxx-1.3.1/src/test/cpp/throughput/0000755000175100001770000000000014721727031020435 5ustar runnerdockerapache-log4cxx-1.3.1/src/test/cpp/throughput/log4cxxbenchmarker.h0000644000175100001770000000602114721727031024377 0ustar runnerdocker/* * 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. */ #ifndef LOG4CXXBENCHMARKER_H #define LOG4CXXBENCHMARKER_H #include #include class log4cxxbenchmarker { private: log4cxxbenchmarker(); static log4cxx::LoggerPtr resetLogger(); public: /** * Given a conversion pattern, send a number of log messages to the logger. INFO level. * * Log message format: "Hello logger: msg number " << x * * @param conversionPattern The conversion pattern used, as passed to the PatternLayout */ static void logWithConversionPattern( const log4cxx::LogString& conversionPattern, int howmany ); /** * Log with the LOG4CXX_INFO_FMT macro to see how long it takes. * This does a single parameter replacement with libfmt(the same message as logWithConversionPattern) * * @param howmany */ static void logWithFMT( int howmany ); /** * Reset logger for multithreaded setup. */ static log4cxx::LoggerPtr logSetupMultithreaded(); /** * Log with the LOG4CXX_INFO_FMT macro to see how long it takes(multithreaded). * @param howmany */ static void logWithFMTMultithreaded( int howmany ); /** * Log messages in a multithreaded manner, but at a TRACE level * so they will be disabled. * * @param howmany */ static void logDisabledMultithreaded( int howmany ); /** * Log a string that doesn't use operator<< any place. * Logs at INFO level * * String to log: "This is a static string to see what happens" * @param howmany */ static void logStaticString( int howmany ); /** * Log a string that doesn't use operator<< any place, but uses libfmt. * Logs at INFO level * * String to log: "This is a static string to see what happens" * @param howmany */ static void logStaticStringFMT( int howmany ); /** * Log a message at the DEBUG level, with debug disabled. */ static void logDisabledDebug( int howmany ); /** * Log a message at the TRACE level, with trace disabled. */ static void logDisabledTrace( int howmany ); /** * Log a message at the DEBUG level, with debug enabled. */ static void logEnabledDebug( int howmany ); /** * Log a message at the TRACE level, with trace enabled. */ static void logEnabledTrace( int howmany ); }; #endif // LOG4CXXBENCHMARKER_H apache-log4cxx-1.3.1/src/test/cpp/throughput/CMakeLists.txt0000644000175100001770000000547214721727031023205 0ustar runnerdocker# # 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. # option(BUILD_THROUGHPUT_TESTS "Build throughput tests" OFF) if( NOT BUILD_THROUGHPUT_TESTS ) return() endif() find_package(fmt REQUIRED) add_executable(throughputtests throughput-main.cpp log4cxxbenchmarker.cpp) # Note: we need to include the APR DLLs on our path so that the tests will run. # The way that CMake sets the environment is that it actually generates a secondary file, # CTestTestfile.cmake, which sets the final properties of the test. # However, this results in a secondary quirk to the running of the tests: CMake uses # a semicolon to deliminate entries in a list! Since the Windows PATH is semicolon-delimited # as well, CMake uses only the first entry in the list when setting the path. # So, we need to do a triple escape on the PATH that we want to set in order for CMake to # properly interpret the PATH if( WIN32 ) get_filename_component(APR_DLL_DIR "${APR_DLL}" DIRECTORY) get_filename_component(APR_UTIL_DLL_DIR "${APR_UTIL_DLL}" DIRECTORY) get_filename_component(EXPAT_LIB_DIR "${EXPAT_LIBRARY}" DIRECTORY) set(EXPAT_DLL_DIR "${EXPAT_LIB_DIR}/../bin") set(LOG4CXX_DLL_DIR "$>;") set(PATH_FOR_TESTS ${CMAKE_PROGRAM_PATH};${APR_DLL_DIR};${APR_UTIL_DLL_DIR};${LOG4CXX_DLL_DIR};${EXPAT_DLL_DIR}\;) list(REMOVE_DUPLICATES PATH_FOR_TESTS) set(NORMAL_PATH $ENV{PATH}) set(ESCAPED_PATH "") foreach( ENTRY ${PATH_FOR_TESTS}${NORMAL_PATH} ) set(ESCAPED_PATH "${ESCAPED_PATH}${ENTRY}\\\;") endforeach() set_target_properties(throughputtests PROPERTIES VS_DEBUGGER_ENVIRONMENT "PATH=${ESCAPED_PATH}" ) endif( WIN32 ) target_compile_definitions(throughputtests PRIVATE ${LOG4CXX_COMPILE_DEFINITIONS} ${APR_COMPILE_DEFINITIONS} ${APR_UTIL_COMPILE_DEFINITIONS} ) target_include_directories(throughputtests PRIVATE ${CMAKE_CURRENT_LIST_DIR} $) target_link_libraries(throughputtests PRIVATE log4cxx ${APR_LIBRARIES} ${APR_SYSTEM_LIBS} Threads::Threads fmt::fmt) add_custom_target(run-throughput COMMAND throughputtests DEPENDS throughputtests) apache-log4cxx-1.3.1/src/test/cpp/throughput/throughput-main.cpp0000644000175100001770000001541314721727031024300 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #if LOG4CXX_USING_STD_FORMAT #include #else #include #include #include #endif #include "log4cxxbenchmarker.h" using log4cxx::LogString; static log4cxx::LoggerPtr console = log4cxx::Logger::getLogger( "console" ); static std::vector results; static std::mutex results_mutex; static void benchmark_function( const std::string& name, void (*fn)(int), int howmany ) { using std::chrono::duration; using std::chrono::duration_cast; using std::chrono::high_resolution_clock; auto start = high_resolution_clock::now(); fn(howmany); auto delta = high_resolution_clock::now() - start; auto delta_d = duration_cast>(delta).count(); std::lock_guard lk(results_mutex); results.push_back( uint64_t(howmany / delta_d) ); LOG4CXX_INFO_FMT( console, "Log4cxx {} Elapsed: {:.4} secs {:L}/sec", name, delta_d, results.back()); } static void benchmark_conversion_pattern( const std::string& name, const std::string& conversion_pattern, void(*fn)(const LogString&, int), int howmany) { using std::chrono::duration; using std::chrono::duration_cast; using std::chrono::high_resolution_clock; auto start = high_resolution_clock::now(); LOG4CXX_DECODE_CHAR(conversion_patternLS, conversion_pattern); fn(conversion_patternLS, howmany); auto delta = high_resolution_clock::now() - start; auto delta_d = duration_cast>(delta).count(); std::lock_guard lk(results_mutex); results.push_back( uint64_t(howmany / delta_d) ); LOG4CXX_INFO_FMT( console, "Log4cxx {} pattern: {} Elapsed: {:.4} secs {:L}/sec", name, conversion_pattern, delta_d, results.back()); } static void bench_log4cxx_single_threaded(int iters) { LOG4CXX_INFO(console, LOG4CXX_STR("**************************************************************")); LOG4CXX_INFO_FMT(console, "Benchmarking Single threaded: {} messages", iters ); LOG4CXX_INFO(console, LOG4CXX_STR("**************************************************************")); benchmark_conversion_pattern( "NoFormat", "%m%n", &log4cxxbenchmarker::logWithConversionPattern, iters ); benchmark_conversion_pattern( "DateOnly", "[%d] %m%n", &log4cxxbenchmarker::logWithConversionPattern, iters ); benchmark_conversion_pattern( "DateClassLevel", "[%d] [%c] [%p] %m%n", &log4cxxbenchmarker::logWithConversionPattern, iters ); benchmark_function( "Logging with FMT", &log4cxxbenchmarker::logWithFMT, iters ); benchmark_function( "Logging static string", &log4cxxbenchmarker::logStaticString, iters ); benchmark_function( "Logging static string with FMT", &log4cxxbenchmarker::logStaticStringFMT, iters ); benchmark_function( "Logging disabled debug", &log4cxxbenchmarker::logDisabledDebug, iters ); benchmark_function( "Logging disabled trace", &log4cxxbenchmarker::logDisabledTrace, iters ); benchmark_function( "Logging enabled debug", &log4cxxbenchmarker::logEnabledDebug, iters ); benchmark_function( "Logging enabled trace", &log4cxxbenchmarker::logEnabledTrace, iters ); } static void bench_log4cxx_multi_threaded(size_t threads, int iters) { LOG4CXX_INFO(console, LOG4CXX_STR("**************************************************************")); LOG4CXX_INFO_FMT(console, "Benchmarking multithreaded threaded: {} messages/thread, {} threads", iters, threads ); LOG4CXX_INFO(console, LOG4CXX_STR("**************************************************************")); std::vector runningThreads; auto logger = log4cxxbenchmarker::logSetupMultithreaded(); for ( size_t x = 0; x < threads; x++ ) { runningThreads.push_back( std::thread( [iters]() { benchmark_function( "Logging with FMT MT", &log4cxxbenchmarker::logWithFMTMultithreaded, iters ); }) ); } for ( std::thread& th : runningThreads ) { th.join(); } } static void bench_log4cxx_multi_threaded_disabled(size_t threads, int iters) { LOG4CXX_INFO(console, LOG4CXX_STR("**************************************************************")); LOG4CXX_INFO_FMT(console, "Benchmarking multithreaded disabled: {} messages/thread, {} threads", iters, threads ); LOG4CXX_INFO(console, LOG4CXX_STR("**************************************************************")); std::vector runningThreads; auto logger = log4cxxbenchmarker::logSetupMultithreaded(); for ( size_t x = 0; x < threads; x++ ) { runningThreads.push_back( std::thread( [iters]() { benchmark_function( "Logging disabled MT", &log4cxxbenchmarker::logDisabledMultithreaded, iters ); }) ); } for ( std::thread& th : runningThreads ) { th.join(); } } int main(int argc, char* argv[]) { int iters = 1000000; size_t threads = 4; size_t max_threads = 32; std::setlocale( LC_ALL, "" ); /* Set locale for C functions */ std::locale::global(std::locale("")); /* set locale for C++ functions */ console->setAdditivity( false ); log4cxx::PatternLayoutPtr pattern( new log4cxx::PatternLayout() ); pattern->setConversionPattern( LOG4CXX_STR("%m%n") ); log4cxx::ConsoleAppenderPtr consoleWriter( new log4cxx::ConsoleAppender ); consoleWriter->setLayout( pattern ); consoleWriter->setTarget( LOG4CXX_STR("System.out") ); log4cxx::helpers::Pool p; consoleWriter->activateOptions(p); console->addAppender( consoleWriter ); if (argc > 1) { iters = std::stoi(argv[1]); } if (argc > 2) { threads = std::stoul(argv[2]); } if (threads > max_threads) { LOG4CXX_ERROR_FMT(console, "Too many threads specified(max: {})", max_threads); return 1; } LOG4CXX_INFO_FMT(console, "Benchmarking library only(no writing out):", 0); bench_log4cxx_single_threaded(iters); bench_log4cxx_multi_threaded(threads, iters); bench_log4cxx_multi_threaded_disabled(threads, iters); LOG4CXX_INFO_FMT(console, "Results for use in spreadsheet:", 0); for ( uint64_t result : results ) { LOG4CXX_INFO_FMT(console, "{}", result ); } return 0; } apache-log4cxx-1.3.1/src/test/cpp/throughput/log4cxxbenchmarker.cpp0000644000175100001770000001373014721727031024737 0ustar runnerdocker/* * 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. */ #include "log4cxxbenchmarker.h" #include #include #include #if LOG4CXX_USING_STD_FORMAT #include #else #include #endif namespace LOG4CXX_NS { class NullWriterAppender : public log4cxx::AppenderSkeleton { public: DECLARE_LOG4CXX_OBJECT(NullWriterAppender) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(NullWriterAppender) LOG4CXX_CAST_ENTRY_CHAIN(AppenderSkeleton) END_LOG4CXX_CAST_MAP() NullWriterAppender() {} void close() override {} bool requiresLayout() const override { return true; } void append(const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& p) override { // This gets called whenever there is a valid event for our appender. } void activateOptions(log4cxx::helpers::Pool& /* pool */) override { // Given all of our options, do something useful(e.g. open a file) } void setOption(const LogString& option, const LogString& value) override { } }; IMPLEMENT_LOG4CXX_OBJECT(NullWriterAppender) LOG4CXX_PTR_DEF(NullWriterAppender); } log4cxxbenchmarker::log4cxxbenchmarker() { } log4cxx::LoggerPtr log4cxxbenchmarker::resetLogger() { log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger( LOG4CXX_STR("bench_logger") ); logger->removeAllAppenders(); logger->setAdditivity( false ); logger->setLevel( log4cxx::Level::getInfo() ); log4cxx::PatternLayoutPtr pattern = std::make_shared(); pattern->setConversionPattern( LOG4CXX_STR("%m%n") ); log4cxx::NullWriterAppenderPtr nullWriter = std::make_shared(); nullWriter->setLayout( pattern ); logger->addAppender( nullWriter ); return logger; } void log4cxxbenchmarker::logWithConversionPattern( const log4cxx::LogString& conversionPattern, int howmany ) { log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger( LOG4CXX_STR("bench_logger") ); logger->removeAllAppenders(); logger->setAdditivity( false ); logger->setLevel( log4cxx::Level::getInfo() ); log4cxx::PatternLayoutPtr pattern = std::make_shared(); pattern->setConversionPattern( conversionPattern ); log4cxx::NullWriterAppenderPtr nullWriter = std::make_shared(); nullWriter->setLayout( pattern ); logger->addAppender( nullWriter ); for ( int x = 0; x < howmany; x++ ) { LOG4CXX_INFO( logger, LOG4CXX_STR("Hello logger: msg number ") << x); } } void log4cxxbenchmarker::logWithFMT(int howmany) { log4cxx::LoggerPtr logger = resetLogger(); for ( int x = 0; x < howmany; x++ ) { LOG4CXX_INFO_FMT( logger, "Hello logger: msg number {}", x); } } log4cxx::LoggerPtr log4cxxbenchmarker::logSetupMultithreaded() { log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger( LOG4CXX_STR("bench_logger") ); logger->removeAllAppenders(); logger->setAdditivity( false ); logger->setLevel( log4cxx::Level::getInfo() ); log4cxx::PatternLayoutPtr pattern = std::make_shared(); pattern->setConversionPattern( LOG4CXX_STR("%m%n") ); log4cxx::NullWriterAppenderPtr nullWriter = std::make_shared(); nullWriter->setLayout( pattern ); logger->addAppender( nullWriter ); return logger; } void log4cxxbenchmarker::logWithFMTMultithreaded(int howmany) { log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger( LOG4CXX_STR("bench_logger") ); for ( int x = 0; x < howmany; x++ ) { LOG4CXX_INFO_FMT( logger, "Hello logger: msg number {}", x); } } void log4cxxbenchmarker::logDisabledMultithreaded( int howmany ) { log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger( LOG4CXX_STR("bench_logger") ); for ( int x = 0; x < howmany; x++ ) { LOG4CXX_TRACE( logger, LOG4CXX_STR("Hello logger! What is happening")); } } void log4cxxbenchmarker::logStaticString( int howmany ) { log4cxx::LoggerPtr logger = resetLogger(); for ( int x = 0; x < howmany; x++ ) { LOG4CXX_INFO( logger, LOG4CXX_STR("This is a static string to see what happens")); } } void log4cxxbenchmarker::logStaticStringFMT( int howmany ) { log4cxx::LoggerPtr logger = resetLogger(); for ( int x = 0; x < howmany; x++ ) { LOG4CXX_INFO_FMT( logger, "This is a static string to see what happens", 0); } } void log4cxxbenchmarker::logDisabledDebug( int howmany ) { log4cxx::LoggerPtr logger = resetLogger(); for ( int x = 0; x < howmany; x++ ) { LOG4CXX_DEBUG( logger, LOG4CXX_STR("This is a static string to see what happens")); } } void log4cxxbenchmarker::logDisabledTrace( int howmany ) { log4cxx::LoggerPtr logger = resetLogger(); for ( int x = 0; x < howmany; x++ ) { LOG4CXX_TRACE( logger, LOG4CXX_STR("This is a static string to see what happens")); } } void log4cxxbenchmarker::logEnabledDebug( int howmany ) { log4cxx::LoggerPtr logger = resetLogger(); logger->setLevel( log4cxx::Level::getDebug() ); for ( int x = 0; x < howmany; x++ ) { LOG4CXX_DEBUG( logger, LOG4CXX_STR("This is a static string to see what happens")); } } void log4cxxbenchmarker::logEnabledTrace( int howmany ) { log4cxx::LoggerPtr logger = resetLogger(); logger->setLevel( log4cxx::Level::getTrace() ); for ( int x = 0; x < howmany; x++ ) { LOG4CXX_DEBUG( logger, LOG4CXX_STR("This is a static string to see what happens")); } } apache-log4cxx-1.3.1/src/test/cpp/minimumtestcase.cpp0000644000175100001770000001311614721727031022141 0ustar runnerdocker/* * 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. */ #include "logunit.h" #include #include #include #include #include "util/compare.h" #include "util/transformer.h" #include "util/linenumberfilter.h" #include "util/controlfilter.h" #include "util/absolutedateandtimefilter.h" #include "util/threadfilter.h" #include #include #include #include #include "testchar.h" #include #include #include using namespace log4cxx; using namespace log4cxx::helpers; LOGUNIT_CLASS(MinimumTestCase) { LOGUNIT_TEST_SUITE(MinimumTestCase); LOGUNIT_TEST(simple); LOGUNIT_TEST_SUITE_END(); public: void setUp() { root = Logger::getRootLogger(); root->removeAllAppenders(); } void tearDown() { auto rep = root->getLoggerRepository(); if (rep) { rep->resetConfiguration(); } } void simple() { LayoutPtr layout = LayoutPtr(new SimpleLayout()); AppenderPtr appender = FileAppenderPtr(new FileAppender(layout, LOG4CXX_STR("output/simple"), false)); root->addAppender(appender); common(); LOGUNIT_ASSERT(Compare::compare(LOG4CXX_FILE("output/simple"), LOG4CXX_FILE("witness/simple"))); } std::string createMessage(int i, Pool & pool) { std::string msg("Message "); msg.append(pool.itoa(i)); return msg; } void common() { int i = 0; // In the lines below, the logger names are chosen as an aid in // remembering their level values. In general, the logger names // have no bearing to level values. LoggerPtr ERRlogger = Logger::getLogger(LOG4CXX_TEST_STR("ERR")); ERRlogger->setLevel(Level::getError()); LoggerPtr INF = Logger::getLogger(LOG4CXX_TEST_STR("INF")); INF->setLevel(Level::getInfo()); LoggerPtr INF_ERR = Logger::getLogger(LOG4CXX_TEST_STR("INF.ERR")); INF_ERR->setLevel(Level::getError()); LoggerPtr DEB = Logger::getLogger(LOG4CXX_TEST_STR("DEB")); DEB->setLevel(Level::getDebug()); // Note: categories with undefined level LoggerPtr INF_UNDEF = Logger::getLogger(LOG4CXX_TEST_STR("INF.UNDEF")); LoggerPtr INF_ERR_UNDEF = Logger::getLogger(LOG4CXX_TEST_STR("INF.ERR.UNDEF")); LoggerPtr UNDEF = Logger::getLogger(LOG4CXX_TEST_STR("UNDEF")); std::string msg("Message "); Pool pool; // These should all log.---------------------------- LOG4CXX_FATAL(ERRlogger, createMessage(i, pool)); i++; //0 LOG4CXX_ERROR(ERRlogger, createMessage(i, pool)); i++; LOG4CXX_FATAL(INF, createMessage(i, pool)); i++; // 2 LOG4CXX_ERROR(INF, createMessage(i, pool)); i++; LOG4CXX_WARN(INF, createMessage(i, pool)); i++; LOG4CXX_INFO(INF, createMessage(i, pool)); i++; LOG4CXX_FATAL(INF_UNDEF, createMessage(i, pool)); i++; //6 LOG4CXX_ERROR(INF_UNDEF, createMessage(i, pool)); i++; LOG4CXX_WARN(INF_UNDEF, createMessage(i, pool)); i++; LOG4CXX_INFO(INF_UNDEF, createMessage(i, pool)); i++; LOG4CXX_FATAL(INF_ERR, createMessage(i, pool)); i++; // 10 LOG4CXX_ERROR(INF_ERR, createMessage(i, pool)); i++; LOG4CXX_FATAL(INF_ERR_UNDEF, createMessage(i, pool)); i++; LOG4CXX_ERROR(INF_ERR_UNDEF, createMessage(i, pool)); i++; LOG4CXX_FATAL(DEB, createMessage(i, pool)); i++; //14 LOG4CXX_ERROR(DEB, createMessage(i, pool)); i++; LOG4CXX_WARN(DEB, createMessage(i, pool)); i++; LOG4CXX_INFO(DEB, createMessage(i, pool)); i++; LOG4CXX_DEBUG(DEB, createMessage(i, pool)); i++; // defaultLevel=DEBUG LOG4CXX_FATAL(UNDEF, createMessage(i, pool)); i++; // 19 LOG4CXX_ERROR(UNDEF, createMessage(i, pool)); i++; LOG4CXX_WARN(UNDEF, createMessage(i, pool)); i++; LOG4CXX_INFO(UNDEF, createMessage(i, pool)); i++; LOG4CXX_DEBUG(UNDEF, createMessage(i, pool)); i++; // ------------------------------------------------- // The following should not log LOG4CXX_WARN(ERRlogger, createMessage(i, pool)); i++; LOG4CXX_INFO(ERRlogger, createMessage(i, pool)); i++; LOG4CXX_DEBUG(ERRlogger, createMessage(i, pool)); i++; LOG4CXX_DEBUG(INF, createMessage(i, pool)); i++; LOG4CXX_DEBUG(INF_UNDEF, createMessage(i, pool)); i++; LOG4CXX_WARN(INF_ERR, createMessage(i, pool)); i++; LOG4CXX_INFO(INF_ERR, createMessage(i, pool)); i++; LOG4CXX_DEBUG(INF_ERR, createMessage(i, pool)); i++; LOG4CXX_WARN(INF_ERR_UNDEF, createMessage(i, pool)); i++; LOG4CXX_INFO(INF_ERR_UNDEF, createMessage(i, pool)); i++; LOG4CXX_DEBUG(INF_ERR_UNDEF, createMessage(i, pool)); i++; // ------------------------------------------------- LOG4CXX_INFO(INF, LOG4CXX_TEST_STR("Messages should bear numbers 0 through 23.")); } LoggerPtr root; LoggerPtr logger; private: static const File FILTERED; }; const File MinimumTestCase::FILTERED("output/minimumfiltered"); LOGUNIT_TEST_SUITE_REGISTRATION(MinimumTestCase); apache-log4cxx-1.3.1/src/test/cpp/util/0000755000175100001770000000000014721727031017201 5ustar runnerdockerapache-log4cxx-1.3.1/src/test/cpp/util/compare.cpp0000644000175100001770000001003214721727031021327 0ustar runnerdocker/* * 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. */ #include "compare.h" #include #include #include #include #include #include using namespace log4cxx; using namespace log4cxx::helpers; bool Compare::compare(const File& file1, const File& file2) { Pool pool; InputStreamPtr fileIn1 = InputStreamPtr( new FileInputStream(file1) ); InputStreamReaderPtr reader1 = InputStreamReaderPtr( new InputStreamReader(fileIn1) ); LogString in1(reader1->read(pool)); Pool pool2; InputStreamPtr fileIn2 = InputStreamPtr( new FileInputStream(file2) ); InputStreamReaderPtr reader2 = InputStreamReaderPtr( new InputStreamReader(fileIn2) ); LogString in2(reader2->read(pool2)); LogString back1(in1); LogString back2(in2); LogString s1; LogString s2; int lineCounter = 0; while (getline(in1, s1)) { lineCounter++; if (!getline(in2, s2)) { s2.erase(s2.begin(), s2.end()); } if (s1 != s2) { LogString msg(LOG4CXX_STR("Files [")); msg += file1.getPath(); msg += LOG4CXX_STR("] and ["); msg += file2.getPath(); msg += LOG4CXX_STR("] differ on line "); StringHelper::toString(lineCounter, pool, msg); msg += LOG4CXX_EOL; msg += LOG4CXX_STR("One reads: ["); msg += s1; msg += LOG4CXX_STR("]."); msg += LOG4CXX_EOL; msg += LOG4CXX_STR("Other reads:["); msg += s2; msg += LOG4CXX_STR("]."); msg += LOG4CXX_EOL; emit(msg); outputFile(file1, back1, pool); outputFile(file2, back2, pool); return false; } } // the second file is longer if (getline(in2, s2)) { LogString msg(LOG4CXX_STR("File [")); msg += file2.getPath(); msg += LOG4CXX_STR("] longer than file ["); msg += file1.getPath(); msg += LOG4CXX_STR("]."); msg += LOG4CXX_EOL; emit(msg); outputFile(file1, back1, pool); outputFile(file2, back2, pool); return false; } return true; } void Compare::outputFile(const File& file, const LogString& contents, log4cxx::helpers::Pool& pool) { int lineCounter = 0; emit(LOG4CXX_STR("--------------------------------")); emit(LOG4CXX_EOL); LogString msg(LOG4CXX_STR("Contents of ")); msg += file.getPath(); msg += LOG4CXX_STR(":"); msg += LOG4CXX_EOL; emit(msg); LogString in1(contents); LogString s1; while (getline(in1, s1)) { lineCounter++; LogString line; StringHelper::toString(lineCounter, pool, line); emit(line); if (lineCounter < 10) { emit(LOG4CXX_STR(" : ")); } else if (lineCounter < 100) { emit(LOG4CXX_STR(" : ")); } else if (lineCounter < 1000) { emit(LOG4CXX_STR(" : ")); } else { emit(LOG4CXX_STR(": ")); } emit(s1); emit(LOG4CXX_EOL); } } void Compare::emit(const LogString& s1) { SystemOutWriter::write(s1); } bool Compare::getline(LogString& in, LogString& line) { if (in.empty()) { return false; } size_t nl = in.find(0x0A); if (nl == std::string::npos) { line = in; in.erase(in.begin(), in.end()); } else { // // if the file has CR-LF then // drop the carriage return alse // if (nl > 0 && in[nl - 1] == 0x0D) { line.assign(in, 0, nl - 1); } else { line.assign(in, 0, nl); } in.erase(in.begin(), in.begin() + nl + 1); } return true; } apache-log4cxx-1.3.1/src/test/cpp/util/filenamefilter.cpp0000644000175100001770000000252414721727031022676 0ustar runnerdocker/* * 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. */ #include "filenamefilter.h" using namespace log4cxx; using namespace log4cxx::helpers; FilenameFilter::FilenameFilter(const std::string& actual, const std::string& expected) { std::string pattern(actual); size_t backslash = pattern.rfind('\\', pattern.length() - 1); while (backslash != std::string::npos) { pattern.replace(backslash, 1, "\\\\", 2); if (backslash == 0) { backslash = std::string::npos; } else { backslash = pattern.rfind('\\', backslash - 1); } } patterns.push_back( PatternReplacement(pattern, expected) ); } apache-log4cxx-1.3.1/src/test/cpp/util/xmlthreadfilter.h0000644000175100001770000000205714721727031022554 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_TESTS_UTIL_XML_THREAD_FILTER_H #define _LOG4CXX_TESTS_UTIL_XML_THREAD_FILTER_H #include "filter.h" namespace LOG4CXX_NS { class XMLThreadFilter : public Filter { public: XMLThreadFilter(); }; } #endif //_LOG4CXX_TESTS_UTIL_XML_THREAD_FILTER_H apache-log4cxx-1.3.1/src/test/cpp/util/binarycompare.h0000644000175100001770000000204714721727031022210 0ustar runnerdocker/* * 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. */ #include namespace LOG4CXX_NS { namespace util { class BinaryCompare { private: /** * Class can not be constructed. */ BinaryCompare(); public: static void compare(const char* filename1, const char* filename2); }; } } apache-log4cxx-1.3.1/src/test/cpp/util/transformer.h0000644000175100001770000000310614721727031021714 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_TESTS_UTIL_TRANSFORMER_H #define _LOG4CXX_TESTS_UTIL_TRANSFORMER_H #include "filter.h" #include extern "C" { struct apr_pool_t; } namespace LOG4CXX_NS { class File; class Transformer { public: static void transform(const File& in, const File& out, const std::vector& filters); static void transform(const File& in, const File& out, const Filter& filter); static void transform(const File& in, const File& out, const std::vector< log4cxx::Filter::PatternReplacement >& patterns); private: static void copyFile(const File& in, const File& out); static void createSedCommandFile(const std::string& regexName, const log4cxx::Filter::PatternList& patterns, apr_pool_t* pool); }; } #endif //_LOG4CXX_TESTS_UTIL_TRANSFORMER_H apache-log4cxx-1.3.1/src/test/cpp/util/threadfilter.cpp0000644000175100001770000000170614721727031022366 0ustar runnerdocker/* * 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. */ #include "threadfilter.h" using namespace log4cxx; using namespace log4cxx::helpers; ThreadFilter::ThreadFilter() : Filter("\\[[0-9A-Fa-fXx]*]", "\\[main]") {} apache-log4cxx-1.3.1/src/test/cpp/util/absolutedateandtimefilter.cpp0000644000175100001770000000175414721727031025140 0ustar runnerdocker/* * 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. */ #include "absolutedateandtimefilter.h" using namespace log4cxx; using namespace log4cxx::helpers; AbsoluteDateAndTimeFilter::AbsoluteDateAndTimeFilter() : Filter(ABSOLUTE_DATE_AND_TIME_PAT, "") {} apache-log4cxx-1.3.1/src/test/cpp/util/iso8601filter.cpp0000644000175100001770000000167014721727031022230 0ustar runnerdocker/* * 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. */ #include "iso8601filter.h" using namespace log4cxx; using namespace log4cxx::helpers; ISO8601Filter::ISO8601Filter() : Filter(ISO8601_PAT, "") {} apache-log4cxx-1.3.1/src/test/cpp/util/absolutetimefilter.h0000644000175100001770000000205714721727031023261 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_TESTS_UTIL_ABS_TIME_FILTER_H #define _LOG4CXX_TESTS_UTIL_ABS_TIME_FILTER_H #include "filter.h" namespace LOG4CXX_NS { class AbsoluteTimeFilter : public Filter { public: AbsoluteTimeFilter(); }; } #endif //_LOG4CXX_TESTS_UTIL_ABS_TIME_FILTER_H apache-log4cxx-1.3.1/src/test/cpp/util/linenumberfilter.h0000644000175100001770000000206414721727031022722 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_TESTS_UTIL_LINE_NUMBER_FILTER_H #define _LOG4CXX_TESTS_UTIL_LINE_NUMBER_FILTER_H #include "filter.h" namespace LOG4CXX_NS { class LineNumberFilter : public Filter { public: LineNumberFilter(); }; } #endif //_LOG4CXX_TESTS_UTIL_LINE_NUMBER_FILTER_H apache-log4cxx-1.3.1/src/test/cpp/util/xmlfilenamefilter.cpp0000644000175100001770000000225714721727031023422 0ustar runnerdocker/* * 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. */ #include "xmlfilenamefilter.h" using namespace log4cxx; using namespace log4cxx::helpers; XMLFilenameFilter::XMLFilenameFilter(const std::string& /*actual*/, const std::string& expected) { std::string pattern(" file=\\(.\\).*"); pattern += expected; std::string replacement(" file=\\\\1"); replacement += expected; // patterns.push_back( PatternReplacement(pattern, replacement) ); } apache-log4cxx-1.3.1/src/test/cpp/util/iso8601filter.h0000644000175100001770000000204514721727031021672 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_TESTS_UTIL_ISO_8601_FILTER_H #define _LOG4CXX_TESTS_UTIL_ISO_8601_FILTER_H #include "filter.h" namespace LOG4CXX_NS { class ISO8601Filter : public Filter { public: ISO8601Filter(); }; } #endif //_LOG4CXX_TESTS_UTIL_ISO_8601_FILTER_H apache-log4cxx-1.3.1/src/test/cpp/util/xmlfilenamefilter.h0000644000175100001770000000215714721727031023066 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_TESTS_UTIL_XML_FILENAME_FILTER_H #define _LOG4CXX_TESTS_UTIL_XML_FILENAME_FILTER_H #include "filter.h" namespace LOG4CXX_NS { class XMLFilenameFilter : public Filter { public: XMLFilenameFilter(const std::string& actual, const std::string& expected); }; } #endif //_LOG4CXX_TESTS_UTIL_XML_FILENAME_FILTER_H apache-log4cxx-1.3.1/src/test/cpp/util/filenamefilter.h0000644000175100001770000000223514721727031022342 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_TESTS_UTIL_FILENAME_FILTER_H #define _LOG4CXX_TESTS_UTIL_FILENAME_FILTER_H #include "filter.h" namespace LOG4CXX_NS { class FilenameFilter : public Filter { public: FilenameFilter(const std::string& actual, const std::string& expected); static const std::string getMatch(const std::string& actual); }; } #endif //_LOG4CXX_TESTS_UTIL_FILENAME_FILTER_H apache-log4cxx-1.3.1/src/test/cpp/util/xmltimestampfilter.h0000644000175100001770000000207614721727031023311 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_TESTS_UTIL_XML_TIMESTAMP_FILTER_H #define _LOG4CXX_TESTS_UTIL_XML_TIMESTAMP_FILTER_H #include "filter.h" namespace LOG4CXX_NS { class XMLTimestampFilter : public Filter { public: XMLTimestampFilter(); }; } #endif //_LOG4CXX_TESTS_UTIL_XML_TIMESTAMP_FILTER_H apache-log4cxx-1.3.1/src/test/cpp/util/utilfilter.cpp0000644000175100001770000000212414721727031022067 0ustar runnerdocker/* * 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. */ #include "filter.h" #include using namespace log4cxx; using namespace log4cxx::helpers; Filter::Filter() {} Filter::Filter(const std::string& match, const std::string& replacement) { patterns.push_back( PatternReplacement(match, replacement)); } Filter::~Filter() {} apache-log4cxx-1.3.1/src/test/cpp/util/binarycompare.cpp0000644000175100001770000000505614721727031022546 0ustar runnerdocker/* * 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. */ #include "binarycompare.h" #include #include #include "../logunit.h" #include #include using namespace log4cxx; using namespace log4cxx::util; using namespace log4cxx::helpers; void BinaryCompare::compare(const char* filename1, const char* filename2) { Pool p; apr_pool_t* pool = p.getAPRPool(); apr_file_t* file1; apr_int32_t flags = APR_FOPEN_READ; apr_fileperms_t perm = APR_OS_DEFAULT; apr_status_t stat1 = apr_file_open(&file1, filename1, flags, perm, pool); if (stat1 != APR_SUCCESS) { LOGUNIT_FAIL(std::string("Unable to open ") + filename1); } apr_file_t* file2; apr_status_t stat2 = apr_file_open(&file2, filename2, flags, perm, pool); if (stat2 != APR_SUCCESS) { LOGUNIT_FAIL(std::string("Unable to open ") + filename2); } enum { BUFSIZE = 1024 }; char* contents1 = (char*) apr_palloc(pool, BUFSIZE); char* contents2 = (char*) apr_palloc(pool, BUFSIZE); memset(contents1, 0, BUFSIZE); memset(contents2, 0, BUFSIZE); apr_size_t bytesRead1 = BUFSIZE; apr_size_t bytesRead2 = BUFSIZE; stat1 = apr_file_read(file1, contents1, &bytesRead1); if (stat1 != APR_SUCCESS) { LOGUNIT_FAIL(std::string("Unable to read ") + filename1); } stat2 = apr_file_read(file2, contents2, &bytesRead2); if (stat2 != APR_SUCCESS) { LOGUNIT_FAIL(std::string("Unable to read ") + filename2); } for (int i = 0; i < BUFSIZE; i++) { if (contents1[i] != contents2[i]) { std::string msg("Contents differ at position "); msg += apr_itoa(pool, i); msg += ": ["; msg += filename1; msg += "] has "; msg += apr_itoa(pool, contents1[i]); msg += ", ["; msg += filename2; msg += "] has "; msg += apr_itoa(pool, contents2[i]); msg += "."; LOGUNIT_FAIL(msg); } } } apache-log4cxx-1.3.1/src/test/cpp/util/controlfilter.cpp0000644000175100001770000000176014721727031022577 0ustar runnerdocker/* * 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. */ #include "controlfilter.h" using namespace log4cxx; using namespace log4cxx::helpers; ControlFilter::ControlFilter() { } ControlFilter& ControlFilter::operator<<(const std::string&) { return *this; } apache-log4cxx-1.3.1/src/test/cpp/util/xmllineattributefilter.cpp0000644000175100001770000000201214721727031024502 0ustar runnerdocker/* * 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. */ #include "xmllineattributefilter.h" using namespace log4cxx; using namespace log4cxx::helpers; XMLLineAttributeFilter::XMLLineAttributeFilter() { patterns.push_back( PatternReplacement("line=\\(.+\\)[0-9]+", "line=\\\\1X")); } apache-log4cxx-1.3.1/src/test/cpp/util/transformer.cpp0000644000175100001770000001437114721727031022255 0ustar runnerdocker/* * 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. */ #include "transformer.h" #include #include #include #include #include #include #include #include using namespace log4cxx; using namespace log4cxx::helpers; #if !defined(APR_FOPEN_READ) #define APR_FOPEN_READ APR_READ #define APR_FOPEN_CREATE APR_CREATE #define APR_FOPEN_WRITE APR_WRITE #define APR_FOPEN_TRUNCATE APR_TRUNCATE #define APR_FOPEN_APPEND APR_APPEND #endif void Transformer::transform(const File& in, const File& out, const std::vector& filters) { log4cxx::Filter::PatternList patterns; for (std::vector::const_iterator iter = filters.begin(); iter != filters.end(); iter++) { const log4cxx::Filter::PatternList& thesePatterns = (*iter)->getPatterns(); for (log4cxx::Filter::PatternList::const_iterator pattern = thesePatterns.begin(); pattern != thesePatterns.end(); pattern++) { patterns.push_back(*pattern); } } transform(in, out, patterns); } void Transformer::transform(const File& in, const File& out, const Filter& filter) { transform(in, out, filter.getPatterns()); } void Transformer::copyFile(const File& in, const File& out) { Pool p; apr_pool_t* pool = p.getAPRPool(); // // fairly naive file copy code // // apr_file_t* child_out; apr_int32_t flags = APR_FOPEN_WRITE | APR_FOPEN_CREATE | APR_FOPEN_TRUNCATE; apr_status_t stat = out.open(&child_out, flags, APR_OS_DEFAULT, p); assert(stat == APR_SUCCESS); apr_file_t* in_file; stat = in.open(&in_file, APR_FOPEN_READ, APR_OS_DEFAULT, p); assert(stat == APR_SUCCESS); apr_size_t bufsize = 32000; void* buf = apr_palloc(pool, bufsize); apr_size_t bytesRead = bufsize; while (stat == 0 && bytesRead == bufsize) { stat = apr_file_read(in_file, buf, &bytesRead); if (stat == 0 && bytesRead > 0) { stat = apr_file_write(child_out, buf, &bytesRead); assert(stat == APR_SUCCESS); } } stat = apr_file_close(child_out); assert(stat == APR_SUCCESS); } void Transformer::createSedCommandFile(const std::string& regexName, const log4cxx::Filter::PatternList& patterns, apr_pool_t* pool) { apr_file_t* regexFile; apr_status_t stat = apr_file_open(®exFile, regexName.c_str(), APR_FOPEN_WRITE | APR_FOPEN_CREATE | APR_FOPEN_TRUNCATE, APR_OS_DEFAULT, pool); assert(stat == APR_SUCCESS); std::string tmp; auto sedSanitizer = [] (const std::string& in, const std::string& sedSeparator = "Q") { std::string ret = in; std::string replaceTo = "\\" + sedSeparator; size_t pos = 0; while((pos = ret.find(sedSeparator, pos)) != std::string::npos) { ret.replace(pos, sedSeparator.length(), replaceTo); pos += replaceTo.length(); } return ret; }; for (log4cxx::Filter::PatternList::const_iterator iter = patterns.begin(); iter != patterns.end(); iter++) { tmp = "sQ"; tmp.append(sedSanitizer(iter->first)); tmp.append(1, 'Q'); tmp.append(sedSanitizer(iter->second)); tmp.append("Qg\n"); apr_file_puts(tmp.c_str(), regexFile); } apr_file_close(regexFile); } void Transformer::transform(const File& in, const File& out, const log4cxx::Filter::PatternList& patterns) { // // if no patterns just copy the file // if (patterns.size() == 0) { copyFile(in, out); } else { Pool p; apr_pool_t* pool = p.getAPRPool(); // // write the regex's to a temporary file since they // may get mangled if passed as parameters // std::string regexName; Transcoder::encode(in.getPath(), regexName); regexName.append(".sed"); createSedCommandFile(regexName, patterns, pool); // // prepare to launch sed // // apr_procattr_t* attr = NULL; apr_status_t stat = apr_procattr_create(&attr, pool); assert(stat == APR_SUCCESS); stat = apr_procattr_io_set(attr, APR_NO_PIPE, APR_FULL_BLOCK, APR_FULL_BLOCK); assert(stat == APR_SUCCESS); // // find the program on the path // stat = apr_procattr_cmdtype_set(attr, APR_PROGRAM_PATH); assert(stat == APR_SUCCESS); // // build the argument list // using Q as regex separator on s command // const char** args = (const char**) apr_palloc(pool, 5 * sizeof(*args)); int i = 0; // // not well documented // but the first arg is a duplicate of the executable name // args[i++] = "sed"; std::string regexArg("-f"); regexArg.append(regexName); args[i++] = apr_pstrdup(pool, regexArg.c_str()); // // specify the input file args[i++] = Transcoder::encode(in.getPath(), p); args[i] = NULL; // // set the output stream to the filtered file // apr_file_t* child_out; apr_int32_t flags = APR_FOPEN_READ | APR_FOPEN_WRITE | APR_FOPEN_CREATE | APR_FOPEN_TRUNCATE; stat = out.open(&child_out, flags, APR_OS_DEFAULT, p); assert(stat == APR_SUCCESS); stat = apr_procattr_child_out_set(attr, child_out, NULL); assert(stat == APR_SUCCESS); // // redirect the child's error stream to this processes' error stream // apr_file_t* child_err; stat = apr_file_open_stderr(&child_err, pool); assert(stat == 0); stat = apr_procattr_child_err_set(attr, child_err, NULL); assert(stat == APR_SUCCESS); apr_proc_t pid; stat = apr_proc_create(&pid, "sed", args, NULL, attr, pool); if (stat != APR_SUCCESS) { puts("Error invoking sed, sed must be on the path in order to run unit tests"); } assert(stat == APR_SUCCESS); apr_proc_wait(&pid, NULL, NULL, APR_WAIT); stat = apr_file_close(child_out); assert(stat == APR_SUCCESS); } } apache-log4cxx-1.3.1/src/test/cpp/util/xmllineattributefilter.h0000644000175100001770000000212514721727031024154 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_TESTS_UTIL_XML_LINE_ATTRIBUTE_FILTER_H #define _LOG4CXX_TESTS_UTIL_XML_LINE_ATTRIBUTE_FILTER_H #include "filter.h" namespace LOG4CXX_NS { class XMLLineAttributeFilter : public Filter { public: XMLLineAttributeFilter(); }; } #endif //_LOG4CXX_TESTS_UTIL_XML_LINE_ATTRIBUTE_FILTER_H apache-log4cxx-1.3.1/src/test/cpp/util/compare.h0000644000175100001770000000234514721727031021004 0ustar runnerdocker/* * 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. */ #include namespace LOG4CXX_NS { class File; namespace helpers { class Pool; } class Compare { public: static bool compare(const File& file1, const File& file2); private: /// Prints file on the console. static void outputFile(const File& file, const LogString& contents, log4cxx::helpers::Pool& pool); static void emit(const LogString& line); static bool getline(LogString& buf, LogString& line); }; } apache-log4cxx-1.3.1/src/test/cpp/util/CMakeLists.txt0000644000175100001770000000275514721727031021752 0ustar runnerdocker# # 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. # # Components required by all tests add_library(testingUtilities STATIC absolutedateandtimefilter.cpp absolutetimefilter.cpp binarycompare.cpp compare.cpp controlfilter.cpp filenamefilter.cpp iso8601filter.cpp linenumberfilter.cpp relativetimefilter.cpp threadfilter.cpp transformer.cpp utilfilter.cpp xmlfilenamefilter.cpp xmllineattributefilter.cpp xmlthreadfilter.cpp xmltimestampfilter.cpp ) target_compile_definitions(testingUtilities PRIVATE ${LOG4CXX_COMPILE_DEFINITIONS} ${APR_COMPILE_DEFINITIONS} ${APR_UTIL_COMPILE_DEFINITIONS} ) target_include_directories(testingUtilities PRIVATE ${CMAKE_CURRENT_LIST_DIR} $) apache-log4cxx-1.3.1/src/test/cpp/util/relativetimefilter.h0000644000175100001770000000205714721727031023256 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_TESTS_UTIL_REL_TIME_FILTER_H #define _LOG4CXX_TESTS_UTIL_REL_TIME_FILTER_H #include "filter.h" namespace LOG4CXX_NS { class RelativeTimeFilter : public Filter { public: RelativeTimeFilter(); }; } #endif //_LOG4CXX_TESTS_UTIL_REL_TIME_FILTER_H apache-log4cxx-1.3.1/src/test/cpp/util/absolutedateandtimefilter.h0000644000175100001770000000211414721727031024574 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_TESTS_UTIL_ABS_DATE_TIME_FILTER_H #define _LOG4CXX_TESTS_UTIL_ABS_DATE_TIME_FILTER_H #include "filter.h" namespace LOG4CXX_NS { class AbsoluteDateAndTimeFilter : public Filter { public: AbsoluteDateAndTimeFilter(); }; } #endif //_LOG4CXX_TESTS_UTIL_ABS_DATE_TIME_FILTER_H apache-log4cxx-1.3.1/src/test/cpp/util/threadfilter.h0000644000175100001770000000203514721727031022027 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_TESTS_UTIL_THREAD_FILTER_H #define _LOG4CXX_TESTS_UTIL_THREAD_FILTER_H #include "filter.h" namespace LOG4CXX_NS { class ThreadFilter : public Filter { public: ThreadFilter(); }; } #endif //_LOG4CXX_TESTS_UTIL_THREAD_FILTER_H apache-log4cxx-1.3.1/src/test/cpp/util/xmlthreadfilter.cpp0000644000175100001770000000173714721727031023113 0ustar runnerdocker/* * 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. */ #include "xmlthreadfilter.h" using namespace log4cxx; using namespace log4cxx::helpers; XMLThreadFilter::XMLThreadFilter() : Filter("thread=\\\"[0-9A-Fa-fXx]*", "thread=\\\"main") { } apache-log4cxx-1.3.1/src/test/cpp/util/controlfilter.h0000644000175100001770000000216514721727031022244 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_TESTS_UTIL_CONTROL_FILTER_H #define _LOG4CXX_TESTS_UTIL_CONTROL_FILTER_H #include "filter.h" #include namespace LOG4CXX_NS { class ControlFilter : public Filter { public: ControlFilter(); ControlFilter& operator<<(const std::string& allowedPattern); }; } #endif //_LOG4CXX_TESTS_UTIL_CONTROL_FILTER_H apache-log4cxx-1.3.1/src/test/cpp/util/linenumberfilter.cpp0000644000175100001770000000204414721727031023253 0ustar runnerdocker/* * 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. */ #include "linenumberfilter.h" using namespace log4cxx; using namespace log4cxx::helpers; LineNumberFilter::LineNumberFilter() { patterns.push_back( PatternReplacement(" [^ ]*[\\\\]", " ")); patterns.push_back( PatternReplacement("([0-9]*)", "(X)")); } apache-log4cxx-1.3.1/src/test/cpp/util/xmltimestampfilter.cpp0000644000175100001770000000176714721727031023652 0ustar runnerdocker/* * 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. */ #include "xmltimestampfilter.h" using namespace log4cxx; using namespace log4cxx::helpers; XMLTimestampFilter::XMLTimestampFilter() : Filter("[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]*", "XXX") {} apache-log4cxx-1.3.1/src/test/cpp/util/filter.h0000644000175100001770000000363114721727031020642 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_TESTS_UTIL_FILTER_H #define _LOG4CXX_TESTS_UTIL_FILTER_H #include #include #include #include #define BASIC_PAT "\\[0x[0-9A-F]*] (FATAL|ERROR|WARN|INFO|DEBUG)" #define ISO8601_PAT "[0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [0-9]\\{2\\}:[0-9]\\{2\\}:[0-9]\\{2\\},[0-9]\\{3\\}" #define ABSOLUTE_DATE_AND_TIME_PAT \ "[0-9]\\{1,2\\} .* 2[0-9][0-9][0-9] [0-9]\\{2\\}:[0-9]\\{2\\}:[0-9]\\{2\\},[0-9]\\{3\\}" #define ABSOLUTE_TIME_PAT "[0-2][0-9]:[0-9][0-9]:[0-9][0-9],[0-9][0-9][0-9]" #define RELATIVE_TIME_PAT "^[0-9]+" namespace LOG4CXX_NS { class UnexpectedFormatException : public std::exception { }; class Filter { public: Filter(const std::string& match, const std::string& replacement); Filter(); virtual ~Filter(); typedef std::pair PatternReplacement; typedef std::vector PatternList; const PatternList& getPatterns() const { return patterns; } private: Filter(const Filter&); Filter& operator=(const Filter&); protected: PatternList patterns; }; } #endif //_LOG4CXX_TESTS_UTIL_FILTER_H apache-log4cxx-1.3.1/src/test/cpp/util/absolutetimefilter.cpp0000644000175100001770000000171614721727031023615 0ustar runnerdocker/* * 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. */ #include "absolutetimefilter.h" using namespace log4cxx; using namespace log4cxx::helpers; AbsoluteTimeFilter::AbsoluteTimeFilter() : Filter(ABSOLUTE_TIME_PAT, "") {} apache-log4cxx-1.3.1/src/test/cpp/util/relativetimefilter.cpp0000644000175100001770000000171614721727031023612 0ustar runnerdocker/* * 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. */ #include "relativetimefilter.h" using namespace log4cxx; using namespace log4cxx::helpers; RelativeTimeFilter::RelativeTimeFilter() : Filter(RELATIVE_TIME_PAT, "") {} apache-log4cxx-1.3.1/src/test/cpp/ndctestcase.cpp0000644000175100001770000000534714721727031021241 0ustar runnerdocker /* * 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. */ #include #include #include #include #include "insertwide.h" #include "logunit.h" #include "util/compare.h" static log4cxx::NDC ndc("ndctest"); using namespace log4cxx; LOGUNIT_CLASS(NDCTestCase) { static File TEMP; static LoggerPtr logger; LOGUNIT_TEST_SUITE(NDCTestCase); LOGUNIT_TEST(testPushPop); LOGUNIT_TEST(test1); LOGUNIT_TEST(testInherit); LOGUNIT_TEST_SUITE_END(); public: void setUp() { } void tearDown() { auto rep = logger->getLoggerRepository(); if (rep) { rep->resetConfiguration(); } } /** * Push and pop a value from the NDC */ void testPushPop() { NDC::push("trivial context"); LogString actual(NDC::pop()); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("trivial context"), actual); } void test1() { PropertyConfigurator::configure(File("input/ndc/NDC1.properties")); common(); LOGUNIT_ASSERT(Compare::compare(TEMP, File("witness/ndc/NDC.1"))); } static void common() { commonLog(); NDC::push("n1"); commonLog(); NDC::push("n2"); NDC::push("n3"); commonLog(); NDC::pop(); commonLog(); NDC::clear(); commonLog(); } static void commonLog() { LOG4CXX_DEBUG(logger, "m1"); LOG4CXX_INFO(logger, "m2"); LOG4CXX_WARN(logger, "m3"); LOG4CXX_ERROR(logger, "m4"); LOG4CXX_FATAL(logger, "m5"); } void testInherit() { NDC::push("hello"); NDC::push("world"); NDC::Stack* clone = NDC::cloneStack(); NDC::clear(); NDC::push("discard"); NDC::inherit(clone); LogString expected1(LOG4CXX_STR("world")); LOGUNIT_ASSERT_EQUAL(expected1, NDC::pop()); LogString expected2(LOG4CXX_STR("hello")); LOGUNIT_ASSERT_EQUAL(expected2, NDC::pop()); LogString expected3; LOGUNIT_ASSERT_EQUAL(expected3, NDC::pop()); } }; File NDCTestCase::TEMP("output/ndc"); LoggerPtr NDCTestCase::logger(Logger::getLogger("org.apache.log4j.NDCTestCase")); LOGUNIT_TEST_SUITE_REGISTRATION(NDCTestCase); apache-log4cxx-1.3.1/src/test/cpp/terminationtestcase.cpp0000644000175100001770000000417714721727031023026 0ustar runnerdocker/* * 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. */ #include "logunit.h" #include #include #include "vectorappender.h" #include #include using namespace log4cxx; static VectorAppenderPtr vectorAppender = std::make_shared(); LOGUNIT_CLASS(TerminationTestCase) { LOGUNIT_TEST_SUITE(TerminationTestCase); LOGUNIT_TEST(logOnce); LOGUNIT_TEST_SUITE_END(); public: static void setDefaultAppender() { auto r = LogManager::getLoggerRepository(); r->ensureIsConfigured([r]() { auto asyncAppender = std::make_shared(); asyncAppender->addAppender(vectorAppender); r->getRootLogger()->addAppender(asyncAppender); } ); } static LoggerPtr getLogger(const LogString& name = LogString()) { static struct initializer { initializer() { setDefaultAppender(); } #if !LOG4CXX_EVENTS_AT_EXIT ~initializer() { LogManager::shutdown(); } #endif } x; auto r = LogManager::getLoggerRepository(); return name.empty() ? r->getLogger(name) : r->getRootLogger(); } void logOnce() { auto root = getLogger(); LOG4CXX_INFO(root, "Message"); std::this_thread::sleep_for( std::chrono::milliseconds( 30 ) ); const std::vector& v = vectorAppender->getVector(); LOGUNIT_ASSERT_EQUAL((size_t) 1, v.size()); } }; LOGUNIT_TEST_SUITE_REGISTRATION(TerminationTestCase); apache-log4cxx-1.3.1/src/test/cpp/fmttest.cpp0000644000175100001770000001367714721727031020434 0ustar runnerdocker/* * 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. */ #include "logunit.h" #include "testchar.h" #include "util/compare.h" #include "util/transformer.h" #include "util/absolutedateandtimefilter.h" #include "util/iso8601filter.h" #include "util/absolutetimefilter.h" #include "util/relativetimefilter.h" #include "util/controlfilter.h" #include "util/threadfilter.h" #include "util/linenumberfilter.h" #include "util/filenamefilter.h" #include "vectorappender.h" #include #include #include #include #include #include #define REGEX_STR(x) x #define PAT0 REGEX_STR("\\[[0-9A-FXx]*]\\ (DEBUG|INFO|WARN|ERROR|FATAL) .* - Message [0-9]\\{1,2\\}") #define PAT1 ISO8601_PAT REGEX_STR(" ") PAT0 #define PAT2 ABSOLUTE_DATE_AND_TIME_PAT REGEX_STR(" ") PAT0 #define PAT3 ABSOLUTE_TIME_PAT REGEX_STR(" ") PAT0 #define PAT4 RELATIVE_TIME_PAT REGEX_STR(" ") PAT0 #define PAT5 REGEX_STR("\\[[0-9A-FXx]*]\\ (DEBUG|INFO|WARN|ERROR|FATAL) .* : Message [0-9]\\{1,2\\}") #define PAT6 REGEX_STR("\\[[0-9A-FXx]*]\\ (DEBUG|INFO |WARN |ERROR|FATAL) .*patternlayouttest.cpp\\([0-9]\\{1,4\\}\\): Message [0-9]\\{1,3\\}") #define PAT11a REGEX_STR("^(DEBUG|INFO |WARN |ERROR|FATAL) \\[[0-9A-FXx]*]\\ log4j.PatternLayoutTest: Message [0-9]\\{1,2\\}") #define PAT11b REGEX_STR("^(DEBUG|INFO |WARN |ERROR|FATAL) \\[[0-9A-FXx]*]\\ root: Message [0-9]\\{1,2\\}") #define PAT12 REGEX_STR("^\\[[0-9A-FXx]*]\\ (DEBUG|INFO |WARN |ERROR|FATAL) ")\ REGEX_STR(".*patternlayouttest.cpp([0-9]\\{1,4\\}): ")\ REGEX_STR("Message [0-9]\\{1,2\\}") #define PAT_MDC_1 REGEX_STR("") using namespace log4cxx; using namespace log4cxx::helpers; LOGUNIT_CLASS(FMTTestCase) { LOGUNIT_TEST_SUITE(FMTTestCase); LOGUNIT_TEST(test1); LOGUNIT_TEST(test1_expanded); LOGUNIT_TEST(test10); // LOGUNIT_TEST(test_date); LOGUNIT_TEST_SUITE_END(); LoggerPtr root; LoggerPtr logger; public: void setUp() { root = Logger::getRootLogger(); MDC::clear(); logger = Logger::getLogger(LOG4CXX_TEST_STR("java.org.apache.log4j.PatternLayoutTest")); } void tearDown() { MDC::clear(); auto rep = root->getLoggerRepository(); if (rep) { rep->resetConfiguration(); } } void test1() { PropertyConfigurator::configure(LOG4CXX_FILE("input/fmtLayout1.properties")); common(); LOGUNIT_ASSERT(Compare::compare(TEMP, LOG4CXX_FILE("witness/patternLayout.1"))); } void test1_expanded() { PropertyConfigurator::configure(LOG4CXX_FILE("input/fmtLayout1_expanded.properties")); common(); LOGUNIT_ASSERT(Compare::compare(TEMP, LOG4CXX_FILE("witness/patternLayout.1"))); } void test10() { PropertyConfigurator::configure(LOG4CXX_FILE("input/fmtLayout10.properties")); common(); ControlFilter filter1; filter1 << PAT6; ThreadFilter filter2; LineNumberFilter filter3; FilenameFilter filenameFilter(__FILE__, "patternlayouttest.cpp"); std::vector filters; filters.push_back(&filenameFilter); filters.push_back(&filter1); filters.push_back(&filter2); filters.push_back(&filter3); try { Transformer::transform(TEMP, FILTERED, filters); } catch (UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/patternLayout.10"))); } void test_date(){ std::tm tm = {}; std::stringstream ss("2013-04-11 08:35:34"); ss >> std::get_time(&tm, "%Y-%m-%d %H:%M:%S"); auto tp = std::chrono::system_clock::from_time_t(std::mktime(&tm)); uint64_t micros = std::chrono::duration_cast(tp.time_since_epoch()).count(); log4cxx::helpers::Date::setGetCurrentTimeFunction([micros](){ return micros; }); log4cxx::spi::LoggingEventPtr logEvt = std::make_shared(LOG4CXX_STR("foo"), Level::getInfo(), LOG4CXX_STR("A Message"), log4cxx::spi::LocationInfo::getLocationUnavailable()); FMTLayout layout(LOG4CXX_STR("{d:%Y-%m-%d %H:%M:%S} {message}")); LogString output; log4cxx::helpers::Pool pool; layout.format( output, logEvt, pool); log4cxx::helpers::Date::setGetCurrentTimeFunction(nullptr); LOGUNIT_ASSERT_EQUAL(LOG4CXX_STR("2013-04-11 09:35:34 A Message"), output); } std::string createMessage(Pool & pool, int i) { std::string msg("Message "); msg.append(pool.itoa(i)); return msg; } void common() { int i = -1; Pool pool; LOG4CXX_DEBUG(logger, createMessage(pool, ++i)); LOG4CXX_DEBUG(root, createMessage(pool, i)); LOG4CXX_INFO(logger, createMessage(pool, ++i)); LOG4CXX_INFO(root, createMessage(pool, i)); LOG4CXX_WARN(logger, createMessage(pool, ++i)); LOG4CXX_WARN(root, createMessage(pool, i)); LOG4CXX_ERROR(logger, createMessage(pool, ++i)); LOG4CXX_ERROR(root, createMessage(pool, i)); LOG4CXX_FATAL(logger, createMessage(pool, ++i)); LOG4CXX_FATAL(root, createMessage(pool, i)); } private: static const LogString FILTERED; static const LogString TEMP; }; const LogString FMTTestCase::TEMP(LOG4CXX_STR("output/fmtlayout")); const LogString FMTTestCase::FILTERED(LOG4CXX_STR("output/fmtlayoutfiltered")); LOGUNIT_TEST_SUITE_REGISTRATION(FMTTestCase); apache-log4cxx-1.3.1/src/test/cpp/streamtestcase.cpp0000644000175100001770000005235514721727031021771 0ustar runnerdocker/* * 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. */ #include /* Prevent error C2491: 'std::numpunct<_Elem>::id': definition of dllimport static data member not allowed */ #if defined(_MSC_VER) && LOG4CXX_UNICHAR_API #define __FORCE_INSTANCE #endif #include #include #include "vectorappender.h" #include #include #include #include "insertwide.h" #include "logunit.h" #include #include #if LOG4CXX_CFSTRING_API #include #endif using namespace log4cxx; using namespace log4cxx::helpers; using namespace std; class ExceptionOnInsert { public: ExceptionOnInsert() { } }; // // define an insertion operation that will throw an // exception to test that evaluation was short // circuited // template ::std::basic_ostream& operator<<( ::std::basic_ostream&, const ExceptionOnInsert&) { throw std::exception(); } /** Unit tests for the optional stream-like interface for log4cxx */ LOGUNIT_CLASS(StreamTestCase) { LOGUNIT_TEST_SUITE(StreamTestCase); LOGUNIT_TEST(testSimple); LOGUNIT_TEST(testMultiple); LOGUNIT_TEST(testShortCircuit); LOGUNIT_TEST_EXCEPTION(testInsertException, std::exception); LOGUNIT_TEST(testScientific); LOGUNIT_TEST(testPrecision); LOGUNIT_TEST(testWidth); #if LOG4CXX_WCHAR_T_API LOGUNIT_TEST(testWide); LOGUNIT_TEST(testWideAppend); LOGUNIT_TEST(testWideWidth); #endif LOGUNIT_TEST(testBaseFlags); LOGUNIT_TEST(testBasePrecisionAndWidth); LOGUNIT_TEST(testLogStreamSimple); LOGUNIT_TEST(testLogStreamMultiple); LOGUNIT_TEST(testLogStreamShortCircuit); LOGUNIT_TEST_EXCEPTION(testLogStreamInsertException, std::exception); LOGUNIT_TEST(testLogStreamScientific); LOGUNIT_TEST(testLogStreamPrecision); LOGUNIT_TEST(testLogStreamWidth); LOGUNIT_TEST(testLogStreamDelegate); LOGUNIT_TEST(testLogStreamFormattingPersists); LOGUNIT_TEST(testSetWidthInsert); #if LOG4CXX_WCHAR_T_API LOGUNIT_TEST(testWLogStreamSimple); LOGUNIT_TEST(testWLogStreamMultiple); LOGUNIT_TEST(testWLogStreamShortCircuit); LOGUNIT_TEST_EXCEPTION(testWLogStreamInsertException, std::exception); LOGUNIT_TEST(testWLogStreamScientific); LOGUNIT_TEST(testWLogStreamPrecision); LOGUNIT_TEST(testWLogStreamWidth); LOGUNIT_TEST(testWLogStreamDelegate); LOGUNIT_TEST(testWLogStreamFormattingPersists); LOGUNIT_TEST(testWSetWidthInsert); #endif #if LOG4CXX_UNICHAR_API LOGUNIT_TEST(testUniChar); LOGUNIT_TEST(testUniCharAppend); // LOGUNIT_TEST(testUniCharWidth); LOGUNIT_TEST(testULogStreamSimple); LOGUNIT_TEST(testULogStreamMultiple); LOGUNIT_TEST(testULogStreamShortCircuit); LOGUNIT_TEST_EXCEPTION(testULogStreamInsertException, std::exception); // LOGUNIT_TEST(testULogStreamScientific); // LOGUNIT_TEST(testULogStreamPrecision); // LOGUNIT_TEST(testULogStreamWidth); LOGUNIT_TEST(testULogStreamDelegate); // LOGUNIT_TEST(testULogStreamFormattingPersists); // LOGUNIT_TEST(testUSetWidthInsert); #endif #if LOG4CXX_CFSTRING_API LOGUNIT_TEST(testCFString); LOGUNIT_TEST(testCFStringAppend); #endif #if LOG4CXX_UNICHAR_API && LOG4CXX_CFSTRING_API LOGUNIT_TEST(testULogStreamCFString); LOGUNIT_TEST(testULogStreamCFString2); #endif LOGUNIT_TEST_SUITE_END(); VectorAppenderPtr vectorAppender; #ifdef _DEBUG struct Fixture { Fixture() { helpers::LogLog::setInternalDebugging(true); } } suiteFixture; #endif public: void setUp() { LoggerPtr root(Logger::getRootLogger()); LayoutPtr layout(new SimpleLayout()); vectorAppender = VectorAppenderPtr(new VectorAppender()); root->addAppender(vectorAppender); } void tearDown() { LogManager::shutdown(); } void testSimple() { LoggerPtr root(Logger::getRootLogger()); LOG4CXX_INFO(root, "This is a test"); LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } void testMultiple() { LoggerPtr root(Logger::getRootLogger()); LOG4CXX_INFO(root, "This is a test" << ": Details to follow"); LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } void testShortCircuit() { LoggerPtr logger(Logger::getLogger("StreamTestCase.shortCircuit")); logger->setLevel(Level::getInfo()); ExceptionOnInsert someObj; LOG4CXX_DEBUG(logger, someObj); LOGUNIT_ASSERT_EQUAL((size_t) 0, vectorAppender->getVector().size()); } void testInsertException() { LoggerPtr logger(Logger::getLogger("StreamTestCase.insertException")); ExceptionOnInsert someObj; LOG4CXX_INFO(logger, someObj); } void testScientific() { LoggerPtr root(Logger::getRootLogger()); LOG4CXX_INFO(root, std::scientific << 0.000001115); auto events = vectorAppender->getVector(); LOGUNIT_ASSERT_EQUAL((size_t) 1, events.size()); LogString msg(events.front()->getMessage()); LOGUNIT_ASSERT(msg.find(LOG4CXX_STR("e-")) != LogString::npos || msg.find(LOG4CXX_STR("E-")) != LogString::npos); } void testPrecision() { LoggerPtr root(Logger::getRootLogger()); LOG4CXX_INFO(root, std::setprecision(4) << 1.000001); spi::LoggingEventPtr event(vectorAppender->getVector()[0]); LogString msg(event->getMessage()); LOGUNIT_ASSERT(msg.find(LOG4CXX_STR("1.00000")) == LogString::npos); } void testWidth() { LoggerPtr root(Logger::getRootLogger()); LOG4CXX_INFO(root, '[' << std::fixed << std::setprecision(2) << std::setw(7) << std::right << std::setfill('_') << 10.0 << ']'); spi::LoggingEventPtr event(vectorAppender->getVector()[0]); LogString msg(event->getMessage()); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("[__10.00]")), msg); } void testBaseFlags() { logstream base1(Logger::getRootLogger(), Level::getInfo()); logstream base2(Logger::getRootLogger(), Level::getInfo()); base1 << std::boolalpha; base2 << std::noboolalpha; std::ostringstream os1a, os1b, os2a, os2b; os1a << std::boolalpha; int fillchar; if (base1.set_stream_state(os1b, fillchar)) { os1b.fill(fillchar); } LOGUNIT_ASSERT_EQUAL(os1a.flags(), os1b.flags()); os2a << std::noboolalpha; if (base2.set_stream_state(os2b, fillchar)) { os2b.fill(fillchar); } LOGUNIT_ASSERT_EQUAL(os2a.flags(), os2b.flags()); } void testBasePrecisionAndWidth() { logstream base(Logger::getRootLogger(), Level::getInfo()); base.precision(2); base.width(5); std::ostringstream os1, os2; os1.precision(2); os1.width(5); os1 << 3.1415926; int fillchar; if (base.set_stream_state(os2, fillchar)) { os2.fill(fillchar); } os2 << 3.1415926; string expected(os1.str()); string actual(os2.str()); LOGUNIT_ASSERT_EQUAL(expected, actual); } void testLogStreamSimple() { logstream root(Logger::getRootLogger(), Level::getInfo()); root << std::string("This is a test") << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } void testLogStreamMultiple() { logstream root(Logger::getRootLogger(), Level::getInfo()); root << std::string("This is a test") << std::string(": Details to follow") << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } void testLogStreamShortCircuit() { LoggerPtr logger(Logger::getLogger("StreamTestCase.shortCircuit")); logger->setLevel(Level::getInfo()); logstream os(logger, Level::getDebug()); ExceptionOnInsert someObj; os << someObj << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 0, vectorAppender->getVector().size()); } void testLogStreamInsertException() { LoggerPtr logger(Logger::getLogger("StreamTestCase.insertException")); ExceptionOnInsert someObj; logstream os(logger, Level::getInfo()); os << someObj << LOG4CXX_ENDMSG; } void testLogStreamScientific() { LoggerPtr root(Logger::getRootLogger()); logstream os(root, Level::getInfo()); os << std::scientific << 0.000001115 << LOG4CXX_ENDMSG; spi::LoggingEventPtr event(vectorAppender->getVector()[0]); LogString msg(event->getMessage()); LOGUNIT_ASSERT(msg.find(LOG4CXX_STR("e-")) != LogString::npos || msg.find(LOG4CXX_STR("E-")) != LogString::npos); } void testLogStreamPrecision() { LoggerPtr root(Logger::getRootLogger()); logstream os(root, Level::getInfo()); os << std::setprecision(4) << 1.000001 << LOG4CXX_ENDMSG; spi::LoggingEventPtr event(vectorAppender->getVector()[0]); LogString msg(event->getMessage()); LOGUNIT_ASSERT(msg.find(LOG4CXX_STR("1.00000")) == LogString::npos); } void testLogStreamWidth() { LoggerPtr root(Logger::getRootLogger()); logstream os(root, Level::getInfo()); os << '[' << std::fixed << std::setprecision(2) << std::setw(7) << std::right << std::setfill('_') << 10.0 << ']' << LOG4CXX_ENDMSG; spi::LoggingEventPtr event(vectorAppender->getVector()[0]); LogString msg(event->getMessage()); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("[__10.00]")), msg); } void report(std::ostream & os) { os << "This just in: \n"; os << "Use logstream in places that expect a std::ostream.\n"; } void testLogStreamDelegate() { logstream root(Logger::getRootLogger(), Level::getInfo()); report(root); root << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } void testLogStreamFormattingPersists() { LoggerPtr root(Logger::getRootLogger()); root->setLevel(Level::getInfo()); logstream os(root, Level::getDebug()); os << std::hex << 20 << LOG4CXX_ENDMSG; os << Level::getInfo() << 16 << LOG4CXX_ENDMSG; spi::LoggingEventPtr event(vectorAppender->getVector()[0]); LogString msg(event->getMessage()); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("10")), msg); } void testSetWidthInsert() { LoggerPtr root(Logger::getRootLogger()); root->setLevel(Level::getInfo()); logstream os(root, Level::getInfo()); os << std::setw(5); LOGUNIT_ASSERT_EQUAL(5, os.width()); } #if LOG4CXX_WCHAR_T_API void testWide() { LoggerPtr root(Logger::getRootLogger()); LOG4CXX_INFO(root, L"This is a test"); LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } void testWideAppend() { LoggerPtr root(Logger::getRootLogger()); LOG4CXX_INFO(root, L"This is a test" << L": Details to follow"); LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } void testWideWidth() { LoggerPtr root(Logger::getRootLogger()); LOG4CXX_INFO(root, L'[' << std::fixed << std::setprecision(2) << std::setw(7) << std::right << std::setfill(L'_') << 10.0 << L"]"); spi::LoggingEventPtr event(vectorAppender->getVector()[0]); LogString msg(event->getMessage()); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("[__10.00]")), msg); } void testWLogStreamSimple() { wlogstream root(Logger::getRootLogger(), Level::getInfo()); root << L"This is a test" << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } void testWLogStreamMultiple() { wlogstream root(Logger::getRootLogger(), Level::getInfo()); root << L"This is a test" << L": Details to follow" << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } void testWLogStreamShortCircuit() { LoggerPtr logger(Logger::getLogger("StreamTestCase.shortCircuit")); logger->setLevel(Level::getInfo()); wlogstream os(logger, Level::getDebug()); ExceptionOnInsert someObj; os << someObj << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 0, vectorAppender->getVector().size()); } void testWLogStreamInsertException() { LoggerPtr logger(Logger::getLogger("StreamTestCase.insertException")); ExceptionOnInsert someObj; wlogstream os(logger, Level::getInfo()); os << someObj << LOG4CXX_ENDMSG; } void testWLogStreamScientific() { LoggerPtr root(Logger::getRootLogger()); wlogstream os(root, Level::getInfo()); os << std::scientific << 0.000001115 << LOG4CXX_ENDMSG; spi::LoggingEventPtr event(vectorAppender->getVector()[0]); LogString msg(event->getMessage()); LOGUNIT_ASSERT(msg.find(LOG4CXX_STR("e-")) != LogString::npos || msg.find(LOG4CXX_STR("E-")) != LogString::npos); } void testWLogStreamPrecision() { LoggerPtr root(Logger::getRootLogger()); wlogstream os(root, Level::getInfo()); os << std::setprecision(4) << 1.000001 << LOG4CXX_ENDMSG; spi::LoggingEventPtr event(vectorAppender->getVector()[0]); LogString msg(event->getMessage()); LOGUNIT_ASSERT(msg.find(LOG4CXX_STR("1.00000")) == LogString::npos); } void testWLogStreamWidth() { LoggerPtr root(Logger::getRootLogger()); wlogstream os(root, Level::getInfo()); os << L"[" << std::fixed << std::setprecision(2) << std::setw(7) << std::right << std::setfill(L'_') << 10.0 << L"]" << LOG4CXX_ENDMSG; spi::LoggingEventPtr event(vectorAppender->getVector()[0]); LogString msg(event->getMessage()); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("[__10.00]")), msg); } void wreport(std::basic_ostream& os) { os << L"This just in: \n"; os << L"Use logstream in places that expect a std::ostream.\n"; } void testWLogStreamDelegate() { wlogstream root(Logger::getRootLogger(), Level::getInfo()); wreport(root); root << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } void testWLogStreamFormattingPersists() { LoggerPtr root(Logger::getRootLogger()); root->setLevel(Level::getInfo()); wlogstream os(root, Level::getDebug()); os << std::hex << 20 << LOG4CXX_ENDMSG; os << Level::getInfo() << 16 << LOG4CXX_ENDMSG; spi::LoggingEventPtr event(vectorAppender->getVector()[0]); LogString msg(event->getMessage()); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("10")), msg); } void testWSetWidthInsert() { LoggerPtr root(Logger::getRootLogger()); root->setLevel(Level::getInfo()); wlogstream os(root, Level::getInfo()); os << std::setw(5); LOGUNIT_ASSERT_EQUAL(5, os.width()); } #endif #if LOG4CXX_UNICHAR_API void testUniChar() { LoggerPtr root(Logger::getRootLogger()); const log4cxx::UniChar msg[] = { 'T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't', 0 }; LOG4CXX_INFO(root, msg); LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } void testUniCharAppend() { LoggerPtr root(Logger::getRootLogger()); const log4cxx::UniChar msg1[] = { 'T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't', 0 }; const log4cxx::UniChar msg2[] = { ':', ' ', 'D', 'e', 't', 'a', 'i', 'l', 's', ' ', 't', 'o', ' ', 'f', 'o', 'l', 'l', 'o', 'w', 0 }; LOG4CXX_INFO(root, msg1 << msg2); LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } void testUniCharWidth() { LoggerPtr root(Logger::getRootLogger()); const log4cxx::UniChar openBracket[] = { '[', 0 }; const log4cxx::UniChar closeBracket[] = { ']', 0 }; LOG4CXX_INFO(root, openBracket << std::fixed << std::setprecision(2) << std::setw(7) << std::right << std::setfill((log4cxx::UniChar)'_') << 10.0 << closeBracket); spi::LoggingEventPtr event(vectorAppender->getVector()[0]); LogString msg(event->getMessage()); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("[__10.00]")), msg); } void testULogStreamSimple() { ulogstream root(Logger::getRootLogger(), Level::getInfo()); const log4cxx::UniChar msg[] = { 'T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't', 0 }; root << msg << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } void testULogStreamMultiple() { ulogstream root(Logger::getRootLogger(), Level::getInfo()); const log4cxx::UniChar msg1[] = { 'T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't', 0 }; const log4cxx::UniChar msg2[] = { ':', ' ', 'D', 'e', 't', 'a', 'i', 'l', 's', ' ', 't', 'o', ' ', 'f', 'o', 'l', 'l', 'o', 'w', 0 }; root << msg1 << msg2 << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } void testULogStreamShortCircuit() { LoggerPtr logger(Logger::getLogger("StreamTestCase.shortCircuit")); logger->setLevel(Level::getInfo()); ulogstream os(logger, Level::getDebug()); ExceptionOnInsert someObj; os << someObj << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 0, vectorAppender->getVector().size()); } void testULogStreamInsertException() { LoggerPtr logger(Logger::getLogger("StreamTestCase.insertException")); ExceptionOnInsert someObj; ulogstream os(logger, Level::getInfo()); os << someObj << LOG4CXX_ENDMSG; } void testULogStreamScientific() { LoggerPtr root(Logger::getRootLogger()); ulogstream os(root, Level::getInfo()); os << std::scientific << 0.000001115 << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); spi::LoggingEventPtr event(vectorAppender->getVector()[0]); LogString msg(event->getMessage()); LOGUNIT_ASSERT(msg.find(LOG4CXX_STR("e-")) != LogString::npos || msg.find(LOG4CXX_STR("E-")) != LogString::npos); } void testULogStreamPrecision() { LoggerPtr root(Logger::getRootLogger()); ulogstream os(root, Level::getInfo()); os << std::setprecision(4) << 1.000001 << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); spi::LoggingEventPtr event(vectorAppender->getVector()[0]); LogString msg(event->getMessage()); LOGUNIT_ASSERT(msg.find(LOG4CXX_STR("1.00000")) == LogString::npos); } void testULogStreamWidth() { LoggerPtr root(Logger::getRootLogger()); ulogstream os(root, Level::getInfo()); const log4cxx::UniChar openBracket[] = { '[', 0 }; const log4cxx::UniChar closeBracket[] = { ']', 0 }; os << openBracket << std::fixed << std::setprecision(2) << std::setw(7) << std::right << std::setfill((log4cxx::UniChar) '_') << 10.0 << closeBracket << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); spi::LoggingEventPtr event(vectorAppender->getVector()[0]); LogString msg(event->getMessage()); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("[__10.00]")), msg); } void ureport(std::basic_ostream& os) { const log4cxx::UniChar msg1[] = { 'T', 'h', 'i', 's', ' ', 'j', 'u', 's', 't', ' ', 'i', 'n', ':', ' ', '\n', 0 }; const log4cxx::UniChar msg2[] = { 'U', 's', 'e', ' ', 'l', 'o', 'g', 's', 't', 'r', 'e', 'a', 'm', '\n', 0 }; os << msg1; os << msg2; } void testULogStreamDelegate() { ulogstream root(Logger::getRootLogger(), Level::getInfo()); ureport(root); root << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } void testULogStreamFormattingPersists() { LoggerPtr root(Logger::getRootLogger()); root->setLevel(Level::getInfo()); ulogstream os(root, Level::getDebug()); os << std::hex << 20 << LOG4CXX_ENDMSG; os << Level::getInfo() << 16 << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); spi::LoggingEventPtr event(vectorAppender->getVector()[0]); LogString msg(event->getMessage()); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("10")), msg); } void testUSetWidthInsert() { LoggerPtr root(Logger::getRootLogger()); root->setLevel(Level::getInfo()); ulogstream os(root, Level::getInfo()); os << std::setw(5); LOGUNIT_ASSERT_EQUAL(5, os.width()); } #endif #if LOG4CXX_CFSTRING_API void testCFString() { LoggerPtr root(Logger::getRootLogger()); LOG4CXX_INFO(root, CFSTR("This is a test")); LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } void testCFStringAppend() { LoggerPtr root(Logger::getRootLogger()); LOG4CXX_INFO(root, CFSTR("This is a test") << CFSTR(": Details to follow")); LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } #endif #if LOG4CXX_UNICHAR_API && LOG4CXX_CFSTRING_API void testULogStreamCFString() { ulogstream root(Logger::getRootLogger(), Level::getInfo()); root << CFSTR("This is a test") << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } void testULogStreamCFString2() { ulogstream root(Logger::getRootLogger(), Level::getInfo()); root << CFSTR("This is a test") << CFSTR(": Details to follow") << LOG4CXX_ENDMSG; LOGUNIT_ASSERT_EQUAL((size_t) 1, vectorAppender->getVector().size()); } #endif }; LOGUNIT_TEST_SUITE_REGISTRATION(StreamTestCase); #if !LOG4CXX_USE_GLOBAL_SCOPE_TEMPLATE // // The following code tests compilation errors // around bug LOGCXX-150 and is not intended to be executed. // Skipped for VC6 since it can't handle having the // templated operator<< in class scope.s namespace foo { class Bar { void fn(); }; std::ostream& operator<<(std::ostream& o, Bar const& b) { return o << "Bar"; } } using namespace foo; namespace { log4cxx::LoggerPtr logger(log4cxx::Logger::getLogger("foo")); log4cxx::logstream lout(logger, log4cxx::Level::getDebug()); } void Bar::fn() { lout << "hi" << LOG4CXX_ENDMSG; } #endif apache-log4cxx-1.3.1/src/test/cpp/decodingtest.cpp0000644000175100001770000001365414721727031021415 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #include #include "logunit.h" #define LOG4CXX_TEST 1 #include // // If there is no support for wchar_t logging then // there is not a consistent way to get the test characters compared. // #if LOG4CXX_WCHAR_T_API using namespace log4cxx; using namespace log4cxx::helpers; /** * Tests support for decoding specification. * * The lib provides multiple different decoders and decides which to use by default on compile time. * This test uses the same checks like {@link CharsetDecoder#createDefaultDecoder} to decide which * checks to run actually, so that some input file with some encoded text according to the decoder * in use is read and the contents compared to some witness. Because of different decoders not all * files have the same content, e.g. the ASCII-only decoder can't deal with Unicode chars obviously. * * This test is based on encodingtest and uses that witnesses, especially the hard coded strings for * greeting and pi. We only combine it into one in the former mentioned order, divided by a space. * * @see LOGCXX-369 * @see LOGCXX-399 */ LOGUNIT_CLASS(DecodingTest) { LOGUNIT_TEST_SUITE(DecodingTest); #if LOG4CXX_CHARSET_USASCII LOGUNIT_TEST(testASCII); #elif LOG4CXX_CHARSET_ISO88591 || defined(_WIN32_WCE) LOGUNIT_TEST(testLatin1); #elif LOG4CXX_CHARSET_UTF8 LOGUNIT_TEST(testUtf8); #elif LOG4CXX_LOGCHAR_IS_WCHAR && LOG4CXX_HAS_MBSRTOWCS LOGUNIT_TEST(testUtf8_to_wchar); LOGUNIT_TEST(testUtf16); LOGUNIT_TEST(testUtf16LE); LOGUNIT_TEST(testUtf16BE); #else // LocaleCharsetDecoder, so it's difficult to provide a file working for e.g. windows-1252 // as well as something completely different. LOGUNIT_TEST(testASCII); #endif LOGUNIT_TEST_SUITE_END(); public: /** * Test us-ascii decoding. */ void testASCII() { const wchar_t witness[] = { L'A', 0x003F, 0x003F, 0x003F, 0x003F, 0x003F, 0x0020, 0x003F, 0 }; testImpl(LOG4CXX_STR("ascii.txt"), witness); } /** * Test iso-8859-1 decoding. */ void testLatin1() { const wchar_t witness[] = { L'A', 0x003F, 0x003F, 0x003F, 0x003F, 0x003F, 0x0020, 0x00B9, 0 }; testImpl(LOG4CXX_STR("latin1.txt"), witness); } /** * Test utf-8 decoding. */ void testUtf8() { const wchar_t witness[] = { L'A', 0x0605, 0x0530, 0x986, 0x4E03, 0x0400, 0x0020, 0x00B9, 0 }; testImpl(LOG4CXX_STR("UTF-8.txt"), witness); } /** * Test utf-8 decoding. */ void testUtf8_to_wchar() { const wchar_t witness[] = { L'A', 0x0605, 0x0530, 0x986, 0x4E03, 0x0400, 0x0020, 0x00B9, 0 }; try { std::locale::global(std::locale("en_US.UTF-8")); testImpl(LOG4CXX_STR("UTF-8.txt"), witness); } catch (std::runtime_error& ex) { LogString msg; Transcoder::decode(ex.what(), msg); msg.append(LOG4CXX_STR(": ")); msg.append(LOG4CXX_STR("en_US.UTF-8")); LogLog::warn(msg); } } /** * Test utf-16 decoding. */ void testUtf16() { const wchar_t witness[] = { L'A', 0x0605, 0x0530, 0x986, 0x4E03, 0x0400, 0x0020, 0x00B9, 0 }; try { std::locale::global(std::locale("en_US.UTF-16")); testImpl(LOG4CXX_STR("UTF-16.txt"), witness); } catch (std::runtime_error& ex) { LogString msg; Transcoder::decode(ex.what(), msg); msg.append(LOG4CXX_STR(": ")); msg.append(LOG4CXX_STR("en_US.UTF-16")); LogLog::warn(msg); } } /** * Test utf-16be decoding. */ void testUtf16BE() { const wchar_t witness[] = { L'A', 0x0605, 0x0530, 0x986, 0x4E03, 0x0400, 0x0020, 0x00B9, 0 }; try { std::locale::global(std::locale("en_US.UTF-16BE")); testImpl(LOG4CXX_STR("UTF-16BE.txt"), witness); } catch (std::runtime_error& ex) { LogString msg; Transcoder::decode(ex.what(), msg); msg.append(LOG4CXX_STR(": ")); msg.append(LOG4CXX_STR("en_US.UTF-16BE")); LogLog::warn(msg); } } /** * Test utf16-le decoding. */ void testUtf16LE() { const wchar_t witness[] = { L'A', 0x0605, 0x0530, 0x986, 0x4E03, 0x0400, 0x0020, 0x00B9, 0 }; try { std::locale::global(std::locale("en_US.UTF-16LE")); testImpl(LOG4CXX_STR("UTF-16LE.txt"), witness); } catch (std::exception& ex) { LogString msg; Transcoder::decode(ex.what(), msg); msg.append(LOG4CXX_STR(": ")); msg.append(LOG4CXX_STR("en_US.UTF-16LE")); LogLog::warn(msg); } } private: void testImpl( const LogString & fileName, const wchar_t* witness) { CharsetDecoderPtr decoder(CharsetDecoder::getDefaultDecoder()); LogString lsContent; std::wstring wsContent; LogString path(LOG4CXX_STR("input/decoding/") + fileName); Pool pool; FileInputStreamPtr fis( new FileInputStream(path)); InputStreamReaderPtr isReader(new InputStreamReader(fis, decoder)); lsContent.assign(isReader->read(pool)); Transcoder::encode(lsContent, wsContent); LOGUNIT_ASSERT_EQUAL((std::wstring) witness, wsContent); } }; LOGUNIT_TEST_SUITE_REGISTRATION(DecodingTest); #endif apache-log4cxx-1.3.1/src/test/cpp/CMakeLists.txt0000644000175100001770000001733714721727031020777 0ustar runnerdocker# # 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. # option(ENABLE_MULTITHREAD_TEST "Enable multithread test. Note that this test is very unstable, it is mostly designed to ensure that we don't crash immediately if exit is called in a thread" OFF) # Components required by all tests add_library(testingFramework STATIC abts.cpp appenderskeletontestcase.cpp logunit.cpp vectorappender.cpp writerappendertestcase.cpp ) target_compile_definitions(testingFramework PRIVATE ${LOG4CXX_COMPILE_DEFINITIONS} ${APR_COMPILE_DEFINITIONS} ${APR_UTIL_COMPILE_DEFINITIONS} ) target_include_directories(testingFramework PRIVATE ${CMAKE_CURRENT_LIST_DIR} $) add_subdirectory(util) target_sources(testingUtilities PRIVATE xml/xlevel.cpp) set( LOG4CXX_TEST_PROGRAM_PATH "" CACHE PATH "Extra path for test programs" ) set( CMAKE_PROGRAM_PATH "${LOG4CXX_TEST_PROGRAM_PATH};${CMAKE_PROGRAM_PATH}" ) # sed, zip, and gzip are needed for the tests to work properly # Note: option 'required' not available until cmake 3.18, however adding # it does not cause an issue find_program(SED_APP sed REQUIRED) find_program(ZIP_APP zip REQUIRED) find_program(GZIP_APP gzip REQUIRED) # Tests defined in this directory set(ALL_LOG4CXX_TESTS autoconfiguretestcase asyncappendertestcase consoleappendertestcase decodingtest encodingtest fileappendertest filetestcase hexdumptestcase hierarchytest hierarchythresholdtestcase jsonlayouttest l7dtestcase leveltestcase levelchangetestcase loggertestcase mdctestcase minimumtestcase ndctestcase patternlayouttest propertyconfiguratortest rollingfileappendertestcase streamtestcase locationtest locationdisabledtest terminationtestcase ) if(${ENABLE_FMT_LAYOUT}) set(ALL_LOG4CXX_TESTS ${ALL_LOG4CXX_TESTS} fmttest) endif() if(${ENABLE_MULTITHREAD_TEST}) set(ALL_LOG4CXX_TESTS ${ALL_LOG4CXX_TESTS} multithreadtest) endif() if(${LOG4CXX_EVENTS_AT_EXIT}) set(ALL_LOG4CXX_TESTS ${ALL_LOG4CXX_TESTS} eventsatexittest) endif() foreach(fileName IN LISTS ALL_LOG4CXX_TESTS) add_executable(${fileName} "${fileName}.cpp") endforeach() target_sources(rollingfileappendertestcase PRIVATE fileappendertestcase.cpp) # Tests defined in subdirectories add_subdirectory(helpers) if(LOG4CXX_DOMCONFIGURATOR_SUPPORT) add_subdirectory(customlogger) add_subdirectory(xml) endif() if(HAS_ODBC) add_subdirectory(db) endif() add_subdirectory(defaultinit) add_subdirectory(filter) add_subdirectory(net) if(WIN32) add_subdirectory(nt) endif() add_subdirectory(pattern) add_subdirectory(rolling) add_subdirectory(varia) add_subdirectory(throughput) add_subdirectory(benchmark) if( WIN32 ) include(win32_target_environment_path) get_target_environment_path(ESCAPED_PATH) elseif(CMAKE_BUILD_TYPE) string(TOUPPER ${CMAKE_BUILD_TYPE} UPPER_BUILD_TYPE) if (UPPER_BUILD_TYPE STREQUAL "DEBUG") set(TEST_COMPILE_DEFINITIONS _DEBUG) endif() else() set(TEST_COMPILE_DEFINITIONS _DEBUG) endif() get_filename_component(UNIT_TEST_WORKING_DIR ../resources ABSOLUTE) if(LOG4CXX_CFSTRING) set(CFSTR_TESTS filetestcase messagebuffertest leveltestcase streamtestcase transcodertestcase) endif() foreach(testName IN LISTS ALL_LOG4CXX_TESTS) if (${testName} IN_LIST CFSTR_TESTS) if(APPLE) target_compile_options(${testName} PRIVATE "-fconstant-cfstrings") target_link_libraries(${testName} PRIVATE "-framework CoreFoundation") else() target_link_libraries(${testName} PRIVATE MockCoreFoundation) endif() endif() target_compile_definitions(${testName} PRIVATE ${TEST_COMPILE_DEFINITIONS} ${LOG4CXX_COMPILE_DEFINITIONS} ${APR_COMPILE_DEFINITIONS} ${APR_UTIL_COMPILE_DEFINITIONS} ) target_include_directories(${testName} PRIVATE ${CMAKE_CURRENT_LIST_DIR} $) target_link_libraries(${testName} PRIVATE testingFramework testingUtilities log4cxx ${APR_LIBRARIES} ${APR_SYSTEM_LIBS} Threads::Threads ${ODBC_LIBRARIES} ) if(HAS_LIBESMTP) target_link_libraries(${testName} PRIVATE ${ESMTP_LIBRARIES}) endif() add_test(NAME ${testName} COMMAND ${testName} -v WORKING_DIRECTORY ${UNIT_TEST_WORKING_DIR} ) set_tests_properties( ${testName} PROPERTIES TIMEOUT 120 ) if(WIN32) set_target_properties(${testName} PROPERTIES VS_DEBUGGER_WORKING_DIRECTORY ${UNIT_TEST_WORKING_DIR} FOLDER UnitTests ) set_target_properties(${testName} PROPERTIES VS_DEBUGGER_COMMAND_ARGUMENTS "-v" ) if(${testName} STREQUAL socketservertestcase) set_target_properties(${testName} PROPERTIES VS_DEBUGGER_ENVIRONMENT "SOCKET_SERVER_PARAMETER_FILE=${START_SOCKET_SERVER_PARAMETER_FILE}\nPATH=${ESCAPED_PATH}" ) set_tests_properties(socketservertestcase PROPERTIES ENVIRONMENT "SOCKET_SERVER_PARAMETER_FILE=${START_SOCKET_SERVER_PARAMETER_FILE};PATH=${ESCAPED_PATH}" ) elseif(${testName} STREQUAL optionconvertertestcase) set_target_properties(${testName} PROPERTIES VS_DEBUGGER_ENVIRONMENT "TOTO=wonderful\nkey1=value1\nkey2=value2\nPATH=${ESCAPED_PATH}" ) set_tests_properties(${testName} PROPERTIES ENVIRONMENT "TOTO=wonderful;key1=value1;key2=value2;PATH=${ESCAPED_PATH}" ) else() set_target_properties(${testName} PROPERTIES VS_DEBUGGER_ENVIRONMENT "key1=value1\nkey2=value2\nPATH=${ESCAPED_PATH}" ) set_tests_properties(${testName} PROPERTIES ENVIRONMENT "key1=value1;key2=value2;PATH=${ESCAPED_PATH}" ) endif() if(NOT BUILD_SHARED_LIBS) # cmake selects a multi-threaded dynamically-linked runtime library by default # (i.e. MSVC_RUNTIME_LIBRARY target property default value is "MultiThreaded$<$:Debug>DLL") # APR static libraries specify the MSVC statically-linked runtime as the default library # Use the MSVC statically-linked runtime to prevent the warning message 'LNK4098: defaultlib 'LIBCMT' conflicts with use of other libs' set_target_properties(${testName} PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") endif() else() if(${testName} STREQUAL socketservertestcase) set_tests_properties(socketservertestcase PROPERTIES ENVIRONMENT "SOCKET_SERVER_PARAMETER_FILE=${START_SOCKET_SERVER_PARAMETER_FILE}" ) elseif(${testName} STREQUAL optionconvertertestcase) set_tests_properties(optionconvertertestcase PROPERTIES ENVIRONMENT "TOTO=wonderful;key1=value1;key2=value2" ) else() set_tests_properties(${testName} PROPERTIES ENVIRONMENT "key1=value1;key2=value2" ) endif() endif() endforeach() target_compile_definitions(locationdisabledtest PRIVATE LOG4CXX_DISABLE_LOCATION_INFO) apache-log4cxx-1.3.1/src/test/cpp/testutil.h0000644000175100001770000000170414721727031020254 0ustar runnerdocker/* 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. */ #include "abts.h" #ifndef APR_TEST_UTIL #define APR_TEST_UTIL void initialize(void); abts_suite* abts_run_suites(abts_suite*); #endif /* APR_TEST_INCLUDES */ apache-log4cxx-1.3.1/src/test/cpp/appenderskeletontestcase.h0000644000175100001770000000216214721727031023475 0ustar runnerdocker/* * 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. */ #include #include "logunit.h" /** An abstract set of tests for inclusion in concrete appender test case */ LOGUNIT_CLASS(AppenderSkeletonTestCase) { public: virtual log4cxx::AppenderSkeleton* createAppenderSkeleton() const = 0; void testDefaultThreshold(); void testSetOptionThreshold(); }; apache-log4cxx-1.3.1/src/test/cpp/rollingfileappendertestcase.cpp0000644000175100001770000000271214721727031024513 0ustar runnerdocker/* * 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. */ #include #include "fileappendertestcase.h" using namespace log4cxx; using namespace log4cxx::helpers; /** Unit tests of log4cxx::RollingFileAppender */ class RollingFileAppenderTestCase : public FileAppenderAbstractTestCase { LOGUNIT_TEST_SUITE(RollingFileAppenderTestCase); // // tests inherited from AppenderSkeletonTestCase // LOGUNIT_TEST(testDefaultThreshold); LOGUNIT_TEST(testSetOptionThreshold); LOGUNIT_TEST_SUITE_END(); public: FileAppender* createFileAppender() const { return new log4cxx::rolling::RollingFileAppender(); } }; LOGUNIT_TEST_SUITE_REGISTRATION(RollingFileAppenderTestCase); apache-log4cxx-1.3.1/src/test/cpp/autoconfiguretestcase.cpp0000644000175100001770000001052314721727031023337 0ustar runnerdocker/* * 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. */ #include "logunit.h" #include #include #include #include #include #include #include #include #include #include #include #include #include "apr_time.h" #define LOGUNIT_TEST_THREADS(testName, threadCount) \ class testName ## ThreadTestRegistration { \ public: \ testName ## ThreadTestRegistration() { \ ThisFixture::getSuite()->addTest(#testName, &testName ## ThreadTestRegistration :: run); \ } \ static void run(abts_case* tc, void*) { \ std::vector threads; \ for (auto i = threadCount; 0 < i; --i) \ threads.emplace_back( [tc]() { \ LogUnit::runTest(tc, &ThisFixture::testName); \ } ); \ while (!threads.empty()) { \ threads.back().join(); \ threads.pop_back(); \ } \ } \ } register ## testName ## ThreadTest using namespace log4cxx; LOGUNIT_CLASS(AutoConfigureTestCase) { LOGUNIT_TEST_SUITE(AutoConfigureTestCase); LOGUNIT_TEST(copyPropertyFile); LOGUNIT_TEST_THREADS(test1, 4); LOGUNIT_TEST(test2); LOGUNIT_TEST(test3); LOGUNIT_TEST(shutdown); LOGUNIT_TEST_SUITE_END(); #ifdef _DEBUG struct Fixture { Fixture() { helpers::LogLog::setInternalDebugging(true); } } suiteFixture; apr_time_t m_initTime = apr_time_now(); #endif helpers::Pool m_pool; char m_buf[2048]; LogString m_configFile = LOG4CXX_STR("autoconfiguretestcase.properties"); public: void copyPropertyFile() { LOGUNIT_ASSERT(File(LOG4CXX_STR("input/autoConfigureTest.properties")).exists(m_pool)); LOGUNIT_ASSERT(apr_file_copy ( "input/autoConfigureTest.properties" , "autoconfiguretestcase.properties" , APR_FPROT_UREAD | APR_FPROT_UWRITE , m_pool.getAPRPool() ) == APR_SUCCESS); DefaultConfigurator::setConfigurationFileName(m_configFile); DefaultConfigurator::setConfigurationWatchSeconds(1); LOGUNIT_ASSERT(File(m_configFile).exists(m_pool)); } void shutdown() { LogManager::shutdown(); LOGUNIT_ASSERT(apr_file_remove("autoconfiguretestcase.properties", m_pool.getAPRPool()) == APR_SUCCESS); } void test1() { auto debugLogger = LogManager::getLogger(LOG4CXX_STR("AutoConfig.test1")); LOGUNIT_ASSERT(debugLogger); LOGUNIT_ASSERT(!debugLogger->isDebugEnabled()); auto rep = LogManager::getLoggerRepository(); LOGUNIT_ASSERT(rep); LOGUNIT_ASSERT(rep->isConfigured()); } void test2() { auto debugLogger = LogManager::getLogger(LOG4CXX_STR("AutoConfig.test2")); LOGUNIT_ASSERT(debugLogger); LOGUNIT_ASSERT(debugLogger->isDebugEnabled()); } void test3() { // wait 2 sec to ensure the modification time is different to that held in the WatchDog apr_sleep(2000000); auto debugLogger = LogManager::getLogger(LOG4CXX_STR("AutoConfig.test3")); LOGUNIT_ASSERT(debugLogger); LOGUNIT_ASSERT(!debugLogger->isDebugEnabled()); // Append a configuration for test3 logger helpers::ByteBuffer bbuf(m_buf, sizeof(m_buf)); int sz = 0; for (const char* p = "\nlog4j.logger.AutoConfig.test3=DEBUG\n"; *p; ++p) { bbuf.put(*p); ++sz; } bbuf.position(0); bbuf.limit(sz); helpers::FileOutputStream of(m_configFile, true); of.write(bbuf, m_pool); of.flush(m_pool); of.close(m_pool); // wait 1.5 sec for the change to be noticed apr_sleep(1500000); LOGUNIT_ASSERT(debugLogger->isDebugEnabled()); } }; LOGUNIT_TEST_SUITE_REGISTRATION(AutoConfigureTestCase); apache-log4cxx-1.3.1/src/test/cpp/db/0000755000175100001770000000000014721727031016611 5ustar runnerdockerapache-log4cxx-1.3.1/src/test/cpp/db/odbcappendertestcase.cpp0000644000175100001770000000525514721727031023506 0ustar runnerdocker/* * 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. */ #include #include #include #include "../appenderskeletontestcase.h" #include #define LOG4CXX_TEST 1 #include #ifdef LOG4CXX_HAVE_ODBC using namespace log4cxx; /** Unit tests of log4cxx::SocketAppender */ class ODBCAppenderTestCase : public AppenderSkeletonTestCase { LOGUNIT_TEST_SUITE(ODBCAppenderTestCase); // // tests inherited from AppenderSkeletonTestCase // LOGUNIT_TEST(testDefaultThreshold); LOGUNIT_TEST(testSetOptionThreshold); //LOGUNIT_TEST(testConnectUsingDSN); LOGUNIT_TEST_SUITE_END(); public: AppenderSkeleton* createAppenderSkeleton() const { return new db::ODBCAppender(); } // Flush the last message to the database prior to process termination void tearDown() { LogManager::shutdown(); } // 'odbcAppenderDSN-Log4cxxTest.xml' requires the data souce name 'Log4cxxTest' // containing a 'ApplicationLogs' database // with 'UnitTestLog' table // containing the fields shown below: // // USE [ApplicationLogs] // GO // // SET ANSI_NULLS ON // GO // // SET QUOTED_IDENTIFIER ON // GO // // CREATE TABLE [dbo].[UnitTestLog]( // [Item] [bigint] IDENTITY(1,1) NOT NULL, /* auto incremented */ // [Thread] [nchar](20) NULL // [LogTime] [datetime] NOT NULL, // [LogName] [nchar](50) NULL, // [LogLevel] [nchar](10) NULL, // [FileName] [nchar](300) NULL, // [FileLine] [int] NULL, // [Message] [nchar](1000) NULL // ) ON [PRIMARY] // GO // void testConnectUsingDSN() { xml::DOMConfigurator::configure("input/xml/odbcAppenderDSN-Log4cxxTest.xml"); auto odbc = Logger::getLogger("DB.UnitTest"); for (int i = 0; i < 100; ++i) { LOG4CXX_INFO(odbc, "Message '" << i << "'"); apr_sleep(30000); } LOG4CXX_INFO(odbc, "Last message"); } }; LOGUNIT_TEST_SUITE_REGISTRATION(ODBCAppenderTestCase); #endif apache-log4cxx-1.3.1/src/test/cpp/db/CMakeLists.txt0000644000175100001770000000021414721727031021346 0ustar runnerdockeradd_executable(odbcappendertestcase odbcappendertestcase.cpp) set(ALL_LOG4CXX_TESTS ${ALL_LOG4CXX_TESTS} odbcappendertestcase PARENT_SCOPE) apache-log4cxx-1.3.1/src/test/cpp/insertwide.h0000644000175100001770000000223614721727031020555 0ustar runnerdocker/* * 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. */ #if !defined(LOG4CXX_TEST_INSERT_WIDE) #define LOG4CXX_TEST_INSERT_WIDE 1 #include #include #if LOG4CXX_WCHAR_T_API std::ostream& operator<<(std::ostream& os, const std::wstring& str); #endif #if LOG4CXX_LOGCHAR_IS_UNICHAR || LOG4CXX_UNICHAR_API std::ostream& operator<<(std::ostream& os, const std::basic_string& str); #endif #endif apache-log4cxx-1.3.1/src/test/cpp/logunit.h0000644000175100001770000001673114721727031020066 0ustar runnerdocker/* * 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. */ #if !defined(_LOG4CXX_LOGUNIT_H) #define _LOG4CXX_LOGUNIT_H #include "abts.h" #include #include #include #include #include #include namespace LogUnit { class TestException : public std::exception { public: TestException(); TestException(const TestException&); TestException& operator=(const TestException&); }; class AssertException : public std::exception { public: AssertException(std::string msg, int lineno); AssertException(bool expected, const char* actualExpr, int lineno); AssertException(const AssertException&); AssertException& operator=(const AssertException&); virtual ~AssertException() throw(); std::string getMessage() const; int getLine() const; private: std::string msg; int lineno; }; class TestFixture { public: TestFixture(); virtual ~TestFixture(); void setCase(abts_case* tc); virtual void setUp(); virtual void tearDown(); void assertEquals(const int expected, const int actual, int lineno); void assertEquals(const std::string expected, const std::string actual, const char* expectedExpr, const char* actualExpr, int lineno); void assertEquals(const char* expected, const char* actual, const char* expectedExpr, const char* actualExpr, int lineno); #if LOG4CXX_LOGCHAR_IS_WCHAR || LOG4CXX_WCHAR_T_API void assertEquals(const std::wstring expected, const std::wstring actual, const char* expectedExpr, const char* actualExpr, int lineno); #endif #if LOG4CXX_LOGCHAR_IS_UNICHAR || LOG4CXX_UNICHAR_API void assertEquals(const std::basic_string expected, const std::basic_string actual, const char* expectedExpr, const char* actualExpr, int lineno); #endif template void assertEquals(const T& expected, const T& actual, const char* expectedExpr, const char* actualExpr, int lineno) { if (expected != actual) { std::string msg(expectedExpr); msg.append(" != "); msg.append(actualExpr); abts_fail(tc, msg.c_str(), lineno); } } private: TestFixture(const TestFixture&); TestFixture& operator=(const TestFixture&); abts_case* tc; }; template void runTest(abts_case* tc, void (T::*func)()) { T ti; ti.setCase(tc); ti.setUp(); try { (ti.*func)(); } catch (TestException&) { } catch (AssertException& fx) { abts_fail(tc, fx.getMessage().c_str(), fx.getLine()); } catch (std::exception& e) { const char* what = e.what(); std::ostringstream oss; oss << "Unexpected std::exception: " << (what ? what : "what() == NULL"); abts_fail(tc, oss.str().c_str(), -1); } catch (...) { abts_fail(tc, "Unexpected exception", -1); } ti.tearDown(); } template void runTestWithException(abts_case* tc, void (T::*func)()) { T ti; ti.setCase(tc); ti.setUp(); try { (ti.*func)(); } catch (TestException&) { } catch (AssertException& fx) { abts_fail(tc, fx.getMessage().c_str(), fx.getLine()); } catch (X&) { } catch (...) { abts_fail(tc, "Unexpected exception", -1); } ti.tearDown(); } class TestSuite { public: TestSuite(const char* filename); void addTest(const char* testName, test_func func); abts_suite* run(abts_suite* suite) const; std::string getName() const; void setDisabled(bool newVal); bool isDisabled() const; private: TestSuite(const TestSuite&); TestSuite& operator=(const TestSuite&); typedef std::vector> TestList; TestList test_funcs; std::string filename; bool disabled; }; typedef std::vector< std::pair > SuiteList; SuiteList& getAllSuites(); template class RegisterSuite { public: RegisterSuite() { T::populateSuite(); TestSuite* suite = T::getSuite(); LogUnit::getAllSuites().push_back(SuiteList::value_type(suite->getName(), suite)); } }; template class RegisterDisabledSuite { public: RegisterDisabledSuite() { T::populateSuite(); TestSuite* suite = T::getSuite(); suite->setDisabled(true); LogUnit::getAllSuites().push_back(SuiteList::value_type(suite->getName(), suite)); } }; } #define LOGUNIT_CLASS(x) class x : public LogUnit::TestFixture #define LOGUNIT_TEST_SUITE(TF) \ public: \ static LogUnit::TestSuite* getSuite() { \ static LogUnit::TestSuite suite(__FILE__); \ return &suite; \ } \ private: \ class RegisterSuite { \ public: \ typedef TF ThisFixture #define LOGUNIT_TEST(testName) \ class testName ## Registration { \ public: \ testName ## Registration() { \ ThisFixture::getSuite()->addTest(#testName, &testName ## Registration :: run); \ } \ static void run(abts_case* tc, void*) { \ LogUnit::runTest(tc, &ThisFixture::testName); \ } \ } register ## testName #define LOGUNIT_TEST_EXCEPTION(testName, Exception) \ class testName ## Registration { \ public: \ testName ## Registration() { \ ThisFixture::getSuite()->addTest(#testName, &testName ## Registration :: run); \ } \ static void run(abts_case* tc, void*) { \ LogUnit::runTestWithException(tc, &ThisFixture::testName); \ } \ } register ## testName #define LOGUNIT_TEST_SUITE_END() \ }; \ public: \ static void populateSuite() { \ static RegisterSuite registration; \ } \ private: \ void nop() #define LOGUNIT_TEST_SUITE_REGISTRATION(TF) \ static LogUnit::RegisterSuite registration; #define LOGUNIT_TEST_SUITE_REGISTRATION_DISABLED(TF) \ static LogUnit::RegisterDisabledSuite registration; #define LOGUNIT_ASSERT( x) { if (!(x)) throw LogUnit::AssertException(true, #x, __LINE__); } #define LOGUNIT_ASSERT_SRCL(x, srcLine) { if (!(x)) throw LogUnit::AssertException(true, #x, srcLine); } #define LOGUNIT_ASSERT_EQUAL( expected, actual) assertEquals(expected, actual, #expected, #actual, __LINE__) #define LOGUNIT_ASSERT_EQUAL_SRCL( expected, actual, srcLine) assertEquals(expected, actual, #expected, #actual, srcLine) #define LOGUNIT_FAIL(msg) throw LogUnit::AssertException(msg, __LINE__) #endif apache-log4cxx-1.3.1/src/test/cpp/vectorappender.h0000644000175100001770000000360214721727031021417 0ustar runnerdocker/* * 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. */ #include #include #include #include namespace LOG4CXX_NS { /** An appender that appends logging events to a vector. */ class VectorAppender : public AppenderSkeleton { public: DECLARE_LOG4CXX_OBJECT(VectorAppender) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(VectorAppender) LOG4CXX_CAST_ENTRY_CHAIN(AppenderSkeleton) END_LOG4CXX_CAST_MAP() std::vector vector; int appendMillisecondDelay = 0; /** This method is called by the AppenderSkeleton#doAppend method. */ void append(const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& p) override; const std::vector& getVector() const { return this->vector; } void close() override; bool isClosed() const { return m_priv->closed; } bool requiresLayout() const override { return false; } void setMillisecondDelay(int milliseconds) { this->appendMillisecondDelay = milliseconds; } }; typedef std::shared_ptr VectorAppenderPtr; } apache-log4cxx-1.3.1/src/test/cpp/testchar.h0000644000175100001770000000222714721727031020215 0ustar runnerdocker/* * 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. */ #if !defined(_LOG4CXX_TESTCHAR_H) #define _LOG4CXX_TESTCHAR_H // // This macro and typedef lets many tests // check either the wchar_t or char based methods. // #if LOG4CXX_WCHAR_T_API && defined(LOG4CXX_TEST_WCHAR) #define LOG4CXX_TEST_STR(str) L ## str typedef wchar_t testchar; #else #define LOG4CXX_TEST_STR(str) str typedef char testchar; #endif #endif apache-log4cxx-1.3.1/src/test/cpp/appenderskeletontestcase.cpp0000644000175100001770000000303514721727031024030 0ustar runnerdocker/* * 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. */ #include "appenderskeletontestcase.h" #include "logunit.h" #include #include using namespace log4cxx; using namespace log4cxx::helpers; void AppenderSkeletonTestCase::testDefaultThreshold() { std::shared_ptr appender(createAppenderSkeleton()); LevelPtr threshold(appender->getThreshold()); LOGUNIT_ASSERT_EQUAL(Level::getAll()->toInt(), threshold->toInt()); } void AppenderSkeletonTestCase::testSetOptionThreshold() { std::shared_ptr appender(createAppenderSkeleton()); appender->setOption(LOG4CXX_STR("threshold"), LOG4CXX_STR("debug")); LevelPtr threshold(appender->getThreshold()); LOGUNIT_ASSERT_EQUAL(Level::getDebug()->toInt(), threshold->toInt()); } apache-log4cxx-1.3.1/src/test/cpp/xml/0000755000175100001770000000000014721727031017024 5ustar runnerdockerapache-log4cxx-1.3.1/src/test/cpp/xml/xlevel.h0000644000175100001770000000362114721727031020476 0ustar runnerdocker/* * 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. */ #include namespace LOG4CXX_NS { class XLevel : public Level { DECLARE_LOG4CXX_LEVEL(XLevel) public: enum { TRACE_INT = Level::DEBUG_INT - 1, LETHAL_INT = Level::FATAL_INT + 1 }; static LevelPtr getTrace(); static LevelPtr getLethal(); XLevel(int level, const LogString& name, int syslogEquivalent); /** Convert the string passed as argument to a level. If the conversion fails, then this method returns #DEBUG. */ static LevelPtr toLevelLS(const LogString& sArg); /** Convert an integer passed as argument to a level. If the conversion fails, then this method returns #DEBUG. */ static LevelPtr toLevel(int val); /** Convert an integer passed as argument to a level. If the conversion fails, then this method returns the specified default. */ static LevelPtr toLevel(int val, const LevelPtr& defaultLevel); /** Convert the string passed as argument to a level. If the conversion fails, then this method returns the value of defaultLevel. */ static LevelPtr toLevelLS(const LogString& sArg, const LevelPtr& defaultLevel); }; } apache-log4cxx-1.3.1/src/test/cpp/xml/xmllayouttestcase.cpp0000644000175100001770000002264514721727031023333 0ustar runnerdocker/* * 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. */ #include "../logunit.h" #include #include #include #include #include "../util/transformer.h" #include "../util/compare.h" #include "../util/xmltimestampfilter.h" #include "../util/xmllineattributefilter.h" #include "../util/xmlthreadfilter.h" #include "../util/filenamefilter.h" #include #include #include "../testchar.h" #include using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::xml; #if defined(__LOG4CXX_FUNC__) #undef __LOG4CXX_FUNC__ #define __LOG4CXX_FUNC__ "X::X()" #else #error __LOG4CXX_FUNC__ expected to be defined #endif class X { public: X() { LoggerPtr logger = Logger::getLogger(LOG4CXX_TEST_STR("org.apache.log4j.xml.XMLLayoutTestCase$X")); LOG4CXX_INFO(logger, LOG4CXX_TEST_STR("in X() constructor")); } }; LOGUNIT_CLASS(XMLLayoutTestCase) { LOGUNIT_TEST_SUITE(XMLLayoutTestCase); LOGUNIT_TEST(basic); LOGUNIT_TEST(locationInfo); LOGUNIT_TEST(testCDATA); LOGUNIT_TEST(testNull); LOGUNIT_TEST(testMDC); LOGUNIT_TEST(testMDCEscaped); LOGUNIT_TEST_SUITE_END(); LoggerPtr root; LoggerPtr logger; public: void setUp() { root = Logger::getRootLogger(); root->setLevel(Level::getTrace()); logger = Logger::getLogger(LOG4CXX_TEST_STR("org.apache.log4j.xml.XMLLayoutTestCase")); logger->setLevel(Level::getTrace()); } void tearDown() { auto rep = logger->getLoggerRepository(); if (rep) { rep->resetConfiguration(); } } void basic() { const LogString tempFileName(LOG4CXX_STR("output/temp.xmlLayout.1")); const File filteredFile("output/filtered.xmlLayout.1"); XMLLayoutPtr xmlLayout = XMLLayoutPtr(new XMLLayout()); AppenderPtr appender(new FileAppender(xmlLayout, tempFileName, false)); root->addAppender(appender); common(); XMLTimestampFilter xmlTimestampFilter; XMLThreadFilter xmlThreadFilter; std::vector filters; filters.push_back(&xmlThreadFilter); filters.push_back(&xmlTimestampFilter); try { Transformer::transform(tempFileName, filteredFile, filters); } catch (UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(filteredFile, LOG4CXX_FILE("witness/xmlLayout.1"))); } void locationInfo() { const LogString tempFileName(LOG4CXX_STR("output/temp.xmlLayout.2")); const File filteredFile("output/filtered.xmlLayout.2"); XMLLayoutPtr xmlLayout = XMLLayoutPtr(new XMLLayout()); xmlLayout->setLocationInfo(true); root->addAppender(AppenderPtr(new FileAppender(xmlLayout, tempFileName, false))); common(); XMLTimestampFilter xmlTimestampFilter; XMLThreadFilter xmlThreadFilter; FilenameFilter xmlFilenameFilter(__FILE__, "XMLLayoutTestCase.java"); Filter line2XX("[23][0-9][0-9]", "X"); Filter line5X("5[0-9]", "X"); std::vector filters; filters.push_back(&xmlFilenameFilter); filters.push_back(&xmlThreadFilter); filters.push_back(&xmlTimestampFilter); filters.push_back(&line2XX); filters.push_back(&line5X); try { Transformer::transform(tempFileName, filteredFile, filters); } catch (UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(filteredFile, LOG4CXX_FILE("witness/xmlLayout.2"))); } #undef __LOG4CXX_FUNC__ #define __LOG4CXX_FUNC__ "void XMLLayoutTestCase::testCDATA()" void testCDATA() { const LogString tempFileName(LOG4CXX_STR("output/temp.xmlLayout.3")); const File filteredFile("output/filtered.xmlLayout.3"); XMLLayoutPtr xmlLayout = XMLLayoutPtr(new XMLLayout()); xmlLayout->setLocationInfo(true); FileAppenderPtr appender(new FileAppender(xmlLayout, tempFileName, false)); root->addAppender(appender); LOG4CXX_TRACE(logger, LOG4CXX_TEST_STR("Message with embedded hi]]>.")); LOG4CXX_DEBUG(logger, LOG4CXX_TEST_STR("Message with embedded hi]]>.")); XMLTimestampFilter xmlTimestampFilter; XMLThreadFilter xmlThreadFilter; FilenameFilter xmlFilenameFilter(__FILE__, "XMLLayoutTestCase.java"); Filter line1xx("1[0-9][0-9]", "X"); std::vector filters; filters.push_back(&xmlFilenameFilter); filters.push_back(&xmlThreadFilter); filters.push_back(&xmlTimestampFilter); filters.push_back(&line1xx); try { Transformer::transform(tempFileName, filteredFile, filters); } catch (UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(filteredFile, LOG4CXX_FILE("witness/xmlLayout.3"))); } void testNull() { const LogString tempFileName(LOG4CXX_STR("output/temp.xmlLayout.null")); const File filteredFile("output/filtered.xmlLayout.null"); XMLLayoutPtr xmlLayout = XMLLayoutPtr(new XMLLayout()); FileAppenderPtr appender(new FileAppender(xmlLayout, tempFileName, false)); root->addAppender(appender); LOG4CXX_DEBUG(logger, LOG4CXX_TEST_STR("hi")); LOG4CXX_DEBUG(logger, (char*) 0); LOG4CXX_DEBUG(logger, "hi"); XMLTimestampFilter xmlTimestampFilter; XMLThreadFilter xmlThreadFilter; std::vector filters; filters.push_back(&xmlThreadFilter); filters.push_back(&xmlTimestampFilter); try { Transformer::transform(tempFileName, filteredFile, filters); } catch (UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(filteredFile, LOG4CXX_FILE("witness/xmlLayout.null"))); } void testMDC() { const LogString tempFileName(LOG4CXX_STR("output/temp.xmlLayout.mdc.1")); const File filteredFile("output/filtered.xmlLayout.mdc.1"); XMLLayoutPtr xmlLayout = XMLLayoutPtr(new XMLLayout()); xmlLayout->setProperties(true); FileAppenderPtr appender(new FileAppender(xmlLayout, tempFileName, false)); root->addAppender(appender); MDC::clear(); MDC::put(LOG4CXX_TEST_STR("key1"), LOG4CXX_TEST_STR("val1")); MDC::put(LOG4CXX_TEST_STR("key2"), LOG4CXX_TEST_STR("val2")); LOG4CXX_DEBUG(logger, LOG4CXX_TEST_STR("Hello")); MDC::clear(); XMLTimestampFilter xmlTimestampFilter; XMLThreadFilter xmlThreadFilter; std::vector filters; filters.push_back(&xmlThreadFilter); filters.push_back(&xmlTimestampFilter); try { Transformer::transform(tempFileName, filteredFile, filters); } catch (UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(filteredFile, LOG4CXX_FILE("witness/xmlLayout.mdc.1"))); } // not incuded in the tests for the moment ! void testMDCEscaped() { const LogString tempFileName(LOG4CXX_STR("output/temp.xmlLayout.mdc.2")); const File filteredFile("output/filtered.xmlLayout.mdc.2"); XMLLayoutPtr xmlLayout = XMLLayoutPtr(new XMLLayout()); xmlLayout->setProperties(true); FileAppenderPtr appender(new FileAppender(xmlLayout, tempFileName, false)); root->addAppender(appender); MDC::clear(); MDC::put(LOG4CXX_TEST_STR("blahAttribute"), LOG4CXX_TEST_STR("")); MDC::put(LOG4CXX_TEST_STR(""), LOG4CXX_TEST_STR("blahValue")); LOG4CXX_DEBUG(logger, LOG4CXX_TEST_STR("Hello")); MDC::clear(); XMLTimestampFilter xmlTimestampFilter; XMLThreadFilter xmlThreadFilter; std::vector filters; filters.push_back(&xmlThreadFilter); filters.push_back(&xmlTimestampFilter); try { Transformer::transform(tempFileName, filteredFile, filters); } catch (UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(filteredFile, LOG4CXX_FILE("witness/xmlLayout.mdc.2"))); } #undef __LOG4CXX_FUNC__ #define __LOG4CXX_FUNC__ "void XMLLayoutTestCase::common()" void common() { int i = 0; X x; std::string msg("Message "); LOG4CXX_TRACE(logger, msg << i); LOG4CXX_TRACE(root, msg << i); i++; LOG4CXX_DEBUG(logger, msg << i); LOG4CXX_DEBUG(root, msg << i); i++; LOG4CXX_INFO(logger, msg << i); LOG4CXX_INFO(root, msg << i); i++; LOG4CXX_WARN(logger, msg << i); LOG4CXX_WARN(root, msg << i); i++; LOG4CXX_ERROR(logger, msg << i); LOG4CXX_ERROR(root, msg << i); i++; LOG4CXX_FATAL(logger, msg << i); LOG4CXX_FATAL(root, msg << i); i++; LOG4CXX_DEBUG(logger, "Message " << i); LOG4CXX_DEBUG(root, "Message " << i); i++; LOG4CXX_ERROR(logger, "Message " << i); LOG4CXX_ERROR(root, "Message " << i); } }; LOGUNIT_TEST_SUITE_REGISTRATION(XMLLayoutTestCase); apache-log4cxx-1.3.1/src/test/cpp/xml/customleveltestcase.cpp0000644000175100001770000000635514721727031023637 0ustar runnerdocker/* * 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. */ #define LOG4CXX_TEST 1 #include #include "../logunit.h" #include #include #include #include #include #include "../util/compare.h" #include "xlevel.h" #include "../testchar.h" using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::xml; LOGUNIT_CLASS(CustomLevelTestCase) { LOGUNIT_TEST_SUITE(CustomLevelTestCase); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST(test3); LOGUNIT_TEST(test4); LOGUNIT_TEST_SUITE_END(); LoggerPtr root; LoggerPtr logger; static const File TEMP; public: void setUp() { root = Logger::getRootLogger(); logger = Logger::getLogger(LOG4CXX_TEST_STR("xml.CustomLevelTestCase")); } void tearDown() { root->getLoggerRepository()->resetConfiguration(); LoggerPtr logger1 = Logger::getLogger(LOG4CXX_TEST_STR("LOG4J")); logger1->setAdditivity(false); logger1->addAppender( new ConsoleAppender(new PatternLayout(LOG4CXX_STR("log4j: %-22c{2} - %m%n")))); } void test1() { DOMConfigurator::configure(LOG4CXX_TEST_STR("input/xml/customLevel1.xml")); common(); const File witness("witness/customLevel.1"); LOGUNIT_ASSERT(Compare::compare(TEMP, witness)); } void test2() { DOMConfigurator::configure(LOG4CXX_TEST_STR("input/xml/customLevel2.xml")); common(); const File witness("witness/customLevel.2"); LOGUNIT_ASSERT(Compare::compare(TEMP, witness)); } void test3() { DOMConfigurator::configure(LOG4CXX_TEST_STR("input/xml/customLevel3.xml")); common(); const File witness("witness/customLevel.3"); LOGUNIT_ASSERT(Compare::compare(TEMP, witness)); } void test4() { DOMConfigurator::configure(LOG4CXX_TEST_STR("input/xml/customLevel4.xml")); common(); const File witness("witness/customLevel.4"); LOGUNIT_ASSERT(Compare::compare(TEMP, witness)); } void common() { int i = 0; std::ostringstream os; os << "Message " << ++i; LOG4CXX_DEBUG(logger, os.str()); os.str(""); os << "Message " << ++i; LOG4CXX_INFO(logger, os.str()); os.str(""); os << "Message " << ++i; LOG4CXX_WARN(logger, os.str()); os.str(""); os << "Message " << ++i; LOG4CXX_ERROR(logger, os.str()); os.str(""); os << "Message " << ++i; LOG4CXX_LOG(logger, XLevel::getTrace(), os.str()); } }; LOGUNIT_TEST_SUITE_REGISTRATION(CustomLevelTestCase); const File CustomLevelTestCase::TEMP("output/temp"); apache-log4cxx-1.3.1/src/test/cpp/xml/xlevel.cpp0000644000175100001770000000414314721727031021031 0ustar runnerdocker/* * 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. */ #include "xlevel.h" #include using namespace log4cxx; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_LEVEL(XLevel) XLevel::XLevel(int level1, const LogString& name1, int syslogEquivalent1) : Level(level1, name1, syslogEquivalent1) { } LevelPtr XLevel::getTrace() { static const LevelPtr trace(new XLevel(XLevel::TRACE_INT, LOG4CXX_STR("TRACE"), 7)); return trace; } LevelPtr XLevel::getLethal() { static const LevelPtr lethal(new XLevel(XLevel::LETHAL_INT, LOG4CXX_STR("LETHAL"), 0)); return lethal; } LevelPtr XLevel::toLevelLS(const LogString& sArg) { return toLevelLS(sArg, getTrace()); } LevelPtr XLevel::toLevel(int val) { return toLevel(val, getTrace()); } LevelPtr XLevel::toLevel(int val, const LevelPtr& defaultLevel) { switch (val) { case TRACE_INT: return getTrace(); case LETHAL_INT: return getLethal(); default: return defaultLevel; } } LevelPtr XLevel::toLevelLS(const LogString& sArg, const LevelPtr& defaultLevel) { if (sArg.empty()) { return defaultLevel; } if (StringHelper::equalsIgnoreCase(sArg, LOG4CXX_STR("TRACE"), LOG4CXX_STR("trace"))) { return getTrace(); } if (StringHelper::equalsIgnoreCase(sArg, LOG4CXX_STR("LETHAL"), LOG4CXX_STR("lethal"))) { return getLethal(); } return Level::toLevel(sArg, defaultLevel); } apache-log4cxx-1.3.1/src/test/cpp/xml/CMakeLists.txt0000644000175100001770000000200614721727031021562 0ustar runnerdocker# # 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. # add_executable(xmltests domtestcase.cpp xmllayouttest.cpp xmllayouttestcase.cpp ) target_link_libraries(xmltests PRIVATE ${APR_UTIL_LIBRARIES} ${EXPAT_LIBRARIES}) set(ALL_LOG4CXX_TESTS ${ALL_LOG4CXX_TESTS} xmltests PARENT_SCOPE) apache-log4cxx-1.3.1/src/test/cpp/xml/domtestcase.cpp0000644000175100001770000001564414721727031022055 0ustar runnerdocker/* * 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. */ #include #include #include "../logunit.h" #include "../util/compare.h" #include "xlevel.h" #include "../util/controlfilter.h" #include "../util/iso8601filter.h" #include "../util/threadfilter.h" #include "../util/transformer.h" #include #include #include #include #include #include "../testchar.h" #include "log4cxx/helpers/loglog.h" using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::xml; #define TEST1_1A_PAT \ "(DEBUG|INFO |WARN |ERROR|FATAL) \\w*\\.\\w* - Message [0-9]" #define TEST1_1B_PAT "(DEBUG|INFO |WARN |ERROR|FATAL) root - Message [0-9]" #define TEST1_2_PAT "^[0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [0-9]\\{2\\}:[0-9]\\{2\\}:[0-9]\\{2\\},[0-9]\\{3\\} " \ "\\[0x[0-9A-F]*]\\ (DEBUG|INFO|WARN|ERROR|FATAL) .* - Message [0-9]" LOGUNIT_CLASS(DOMTestCase) { LOGUNIT_TEST_SUITE(DOMTestCase); LOGUNIT_TEST(test1); #if defined(_WIN32) LOGUNIT_TEST(test2); #endif LOGUNIT_TEST(test3); LOGUNIT_TEST(test4); LOGUNIT_TEST_SUITE_END(); LoggerPtr root; LoggerPtr logger; static const File TEMP_A1; static const File TEMP_A2; static const File FILTERED_A1; static const File FILTERED_A2; static const File TEMP_A1_2; static const File TEMP_A2_2; static const File FILTERED_A1_2; static const File FILTERED_A2_2; public: void setUp() { root = Logger::getRootLogger(); logger = Logger::getLogger(LOG4CXX_TEST_STR("org.apache.log4j.xml.DOMTestCase")); } void tearDown() { auto rep = root->getLoggerRepository(); if (rep) { rep->resetConfiguration(); } } void test1() { LogLog::setInternalDebugging(true); DOMConfigurator::configure(LOG4CXX_TEST_STR("input/xml/DOMTestCase1.xml")); common(); ControlFilter cf1; cf1 << TEST1_1A_PAT << TEST1_1B_PAT; ControlFilter cf2; cf2 << TEST1_2_PAT; ThreadFilter threadFilter; ISO8601Filter iso8601Filter; std::vector filters1; filters1.push_back(&cf1); std::vector filters2; filters2.push_back(&cf2); filters2.push_back(&threadFilter); filters2.push_back(&iso8601Filter); try { Transformer::transform(TEMP_A1, FILTERED_A1, filters1); Transformer::transform(TEMP_A2, FILTERED_A2, filters2); } catch (UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } const File witness1(LOG4CXX_TEST_STR("witness/dom.A1.1")); const File witness2(LOG4CXX_TEST_STR("witness/dom.A2.1")); // TODO: A1 doesn't contain duplicate entries // // LOGUNIT_ASSERT(Compare::compare(FILTERED_A1, witness1)); LOGUNIT_ASSERT(Compare::compare(FILTERED_A2, witness2)); } // // Same test but backslashes instead of forward // void test2() { DOMConfigurator::configure(LOG4CXX_TEST_STR("input\\xml\\DOMTestCase2.xml")); common(); ThreadFilter threadFilter; ISO8601Filter iso8601Filter; std::vector filters1; std::vector filters2; filters2.push_back(&threadFilter); filters2.push_back(&iso8601Filter); try { Transformer::transform(TEMP_A1_2, FILTERED_A1_2, filters1); Transformer::transform(TEMP_A2_2, FILTERED_A2_2, filters2); } catch (UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } const File witness1(LOG4CXX_TEST_STR("witness/dom.A1.2")); const File witness2(LOG4CXX_TEST_STR("witness/dom.A2.2")); // TODO: A1 doesn't contain duplicate entries // // LOGUNIT_ASSERT(Compare::compare(FILTERED_A1, witness1)); LOGUNIT_ASSERT(Compare::compare(FILTERED_A2, witness2)); } void common() { int i = 0; LOG4CXX_DEBUG(logger, "Message " << i); LOG4CXX_DEBUG(root, "Message " << i); i++; LOG4CXX_INFO(logger, "Message " << i); LOG4CXX_INFO(root, "Message " << i); i++; LOG4CXX_WARN(logger, "Message " << i); LOG4CXX_WARN(root, "Message " << i); i++; LOG4CXX_ERROR(logger, "Message " << i); LOG4CXX_ERROR(root, "Message " << i); i++; LOG4CXX_FATAL(logger, "Message " << i); LOG4CXX_FATAL(root, "Message " << i); } /** * Creates a output file that ends with a superscript 3. * Output file is checked by build.xml after completion. */ void test3() { DOMConfigurator::configure(LOG4CXX_TEST_STR("input/xml/DOMTestCase3.xml")); LOG4CXX_INFO(logger, "File name is expected to end with a superscript 3"); #if LOG4CXX_LOGCHAR_IS_UTF8 const logchar fname[] = { 0x6F, 0x75, 0x74, 0x70, 0x75, 0x74, 0x2F, 0x64, 0x6F, 0x6D, static_cast(0xC2), static_cast(0xB3), 0 }; #else const logchar fname[] = { 0x6F, 0x75, 0x74, 0x70, 0x75, 0x74, 0x2F, 0x64, 0x6F, 0x6D, static_cast(0xB3), 0 }; #endif File file; file.setPath(fname); Pool p; bool exists = file.exists(p); LOGUNIT_ASSERT(exists); } /** * Creates a output file that ends with a ideographic 4. * Output file is checked by build.xml after completion. */ void test4() { DOMConfigurator::configure(LOG4CXX_TEST_STR("input/xml/DOMTestCase4.xml")); LOG4CXX_INFO(logger, "File name is expected to end with an ideographic 4"); #if LOG4CXX_LOGCHAR_IS_UTF8 const logchar fname[] = { 0x6F, 0x75, 0x74, 0x70, 0x75, 0x74, 0x2F, 0x64, 0x6F, 0x6D, static_cast(0xE3), static_cast(0x86), static_cast(0x95), 0 }; #else const logchar fname[] = { 0x6F, 0x75, 0x74, 0x70, 0x75, 0x74, 0x2F, 0x64, 0x6F, 0x6D, static_cast(0x3195), 0 }; #endif File file; file.setPath(fname); Pool p; bool exists = file.exists(p); LOGUNIT_ASSERT(exists); } }; LOGUNIT_TEST_SUITE_REGISTRATION(DOMTestCase); const File DOMTestCase::TEMP_A1(LOG4CXX_TEST_STR("output/temp.A1")); const File DOMTestCase::TEMP_A2(LOG4CXX_TEST_STR("output/temp.A2")); const File DOMTestCase::FILTERED_A1(LOG4CXX_TEST_STR("output/filtered.A1")); const File DOMTestCase::FILTERED_A2(LOG4CXX_TEST_STR("output/filtered.A2")); const File DOMTestCase::TEMP_A1_2(LOG4CXX_TEST_STR("output/temp.A1.2")); const File DOMTestCase::TEMP_A2_2(LOG4CXX_TEST_STR("output/temp.A2.2")); const File DOMTestCase::FILTERED_A1_2(LOG4CXX_TEST_STR("output/filtered.A1.2")); const File DOMTestCase::FILTERED_A2_2(LOG4CXX_TEST_STR("output/filtered.A2.2")); apache-log4cxx-1.3.1/src/test/cpp/xml/xmllayouttest.cpp0000644000175100001770000002664214721727031022500 0ustar runnerdocker/* * 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. */ #include "../logunit.h" #include #include #include #include #include "../util/transformer.h" #include "../util/compare.h" #include "../util/xmltimestampfilter.h" #include "../util/xmllineattributefilter.h" #include "../util/xmlthreadfilter.h" #include "../util/filenamefilter.h" #include #include #include "../testchar.h" #include #include #include #include #include "../xml/xlevel.h" #include #include using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::xml; using namespace log4cxx::spi; #if defined(__LOG4CXX_FUNC__) #undef __LOG4CXX_FUNC__ #define __LOG4CXX_FUNC__ "X::X()" #else #error __LOG4CXX_FUNC__ expected to be defined #endif /** * Test for XMLLayout. * */ LOGUNIT_CLASS(XMLLayoutTest) { LOGUNIT_TEST_SUITE(XMLLayoutTest); LOGUNIT_TEST(testGetContentType); LOGUNIT_TEST(testIgnoresThrowable); LOGUNIT_TEST(testGetHeader); LOGUNIT_TEST(testGetFooter); LOGUNIT_TEST(testFormat); LOGUNIT_TEST(testFormatWithNDC); LOGUNIT_TEST(testGetSetLocationInfo); LOGUNIT_TEST(testActivateOptions); LOGUNIT_TEST(testProblemCharacters); LOGUNIT_TEST(testNDCWithCDATA); LOGUNIT_TEST_SUITE_END(); public: /** * Clear MDC and NDC before test. */ void setUp() { NDC::clear(); MDC::clear(); } /** * Clear MDC and NDC after test. */ void tearDown() { setUp(); } public: /** * Tests getContentType. */ void testGetContentType() { LogString expected(LOG4CXX_STR("text/plain")); LogString actual(XMLLayout().getContentType()); LOGUNIT_ASSERT(expected == actual); } /** * Tests ignoresThrowable. */ void testIgnoresThrowable() { LOGUNIT_ASSERT_EQUAL(false, XMLLayout().ignoresThrowable()); } /** * Tests getHeader. */ void testGetHeader() { Pool p; LogString header; XMLLayout().appendHeader(header, p); LOGUNIT_ASSERT_EQUAL((size_t) 0, header.size()); } /** * Tests getFooter. */ void testGetFooter() { Pool p; LogString footer; XMLLayout().appendFooter(footer, p); LOGUNIT_ASSERT_EQUAL((size_t) 0, footer.size()); } private: /** * 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. */ static apr_xml_elem* parse(const LogString & source, Pool & p) { char backing[3000]; ByteBuffer buf(backing, sizeof(backing)); CharsetEncoderPtr encoder(CharsetEncoder::getUTF8Encoder()); LogString header(LOG4CXX_STR("")); LogString::const_iterator iter(header.begin()); encoder->encode(header, iter, buf); LOGUNIT_ASSERT(iter == header.end()); iter = source.begin(); encoder->encode(source, iter, buf); LOGUNIT_ASSERT(iter == source.end()); LogString footer(LOG4CXX_STR("")); iter = footer.begin(); encoder->encode(footer, iter, buf); buf.flip(); apr_pool_t* apr_pool = p.getAPRPool(); apr_xml_parser* parser = apr_xml_parser_create(apr_pool); LOGUNIT_ASSERT(parser != 0); apr_status_t stat = apr_xml_parser_feed(parser, buf.data(), buf.remaining()); LOGUNIT_ASSERT(stat == APR_SUCCESS); apr_xml_doc* doc = 0; stat = apr_xml_parser_done(parser, &doc); LOGUNIT_ASSERT(doc != 0); apr_xml_elem* eventSet = doc->root; LOGUNIT_ASSERT(eventSet != 0); apr_xml_elem* event = eventSet->first_child; LOGUNIT_ASSERT(event != 0); return event; } std::string getAttribute(apr_xml_elem * elem, const char* attrName) { for (apr_xml_attr* attr = elem->attr; attr != NULL; attr = attr->next) { if (strcmp(attr->name, attrName) == 0) { return attr->value; } } return ""; } std::string getText(apr_xml_elem * elem) { std::string dMessage; for (apr_text* t = elem->first_cdata.first; t != NULL; t = t->next) { dMessage.append(t->text); } return dMessage; } /** * Checks a log4j:event element against expectations. * @param element element, may not be null. * @param event event, may not be null. */ void checkEventElement( apr_xml_elem * element, LoggingEventPtr & event) { std::string tagName("event"); LOGUNIT_ASSERT_EQUAL(tagName, (std::string) element->name); LOG4CXX_ENCODE_CHAR(cLoggerName, event->getLoggerName()); LOGUNIT_ASSERT_EQUAL(cLoggerName, getAttribute(element, "logger")); LOG4CXX_ENCODE_CHAR(cLevelName, event->getLevel()->toString()); LOGUNIT_ASSERT_EQUAL(cLevelName, getAttribute(element, "level")); } /** * Checks a log4j:message element against expectations. * @param element element, may not be null. * @param message expected message. */ void checkMessageElement( apr_xml_elem * element, std::string message) { std::string tagName = "message"; LOGUNIT_ASSERT_EQUAL(tagName, (std::string) element->name); LOGUNIT_ASSERT_EQUAL(message, getText(element)); } /** * Checks a log4j:message element against expectations. * @param element element, may not be null. * @param message expected message. */ void checkNDCElement(apr_xml_elem * element, std::string message) { std::string tagName = "NDC"; LOGUNIT_ASSERT_EQUAL(tagName, (std::string) element->name); std::string dMessage = getText(element); LOGUNIT_ASSERT_EQUAL(message, dMessage); } /** * Checks a log4j:properties element against expectations. * @param element element, may not be null. * @param key key. * @param value value. */ void checkPropertiesElement( apr_xml_elem * element, std::string key, std::string value) { std::string tagName = "properties"; std::string dataTag = "data"; int childNodeCount = 0; LOGUNIT_ASSERT_EQUAL(tagName, (std::string) element->name); for (apr_xml_elem* child = element->first_child; child != NULL; child = child->next) { LOGUNIT_ASSERT_EQUAL(dataTag, (std::string) child->name); LOGUNIT_ASSERT_EQUAL(key, getAttribute(child, "name")); LOGUNIT_ASSERT_EQUAL(value, getAttribute(child, "value")); childNodeCount++; } LOGUNIT_ASSERT_EQUAL(1, childNodeCount); } public: /** * Tests formatted results. * @throws Exception if parser can not be constructed or source is not a valid XML document. */ void testFormat() { LogString logger = LOG4CXX_STR("org.apache.log4j.xml.XMLLayoutTest"); LoggingEventPtr event = LoggingEventPtr( new LoggingEvent( logger, Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); Pool p; XMLLayout layout; LogString result; layout.format(result, event, p); apr_xml_elem* parsedResult = parse(result, p); checkEventElement(parsedResult, event); int childElementCount = 0; for ( apr_xml_elem* node = parsedResult->first_child; node != NULL; node = node->next) { childElementCount++; checkMessageElement(node, "Hello, World"); } LOGUNIT_ASSERT_EQUAL(1, childElementCount); } /** * Tests formatted results with an exception. * @throws Exception if parser can not be constructed or source is not a valid XML document. */ void testFormatWithNDC() { LogString logger = LOG4CXX_STR("org.apache.log4j.xml.XMLLayoutTest"); NDC::push("NDC goes here"); LoggingEventPtr event = LoggingEventPtr( new LoggingEvent( logger, Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); Pool p; XMLLayout layout; LogString result; layout.format(result, event, p); NDC::pop(); apr_xml_elem* parsedResult = parse(result, p); checkEventElement(parsedResult, event); int childElementCount = 0; for ( apr_xml_elem* node = parsedResult->first_child; node != NULL; node = node->next) { childElementCount++; if (childElementCount == 1) { checkMessageElement(node, "Hello, World"); } else { checkNDCElement(node, "NDC goes here"); } } LOGUNIT_ASSERT_EQUAL(2, childElementCount); } /** * Tests getLocationInfo and setLocationInfo. */ void testGetSetLocationInfo() { XMLLayout layout; LOGUNIT_ASSERT_EQUAL(false, layout.getLocationInfo()); layout.setLocationInfo(true); LOGUNIT_ASSERT_EQUAL(true, layout.getLocationInfo()); layout.setLocationInfo(false); LOGUNIT_ASSERT_EQUAL(false, layout.getLocationInfo()); } /** * Tests activateOptions(). */ void testActivateOptions() { Pool p; XMLLayout layout; layout.activateOptions(p); } /** * Tests problematic characters in multiple fields. * @throws Exception if parser can not be constructed or source is not a valid XML document. */ void testProblemCharacters() { std::string problemName = "com.example.bar<>&\"'"; LogString problemNameLS = LOG4CXX_STR("com.example.bar<>&\"'"); LevelPtr level = LevelPtr(new XLevel(6000, problemNameLS, 7)); NDC::push(problemName); MDC::clear(); MDC::put(problemName, problemName); LoggingEventPtr event = LoggingEventPtr( new LoggingEvent(problemNameLS, level, problemNameLS, LOG4CXX_LOCATION)); XMLLayout layout; layout.setProperties(true); Pool p; LogString result; layout.format(result, event, p); MDC::clear(); apr_xml_elem* parsedResult = parse(result, p); checkEventElement(parsedResult, event); int childElementCount = 0; for ( apr_xml_elem* node = parsedResult->first_child; node != NULL; node = node->next) { childElementCount++; switch (childElementCount) { case 1: checkMessageElement(node, problemName); break; case 2: checkNDCElement(node, problemName); break; case 3: checkPropertiesElement(node, problemName.c_str(), problemName.c_str()); break; default: break; } } LOGUNIT_ASSERT_EQUAL(3, childElementCount); } /** * Tests CDATA element within NDC content. See bug 37560. */ void testNDCWithCDATA() { LogString logger = LOG4CXX_STR("com.example.bar"); LevelPtr level = Level::getInfo(); std::string ndcMessage = ""; NDC::push(ndcMessage); LoggingEventPtr event = LoggingEventPtr( new LoggingEvent( logger, level, LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); XMLLayout layout; Pool p; LogString result; layout.format(result, event, p); NDC::clear(); apr_xml_elem* parsedResult = parse(result, p); int ndcCount = 0; for (apr_xml_elem* node = parsedResult->first_child; node != NULL; node = node->next) { if (strcmp(node->name, "NDC") == 0) { ndcCount++; LOGUNIT_ASSERT_EQUAL(ndcMessage, getText(node)); } } LOGUNIT_ASSERT_EQUAL(1, ndcCount); } }; LOGUNIT_TEST_SUITE_REGISTRATION(XMLLayoutTest); apache-log4cxx-1.3.1/src/test/cpp/writerappendertestcase.cpp0000644000175100001770000000202714721727031023520 0ustar runnerdocker/* * 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. */ #include "writerappendertestcase.h" #include using namespace log4cxx; using namespace log4cxx::helpers; AppenderSkeleton* WriterAppenderTestCase::createAppenderSkeleton() const { return createWriterAppender(); } apache-log4cxx-1.3.1/src/test/cpp/propertyconfiguratortest.cpp0000644000175100001770000000730314721727031024142 0ustar runnerdocker/* * 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. */ #include #include #include #include "vectorappender.h" #include "logunit.h" using namespace log4cxx; using namespace log4cxx::helpers; LOGUNIT_CLASS(PropertyConfiguratorTest) { LOGUNIT_TEST_SUITE(PropertyConfiguratorTest); LOGUNIT_TEST(testInherited); LOGUNIT_TEST(testNull); LOGUNIT_TEST(testAppenderThreshold); LOGUNIT_TEST_SUITE_END(); public: void testInherited() { Properties props; props.put(LOG4CXX_STR("log4j.rootLogger"), LOG4CXX_STR("DEBUG,VECTOR1")); props.put(LOG4CXX_STR("log4j.logger.org.apache.log4j.PropertyConfiguratorTest"), LOG4CXX_STR("inherited,VECTOR2")); props.put(LOG4CXX_STR("log4j.appender.VECTOR1"), LOG4CXX_STR("org.apache.log4j.VectorAppender")); props.put(LOG4CXX_STR("log4j.appender.VECTOR2"), LOG4CXX_STR("org.apache.log4j.VectorAppender")); PropertyConfigurator::configure(props); LoggerPtr logger = Logger::getLogger("org.apache.log4j.PropertyConfiguratorTest"); LOGUNIT_ASSERT_EQUAL((int) Level::DEBUG_INT, logger->getEffectiveLevel()->toInt()); Logger::getRootLogger()->setLevel(Level::getError()); LOGUNIT_ASSERT_EQUAL((int) Level::ERROR_INT, logger->getEffectiveLevel()->toInt()); LogManager::resetConfiguration(); } void testNull() { Properties props; props.put(LOG4CXX_STR("log4j.rootLogger"), LOG4CXX_STR("DEBUG,VECTOR1")); props.put(LOG4CXX_STR("log4j.logger.org.apache.log4j.PropertyConfiguratorTest"), LOG4CXX_STR("NuLL,VECTOR2")); props.put(LOG4CXX_STR("log4j.appender.VECTOR1"), LOG4CXX_STR("org.apache.log4j.VectorAppender")); props.put(LOG4CXX_STR("log4j.appender.VECTOR2"), LOG4CXX_STR("org.apache.log4j.VectorAppender")); PropertyConfigurator::configure(props); LoggerPtr logger = Logger::getLogger("org.apache.log4j.PropertyConfiguratorTest"); LOGUNIT_ASSERT_EQUAL((int) Level::DEBUG_INT, logger->getEffectiveLevel()->toInt()); Logger::getRootLogger()->setLevel(Level::getError()); LOGUNIT_ASSERT_EQUAL((int) Level::ERROR_INT, logger->getEffectiveLevel()->toInt()); LogManager::resetConfiguration(); } void testAppenderThreshold() { Properties props; props.put(LOG4CXX_STR("log4j.rootLogger"), LOG4CXX_STR("ALL,VECTOR1")); props.put(LOG4CXX_STR("log4j.appender.VECTOR1"), LOG4CXX_STR("org.apache.log4j.VectorAppender")); props.put(LOG4CXX_STR("log4j.appender.VECTOR1.threshold"), LOG4CXX_STR("WARN")); PropertyConfigurator::configure(props); LoggerPtr root(Logger::getRootLogger()); VectorAppenderPtr appender = log4cxx::cast(root->getAppender(LOG4CXX_STR("VECTOR1"))); LOGUNIT_ASSERT_EQUAL((int) Level::WARN_INT, appender->getThreshold()->toInt()); LOG4CXX_INFO(root, "Info message"); LOG4CXX_WARN(root, "Warn message"); LOG4CXX_WARN(root, "Error message"); LOGUNIT_ASSERT_EQUAL((size_t) 2, appender->vector.size()); LogManager::resetConfiguration(); } }; LOGUNIT_TEST_SUITE_REGISTRATION(PropertyConfiguratorTest); apache-log4cxx-1.3.1/src/test/cpp/helpers/0000755000175100001770000000000014721727031017666 5ustar runnerdockerapache-log4cxx-1.3.1/src/test/cpp/helpers/stringhelpertestcase.cpp0000644000175100001770000000664614721727031024650 0ustar runnerdocker/* * 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. */ #include #include #include "../insertwide.h" #include "../logunit.h" using namespace log4cxx; using namespace log4cxx::helpers; /** Unit test for StringHelper. */ LOGUNIT_CLASS(StringHelperTestCase) { LOGUNIT_TEST_SUITE( StringHelperTestCase ); LOGUNIT_TEST( testStartsWith1 ); LOGUNIT_TEST( testStartsWith2 ); LOGUNIT_TEST( testStartsWith3 ); LOGUNIT_TEST( testStartsWith4 ); LOGUNIT_TEST( testStartsWith5 ); LOGUNIT_TEST( testEndsWith1 ); LOGUNIT_TEST( testEndsWith2 ); LOGUNIT_TEST( testEndsWith3 ); LOGUNIT_TEST( testEndsWith4 ); LOGUNIT_TEST( testEndsWith5 ); LOGUNIT_TEST_SUITE_END(); public: /** * Check that startsWith("foobar", "foo") returns true. */ void testStartsWith1() { LOGUNIT_ASSERT_EQUAL(true, StringHelper::startsWith(LOG4CXX_STR("foobar"), LOG4CXX_STR("foo"))); } /** * Check that startsWith("bar", "foobar") returns false. */ void testStartsWith2() { LOGUNIT_ASSERT_EQUAL(false, StringHelper::startsWith(LOG4CXX_STR("foo"), LOG4CXX_STR("foobar"))); } /** * Check that startsWith("foobar", "foobar") returns true. */ void testStartsWith3() { LOGUNIT_ASSERT_EQUAL(true, StringHelper::startsWith(LOG4CXX_STR("foobar"), LOG4CXX_STR("foobar"))); } /** * Check that startsWith("foobar", "") returns true. */ void testStartsWith4() { LOGUNIT_ASSERT_EQUAL(true, StringHelper::startsWith(LOG4CXX_STR("foobar"), LOG4CXX_STR(""))); } /** * Check that startsWith("foobar", "abc") returns false. */ void testStartsWith5() { LOGUNIT_ASSERT_EQUAL(false, StringHelper::startsWith(LOG4CXX_STR("foobar"), LOG4CXX_STR("abc"))); } /** * Check that endsWith("foobar", "bar") returns true. */ void testEndsWith1() { LOGUNIT_ASSERT_EQUAL(true, StringHelper::endsWith(LOG4CXX_STR("foobar"), LOG4CXX_STR("bar"))); } /** * Check that endsWith("bar", "foobar") returns false. */ void testEndsWith2() { LOGUNIT_ASSERT_EQUAL(false, StringHelper::endsWith(LOG4CXX_STR("bar"), LOG4CXX_STR("foobar"))); } /** * Check that endsWith("foobar", "foobar") returns true. */ void testEndsWith3() { LOGUNIT_ASSERT_EQUAL(true, StringHelper::endsWith(LOG4CXX_STR("foobar"), LOG4CXX_STR("foobar"))); } /** * Check that endsWith("foobar", "") returns true. */ void testEndsWith4() { LOGUNIT_ASSERT_EQUAL(true, StringHelper::endsWith(LOG4CXX_STR("foobar"), LOG4CXX_STR(""))); } /** * Check that endsWith("foobar", "abc") returns false. */ void testEndsWith5() { LOGUNIT_ASSERT_EQUAL(false, StringHelper::startsWith(LOG4CXX_STR("foobar"), LOG4CXX_STR("abc"))); } }; LOGUNIT_TEST_SUITE_REGISTRATION(StringHelperTestCase); apache-log4cxx-1.3.1/src/test/cpp/helpers/localechanger.cpp0000644000175100001770000000317514721727031023167 0ustar runnerdocker/* * 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. */ #define LOG4CXX_TEST #include #include "log4cxx/helpers/loglog.h" #include "log4cxx/helpers/transcoder.h" #if LOG4CXX_HAS_STD_LOCALE #include "localechanger.h" #include using namespace log4cxx::helpers; /** * Construction attemtps to change default locale. * @param locale locale. */ LocaleChanger::LocaleChanger(const char* locale) { effective = false; try { std::locale newLocale(locale); initial = std::locale::global(newLocale); effective = true; } catch (std::exception& ex) { LOG4CXX_DECODE_CHAR(lsMsg, ex.what()); LogString errorMsg; errorMsg.append(lsMsg); errorMsg.append(LOG4CXX_STR(" - in LocaleChanger")); LogLog::error(errorMsg); } } /** * Restores previous locale. */ LocaleChanger::~LocaleChanger() { if (effective) { std::locale::global(initial); } } #endif apache-log4cxx-1.3.1/src/test/cpp/helpers/stringtokenizertestcase.cpp0000644000175100001770000000764514721727031025403 0ustar runnerdocker/* * 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. */ #include #include #include "../logunit.h" #include "../insertwide.h" using namespace log4cxx; using namespace log4cxx::helpers; LOGUNIT_CLASS(StringTokenizerTestCase) { LOGUNIT_TEST_SUITE(StringTokenizerTestCase); LOGUNIT_TEST(testNextTokenEmptyString); LOGUNIT_TEST(testHasMoreTokensEmptyString); LOGUNIT_TEST(testNextTokenAllDelim); LOGUNIT_TEST(testHasMoreTokensAllDelim); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST(test3); LOGUNIT_TEST(test4); LOGUNIT_TEST(test5); LOGUNIT_TEST(test6); LOGUNIT_TEST_SUITE_END(); public: void testNextTokenEmptyString() { LogString src; LogString delim(LOG4CXX_STR(" ")); StringTokenizer tokenizer(src, delim); try { LogString token(tokenizer.nextToken()); } catch (NoSuchElementException& ex) { return; } LOGUNIT_ASSERT(false); } void testHasMoreTokensEmptyString() { LogString src; LogString delim(LOG4CXX_STR(" ")); StringTokenizer tokenizer(src, delim); LOGUNIT_ASSERT_EQUAL(false, tokenizer.hasMoreTokens()); } void testNextTokenAllDelim() { LogString src(LOG4CXX_STR("===")); LogString delim(LOG4CXX_STR("=")); StringTokenizer tokenizer(src, delim); try { LogString token(tokenizer.nextToken()); } catch (NoSuchElementException& ex) { return; } LOGUNIT_ASSERT(false); } void testHasMoreTokensAllDelim() { LogString src(LOG4CXX_STR("===")); LogString delim(LOG4CXX_STR("=")); StringTokenizer tokenizer(src, delim); LOGUNIT_ASSERT_EQUAL(false, tokenizer.hasMoreTokens()); } void testBody(const LogString & src, const LogString & delim) { StringTokenizer tokenizer(src, delim); LOGUNIT_ASSERT_EQUAL(true, tokenizer.hasMoreTokens()); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("log4j"), tokenizer.nextToken()); LOGUNIT_ASSERT_EQUAL(true, tokenizer.hasMoreTokens()); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("properties"), tokenizer.nextToken()); LOGUNIT_ASSERT_EQUAL(true, tokenizer.hasMoreTokens()); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("txt"), tokenizer.nextToken()); LOGUNIT_ASSERT_EQUAL(false, tokenizer.hasMoreTokens()); try { LogString token(tokenizer.nextToken()); } catch (NoSuchElementException& ex) { return; } LOGUNIT_ASSERT(false); } void test1() { LogString src(LOG4CXX_STR("log4j.properties.txt")); LogString delim(LOG4CXX_STR(".")); testBody(src, delim); } void test2() { LogString src(LOG4CXX_STR(".log4j.properties.txt")); LogString delim(LOG4CXX_STR(".")); testBody(src, delim); } void test3() { LogString src(LOG4CXX_STR("log4j.properties.txt.")); LogString delim(LOG4CXX_STR(".")); testBody(src, delim); } void test4() { LogString src(LOG4CXX_STR("log4j..properties....txt")); LogString delim(LOG4CXX_STR(".")); testBody(src, delim); } void test5() { LogString src(LOG4CXX_STR("log4j properties,txt")); LogString delim(LOG4CXX_STR(" ,")); testBody(src, delim); } void test6() { LogString src(LOG4CXX_STR(" log4j properties,txt ")); LogString delim(LOG4CXX_STR(" ,")); testBody(src, delim); } }; LOGUNIT_TEST_SUITE_REGISTRATION(StringTokenizerTestCase); apache-log4cxx-1.3.1/src/test/cpp/helpers/inetaddresstestcase.cpp0000644000175100001770000000473014721727031024437 0ustar runnerdocker/* * 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. */ #include #include "../logunit.h" using namespace log4cxx; using namespace log4cxx::helpers; LOGUNIT_CLASS(InetAddressTestCase) { LOGUNIT_TEST_SUITE(InetAddressTestCase); LOGUNIT_TEST(testGetLocalHost); LOGUNIT_TEST(testByNameLocal); LOGUNIT_TEST(testAllByNameLocal); LOGUNIT_TEST(testUnreachable); LOGUNIT_TEST_SUITE_END(); public: /** * Tests the InetAddress::getLocalHost() method. */ void testGetLocalHost() { InetAddressPtr addr = InetAddress::getLocalHost(); LOGUNIT_ASSERT(addr->getHostAddress() == LOG4CXX_STR("127.0.0.1")); LOGUNIT_ASSERT(!addr->getHostName().empty()); } /** * Tests the InetAddress::getByName() method with the * "localhost" host name. */ void testByNameLocal() { InetAddressPtr addr = InetAddress::getByName(LOG4CXX_STR("localhost")); LOGUNIT_ASSERT(addr->getHostAddress() == LOG4CXX_STR("127.0.0.1")); LOGUNIT_ASSERT(!addr->getHostName().empty()); } /** * Tests the InetAddress::getAllByName() method with the * "localhost" host name. */ void testAllByNameLocal() { std::vector addr = InetAddress::getAllByName(LOG4CXX_STR("localhost")); LOGUNIT_ASSERT(addr.size() > 0); } /** * Tests the UnknownHostException. */ void testUnknownHost() { InetAddressPtr addr = InetAddress::getByName(LOG4CXX_STR("unknown.invalid")); } /** * Tests an (likely) unreachable address. */ void testUnreachable() { InetAddressPtr addr(InetAddress::getByName(LOG4CXX_STR("192.168.10.254"))); LogString addrStr(addr->toString()); LOGUNIT_ASSERT_EQUAL(addrStr.size() - 15, addrStr.find(LOG4CXX_STR("/192.168.10.254"))); } }; LOGUNIT_TEST_SUITE_REGISTRATION(InetAddressTestCase); apache-log4cxx-1.3.1/src/test/cpp/helpers/syslogwritertest.cpp0000644000175100001770000000244614721727031024055 0ustar runnerdocker/* * 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. */ #include "../logunit.h" #include using namespace log4cxx; using namespace log4cxx::helpers; LOGUNIT_CLASS(SyslogWriterTest) { LOGUNIT_TEST_SUITE(SyslogWriterTest); LOGUNIT_TEST(testUnknownHost); LOGUNIT_TEST_SUITE_END(); public: /** * Tests writing to an unknown host. */ void testUnknownHost() { SyslogWriter writer(LOG4CXX_STR("unknown.invalid")); writer.write(LOG4CXX_STR("Hello, Unknown World.")); } }; LOGUNIT_TEST_SUITE_REGISTRATION(SyslogWriterTest); apache-log4cxx-1.3.1/src/test/cpp/helpers/relativetimedateformattestcase.cpp0000644000175100001770000000457214721727031026677 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include "../insertwide.h" #include "../logunit.h" #include using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::spi; /** Unit test {@link RelativeTimeDateFormat} class. */ LOGUNIT_CLASS(RelativeTimeDateFormatTestCase) { LOGUNIT_TEST_SUITE(RelativeTimeDateFormatTestCase); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST(test3); LOGUNIT_TEST_SUITE_END(); public: /** * Convert 2 Jan 2004 */ void test1() { log4cxx_time_t jan2 = Date::getMicrosecondsPerDay() * 12419; log4cxx_time_t preStartTime = LoggingEvent::getStartTime(); RelativeTimeDateFormat formatter; Pool p; LogString actual; formatter.format(actual, jan2, p); log4cxx_time_t elapsed = log4cxx::helpers::StringHelper::toInt64(actual); LOGUNIT_ASSERT(preStartTime + elapsed * 1000 > jan2 - 2000); LOGUNIT_ASSERT(preStartTime + elapsed * 1000 < jan2 + 2000); } /** * Checks that numberFormat works as expected. */ void test2() { LogString numb; Pool p; RelativeTimeDateFormat formatter; formatter.numberFormat(numb, 87, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("87"), numb); } /** * Checks that setting timezone doesn't throw an exception. */ void test3() { RelativeTimeDateFormat formatter; formatter.setTimeZone(TimeZone::getGMT()); } }; LOGUNIT_TEST_SUITE_REGISTRATION(RelativeTimeDateFormatTestCase); apache-log4cxx-1.3.1/src/test/cpp/helpers/charsetencodertestcase.cpp0000644000175100001770000002466314721727031025132 0ustar runnerdocker/* * 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. */ #include #include "../logunit.h" #include "../insertwide.h" #include #include #include #include #include #include #include using namespace log4cxx; using namespace log4cxx::helpers; LOGUNIT_CLASS(CharsetEncoderTestCase) { LOGUNIT_TEST_SUITE(CharsetEncoderTestCase); LOGUNIT_TEST(encode1); LOGUNIT_TEST(encode2); LOGUNIT_TEST(encode3); LOGUNIT_TEST(encode4); LOGUNIT_TEST(encode5); LOGUNIT_TEST(thread1); LOGUNIT_TEST_SUITE_END(); enum { BUFSIZE = 256 }; public: void encode1() { const LogString greeting(LOG4CXX_STR("Hello, World")); CharsetEncoderPtr enc(CharsetEncoder::getEncoder(LOG4CXX_STR("US-ASCII"))); char buf[BUFSIZE]; ByteBuffer out(buf, BUFSIZE); LogString::const_iterator iter = greeting.begin(); log4cxx_status_t stat = enc->encode(greeting, iter, out); LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat); LOGUNIT_ASSERT(iter == greeting.end()); stat = enc->encode(greeting, iter, out); LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat); LOGUNIT_ASSERT_EQUAL((size_t) 12, out.position()); out.flip(); std::string encoded((const char*) out.data(), out.limit()); LOGUNIT_ASSERT_EQUAL((std::string) "Hello, World", encoded); LOGUNIT_ASSERT(iter == greeting.end()); } void encode2() { LogString greeting(BUFSIZE - 3, LOG4CXX_STR('A')); greeting.append(LOG4CXX_STR("Hello")); CharsetEncoderPtr enc(CharsetEncoder::getEncoder(LOG4CXX_STR("US-ASCII"))); char buf[BUFSIZE]; ByteBuffer out(buf, BUFSIZE); LogString::const_iterator iter = greeting.begin(); log4cxx_status_t stat = enc->encode(greeting, iter, out); LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat); LOGUNIT_ASSERT_EQUAL((size_t) 0, out.remaining()); LOGUNIT_ASSERT_EQUAL(LOG4CXX_STR('o'), *(iter + 1)); out.flip(); std::string encoded((char*) out.data(), out.limit()); out.clear(); stat = enc->encode(greeting, iter, out); LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat); LOGUNIT_ASSERT_EQUAL((size_t) 2, out.position()); LOGUNIT_ASSERT(iter == greeting.end()); stat = enc->encode(greeting, iter, out); out.flip(); LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat); encoded.append(out.data(), out.limit()); std::string manyAs(BUFSIZE - 3, 'A'); LOGUNIT_ASSERT_EQUAL(manyAs, encoded.substr(0, BUFSIZE - 3)); LOGUNIT_ASSERT_EQUAL(std::string("Hello"), encoded.substr(BUFSIZE - 3)); } void encode3() { #if LOG4CXX_LOGCHAR_IS_WCHAR || LOG4CXX_LOGCHAR_IS_UNICHAR // arbitrary, hopefully meaningless, characters from // Latin, Arabic, Armenian, Bengali, CJK and Cyrillic const logchar greet[] = { L'A', 0x0605, 0x0530, 0x986, 0x4E03, 0x400, 0 }; #endif #if LOG4CXX_LOGCHAR_IS_UTF8 const char greet[] = { 'A', (char) 0xD8, (char) 0x85, (char) 0xD4, (char) 0xB0, (char) 0xE0, (char) 0xA6, (char) 0x86, (char) 0xE4, (char) 0xB8, (char) 0x83, (char) 0xD0, (char) 0x80, 0 }; #endif LogString greeting(greet); CharsetEncoderPtr enc(CharsetEncoder::getEncoder(LOG4CXX_STR("US-ASCII"))); char buf[BUFSIZE]; ByteBuffer out(buf, BUFSIZE); LogString::const_iterator iter = greeting.begin(); log4cxx_status_t stat = enc->encode(greeting, iter, out); out.flip(); LOGUNIT_ASSERT_EQUAL(true, CharsetEncoder::isError(stat)); LOGUNIT_ASSERT_EQUAL((size_t) 1, out.limit()); LOGUNIT_ASSERT_EQUAL(greet[1], *iter); LOGUNIT_ASSERT_EQUAL('A', out.data()[0]); } void encode4() { const char utf8_greet[] = { 'A', (char) 0xD8, (char) 0x85, (char) 0xD4, (char) 0xB0, (char) 0xE0, (char) 0xA6, (char) 0x86, (char) 0xE4, (char) 0xB8, (char) 0x83, (char) 0xD0, (char) 0x80, 0 }; #if LOG4CXX_LOGCHAR_IS_WCHAR || LOG4CXX_LOGCHAR_IS_UNICHAR // arbitrary, hopefully meaningless, characters from // Latin, Arabic, Armenian, Bengali, CJK and Cyrillic const logchar greet[] = { L'A', 0x0605, 0x0530, 0x986, 0x4E03, 0x400, 0 }; #endif #if LOG4CXX_LOGCHAR_IS_UTF8 const logchar* greet = utf8_greet; #endif LogString greeting(greet); CharsetEncoderPtr enc(CharsetEncoder::getEncoder(LOG4CXX_STR("UTF-8"))); char buf[BUFSIZE]; ByteBuffer out(buf, BUFSIZE); LogString::const_iterator iter = greeting.begin(); log4cxx_status_t stat = enc->encode(greeting, iter, out); LOGUNIT_ASSERT_EQUAL(false, CharsetEncoder::isError(stat)); stat = enc->encode(greeting, iter, out); LOGUNIT_ASSERT_EQUAL(false, CharsetEncoder::isError(stat)); out.flip(); LOGUNIT_ASSERT_EQUAL((size_t) 13, out.limit()); for (size_t i = 0; i < out.limit(); i++) { LOGUNIT_ASSERT_EQUAL((int) utf8_greet[i], (int) out.data()[i]); } LOGUNIT_ASSERT(iter == greeting.end()); } void encode5() { const char utf8_greet[] = { 'A', (char) 0xD8, (char) 0x85, (char) 0xD4, (char) 0xB0, (char) 0xE0, (char) 0xA6, (char) 0x86, (char) 0xE4, (char) 0xB8, (char) 0x83, (char) 0xD0, (char) 0x80, 0 }; #if LOG4CXX_LOGCHAR_IS_WCHAR || LOG4CXX_LOGCHAR_IS_UNICHAR // arbitrary, hopefully meaningless, characters from // Latin, Arabic, Armenian, Bengali, CJK and Cyrillic const logchar greet[] = { L'A', 0x0605, 0x0530, 0x986, 0x4E03, 0x400, 0 }; #endif #if LOG4CXX_LOGCHAR_IS_UTF8 const logchar* greet = utf8_greet; #endif LogString greeting(greet); try { std::locale::global(std::locale("en_US.UTF-8")); auto enc = CharsetEncoder::getEncoder(LOG4CXX_STR("locale")); char buf[BUFSIZE]; ByteBuffer out(buf, BUFSIZE); LogString::const_iterator iter = greeting.begin(); log4cxx_status_t stat = enc->encode(greeting, iter, out); LOGUNIT_ASSERT_EQUAL(false, CharsetEncoder::isError(stat)); stat = enc->encode(greeting, iter, out); LOGUNIT_ASSERT_EQUAL(false, CharsetEncoder::isError(stat)); out.flip(); LOGUNIT_ASSERT_EQUAL((size_t) 13, out.limit()); for (size_t i = 0; i < out.limit(); i++) { unsigned expected = (unsigned)utf8_greet[i]; unsigned actual = (unsigned)out.data()[i]; LOGUNIT_ASSERT_EQUAL(expected, actual); } LOGUNIT_ASSERT(iter == greeting.end()); } catch (std::runtime_error& ex) { LogString msg; Transcoder::decode(ex.what(), msg); msg.append(LOG4CXX_STR(": ")); msg.append(LOG4CXX_STR("en_US.UTF-8")); LogLog::warn(msg); } } class ThreadPackage { public: ThreadPackage(CharsetEncoderPtr& enc, int repetitions) : passCount(0), failCount(0), enc(enc), repetitions(repetitions) { } void await() { std::unique_lock sync(lock); condition.wait(sync); } void signalAll() { condition.notify_all(); } void fail() { std::lock_guard sync(lock); ++failCount; } void pass() { std::lock_guard sync(lock); ++passCount; } uint32_t getFail() { std::lock_guard sync(lock); return failCount; } uint32_t getPass() { std::lock_guard sync(lock); return passCount; } int getRepetitions() { return repetitions; } CharsetEncoderPtr& getEncoder() { return enc; } void run() { #if LOG4CXX_LOGCHAR_IS_UTF8 const logchar greet[] = { 'H', 'e', 'l', 'l', 'o', ' ', (char) 0xC2, (char) 0xA2, // cent sign (char) 0xC2, (char) 0xA9, // copyright (char) 0xc3, (char) 0xb4, // latin small letter o with circumflex 0 }; #endif #if LOG4CXX_LOGCHAR_IS_WCHAR || LOG4CXX_LOGCHAR_IS_UNICHAR // arbitrary, hopefully meaningless, characters from // Latin, Arabic, Armenian, Bengali, CJK and Cyrillic const logchar greet[] = { L'H', L'e', L'l', L'l', L'o', L' ', 0x00A2, 0x00A9, 0x00F4, 0 }; #endif const char expected[] = { 'H', 'e', 'l', 'l', 'o', ' ', (char) 0x00A2, (char) 0x00A9, (char) 0x00F4 }; LogString greeting(greet); await(); for (int i = 0; i < getRepetitions(); i++) { bool pass = true; char buf[BUFSIZE]; ByteBuffer out(buf, BUFSIZE); LogString::const_iterator iter = greeting.begin(); log4cxx_status_t stat = getEncoder()->encode(greeting, iter, out); pass = (false == CharsetEncoder::isError(stat)); if (pass) { stat = getEncoder()->encode(greeting, iter, out); pass = (false == CharsetEncoder::isError(stat)); if (pass) { out.flip(); pass = (sizeof(expected) == out.limit()); for (size_t i = 0; i < out.limit() && pass; i++) { pass = (expected[i] == out.data()[i]); } pass = pass && (iter == greeting.end()); } } if (pass) { ThreadPackage::pass(); } else { fail(); } } } private: ThreadPackage(const ThreadPackage&); ThreadPackage& operator=(ThreadPackage&); std::mutex lock; std::condition_variable condition; uint32_t passCount; uint32_t failCount; CharsetEncoderPtr enc; int repetitions; }; void thread1() { enum { THREAD_COUNT = 10, THREAD_REPS = 10000 }; std::thread threads[THREAD_COUNT]; CharsetEncoderPtr enc(CharsetEncoder::getEncoder(LOG4CXX_STR("ISO-8859-1"))); auto package = std::make_unique(enc, THREAD_REPS); for (int i = 0; i < THREAD_COUNT; i++) { threads[i] = std::thread(&ThreadPackage::run, package.get()); } // // give time for all threads to be launched so // we don't signal before everybody is waiting. std::this_thread::sleep_for( std::chrono::milliseconds( 100 ) ); package->signalAll(); for (int i = 0; i < THREAD_COUNT; i++) { threads[i].join(); } LOGUNIT_ASSERT_EQUAL((apr_uint32_t) 0, package->getFail()); LOGUNIT_ASSERT_EQUAL((apr_uint32_t) THREAD_COUNT * THREAD_REPS, package->getPass()); } }; LOGUNIT_TEST_SUITE_REGISTRATION(CharsetEncoderTestCase); apache-log4cxx-1.3.1/src/test/cpp/helpers/filewatchdogtest.cpp0000644000175100001770000000344214721727031023735 0ustar runnerdocker/* * 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. */ #include #include #include "../logunit.h" #include "apr_time.h" using namespace log4cxx; using namespace log4cxx::helpers; /** * * FileWatchdog tests. */ LOGUNIT_CLASS(FileWatchdogTest) { LOGUNIT_TEST_SUITE(FileWatchdogTest); LOGUNIT_TEST(testShutdownDelay); LOGUNIT_TEST_SUITE_END(); private: class MockWatchdog : public FileWatchdog { public: MockWatchdog(const File& file) : FileWatchdog(file) { } void doOnChange() { } }; public: /** * Tests that FileWatchdog will respond to a shutdown request more rapidly * than waiting out its delay. */ void testShutdownDelay() { apr_time_t start = apr_time_now(); { MockWatchdog dog(File(LOG4CXX_STR("input/patternlayout1.properties"))); dog.start(); // wait 50 ms for thread to get rolling apr_sleep(50000); } apr_time_t delta = apr_time_now() - start; LOGUNIT_ASSERT(delta < 30000000); } }; LOGUNIT_TEST_SUITE_REGISTRATION(FileWatchdogTest); apache-log4cxx-1.3.1/src/test/cpp/helpers/localechanger.h0000644000175100001770000000301514721727031022625 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_LOCALE_CHANGER_H #define _LOG4CXX_HELPERS_LOCALE_CHANGER_H #include namespace LOG4CXX_NS { namespace helpers { /** * Utility class to change the locale for the duration of a test. * * * * */ class LocaleChanger { public: /** * Construction attemtps to change default locale. * @param locale locale. */ LocaleChanger(const char* locale); /** * Restores previous locale. */ ~LocaleChanger(); /** * Determines whether locale change was effective. * @return true if effective. */ inline bool isEffective() { return effective; } private: LocaleChanger(LocaleChanger&); LocaleChanger& operator=(LocaleChanger&); std::locale initial; bool effective; }; } } #endif apache-log4cxx-1.3.1/src/test/cpp/helpers/casttestcase.cpp0000644000175100001770000000426314721727031023065 0ustar runnerdocker/* * 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. */ #include "../logunit.h" #include #include #include #include using namespace log4cxx; using namespace log4cxx::helpers; #define LOG4CXX_TEST 1 #include /** */ LOGUNIT_CLASS(CastTestCase) { LOGUNIT_TEST_SUITE( CastTestCase ); LOGUNIT_TEST(testGoodCast); LOGUNIT_TEST(testBadCast); LOGUNIT_TEST(testNullParameter); LOGUNIT_TEST(testRollingFileAppender); LOGUNIT_TEST_SUITE_END(); public: /** * */ void testGoodCast() { OutputStreamPtr out = OutputStreamPtr(new ByteArrayOutputStream()); ByteArrayOutputStreamPtr byteOut = log4cxx::cast(out); LOGUNIT_ASSERT(byteOut); } void testBadCast() { OutputStreamPtr out = OutputStreamPtr(new ByteArrayOutputStream()); FileOutputStreamPtr fos = log4cxx::cast(out); LOGUNIT_ASSERT(!fos); } void testNullParameter() { OutputStreamPtr out = nullptr; FileOutputStreamPtr fos = log4cxx::cast(out); LOGUNIT_ASSERT(!fos); } void testRollingFileAppender() { rolling::RollingFileAppenderPtr rolling = rolling::RollingFileAppenderPtr(new rolling::RollingFileAppender()); AppenderPtr appender = log4cxx::cast(rolling); LOGUNIT_ASSERT(appender); } }; LOGUNIT_TEST_SUITE_REGISTRATION(CastTestCase); apache-log4cxx-1.3.1/src/test/cpp/helpers/optionconvertertestcase.cpp0000644000175100001770000001357114721727031025375 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include "../testchar.h" #include "../insertwide.h" #include "../logunit.h" #include #include #include #include #include using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::spi; #define MAX 1000 LOGUNIT_CLASS(OptionConverterTestCase) { LOGUNIT_TEST_SUITE(OptionConverterTestCase); LOGUNIT_TEST(varSubstTest1); LOGUNIT_TEST(varSubstTest2); LOGUNIT_TEST(varSubstTest3); LOGUNIT_TEST(varSubstTest4); LOGUNIT_TEST(varSubstTest5); LOGUNIT_TEST(testTmpDir); #if APR_HAS_USER LOGUNIT_TEST(testUserHome); LOGUNIT_TEST(testUserName); #endif LOGUNIT_TEST(testUserDir); LOGUNIT_TEST_SUITE_END(); Properties props; Properties nullProperties; public: void setUp() { } void tearDown() { } /** * Checks that environment variables were properly set * before invoking tests. ::putenv not reliable. */ void envCheck() { Pool p; char* toto; apr_status_t stat = apr_env_get(&toto, "TOTO", p.getAPRPool()); LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat); LOGUNIT_ASSERT_EQUAL("wonderful", toto); char* key1; stat = apr_env_get(&key1, "key1", p.getAPRPool()); LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat); LOGUNIT_ASSERT_EQUAL("value1", key1); char* key2; stat = apr_env_get(&key2, "key2", p.getAPRPool()); LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat); LOGUNIT_ASSERT_EQUAL("value2", key2); } void varSubstTest1() { envCheck(); LogString r(OptionConverter::substVars(LOG4CXX_STR("hello world."), nullProperties)); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("hello world."), r); r = OptionConverter::substVars(LOG4CXX_STR("hello ${TOTO} world."), nullProperties); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("hello wonderful world."), r); } void varSubstTest2() { envCheck(); LogString r(OptionConverter::substVars(LOG4CXX_STR("Test2 ${key1} mid ${key2} end."), nullProperties)); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("Test2 value1 mid value2 end."), r); } void varSubstTest3() { envCheck(); LogString r(OptionConverter::substVars( LOG4CXX_STR("Test3 ${unset} mid ${key1} end."), nullProperties)); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("Test3 mid value1 end."), r); } void varSubstTest4() { LogString res; LogString val(LOG4CXX_STR("Test4 ${incomplete ")); try { res = OptionConverter::substVars(val, nullProperties); } catch (IllegalArgumentException& e) { std::string witness("\"Test4 ${incomplete \" has no closing brace. Opening brace at position 6."); LOGUNIT_ASSERT_EQUAL(witness, (std::string) e.what()); } } void varSubstTest5() { Properties props1; props1.setProperty(LOG4CXX_STR("p1"), LOG4CXX_STR("x1")); props1.setProperty(LOG4CXX_STR("p2"), LOG4CXX_STR("${p1}")); LogString res = OptionConverter::substVars(LOG4CXX_STR("${p2}"), props1); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("x1"), res); } void testTmpDir() { LogString actual(OptionConverter::substVars( LOG4CXX_STR("${java.io.tmpdir}"), nullProperties)); Pool p; const char* tmpdir = NULL; apr_status_t stat = apr_temp_dir_get(&tmpdir, p.getAPRPool()); LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat); LogString expected; Transcoder::decode(tmpdir, expected); LOGUNIT_ASSERT_EQUAL(expected, actual); } #if APR_HAS_USER void testUserHome() { LogString actual(OptionConverter::substVars( LOG4CXX_STR("${user.home}"), nullProperties)); Pool p; apr_uid_t userid; apr_gid_t groupid; apr_status_t stat = apr_uid_current(&userid, &groupid, p.getAPRPool()); if (stat == APR_SUCCESS) { char* username = NULL; stat = apr_uid_name_get(&username, userid, p.getAPRPool()); if (stat == APR_SUCCESS) { char* dirname = NULL; stat = apr_uid_homepath_get(&dirname, username, p.getAPRPool()); if (stat == APR_SUCCESS) { LogString expected; Transcoder::decode(dirname, expected); LOGUNIT_ASSERT_EQUAL(expected, actual); } } } } void testUserName() { LogString actual(OptionConverter::substVars( LOG4CXX_STR("${user.name}"), nullProperties)); Pool p; apr_uid_t userid; apr_gid_t groupid; apr_status_t stat = apr_uid_current(&userid, &groupid, p.getAPRPool()); if (stat == APR_SUCCESS) { char* username = NULL; stat = apr_uid_name_get(&username, userid, p.getAPRPool()); if (stat == APR_SUCCESS) { LogString expected; Transcoder::decode(username, expected); LOGUNIT_ASSERT_EQUAL(expected, actual); } } } #endif void testUserDir() { LogString actual(OptionConverter::substVars( LOG4CXX_STR("${user.dir}"), nullProperties)); Pool p; char* dirname = NULL; apr_status_t stat = apr_filepath_get(&dirname, APR_FILEPATH_NATIVE, p.getAPRPool()); LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat); LogString expected; Transcoder::decode(dirname, expected); LOGUNIT_ASSERT_EQUAL(expected, actual); } }; LOGUNIT_TEST_SUITE_REGISTRATION(OptionConverterTestCase); apache-log4cxx-1.3.1/src/test/cpp/helpers/timezonetestcase.cpp0000644000175100001770000000636614721727031023773 0ustar runnerdocker/* * 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. */ #include #include #include "../insertwide.h" #include "../logunit.h" #include using namespace log4cxx; using namespace log4cxx::helpers; //Define INT64_C for compilers that don't have it #if (!defined(INT64_C)) #define INT64_C(value) value ## LL #endif /** Unit test {@link TimeZone}. */ LOGUNIT_CLASS(TimeZoneTestCase) { LOGUNIT_TEST_SUITE(TimeZoneTestCase); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST(test3); LOGUNIT_TEST(test4); LOGUNIT_TEST(test5); LOGUNIT_TEST(test6); LOGUNIT_TEST_SUITE_END(); #define MICROSECONDS_PER_DAY APR_INT64_C(86400000000) public: /** * Checks the GMT timezone */ void test1() { TimeZonePtr tz(TimeZone::getGMT()); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("GMT"), tz->getID()); } /** * Get "GMT-6" time zone */ void test2() { TimeZonePtr tz(TimeZone::getTimeZone(LOG4CXX_STR("GMT-6"))); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("GMT-06:00"), tz->getID()); apr_time_t jan2 = MICROSECONDS_PER_DAY * 12420; apr_time_exp_t exploded; tz->explode(&exploded, jan2); LOGUNIT_ASSERT_EQUAL(-6 * 3600, exploded.tm_gmtoff); LOGUNIT_ASSERT_EQUAL(18, exploded.tm_hour); } /** * Get the default timezone name */ void test3() { TimeZonePtr tz(TimeZone::getDefault()); LogString tzName(tz->getID()); LOGUNIT_ASSERT(tzName.length() > 0); } /** * Get "GMT+0010" time zone */ void test4() { TimeZonePtr tz(TimeZone::getTimeZone(LOG4CXX_STR("GMT+0010"))); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("GMT+00:10"), tz->getID()); apr_time_t jan2 = MICROSECONDS_PER_DAY * 12420; apr_time_exp_t exploded; tz->explode(&exploded, jan2); LOGUNIT_ASSERT_EQUAL(600, exploded.tm_gmtoff); LOGUNIT_ASSERT_EQUAL(0, exploded.tm_hour); LOGUNIT_ASSERT_EQUAL(10, exploded.tm_min); } /** * Get "GMT+6" time zone */ void test5() { TimeZonePtr tz(TimeZone::getTimeZone(LOG4CXX_STR("GMT+6"))); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("GMT+06:00"), tz->getID()); apr_time_t jan2 = MICROSECONDS_PER_DAY * 12420; apr_time_exp_t exploded; tz->explode(&exploded, jan2); LOGUNIT_ASSERT_EQUAL(6 * 3600, exploded.tm_gmtoff); LOGUNIT_ASSERT_EQUAL(6, exploded.tm_hour); } /** * Checks the GMT timezone */ void test6() { TimeZonePtr tz(TimeZone::getTimeZone(LOG4CXX_STR("GMT"))); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("GMT"), tz->getID()); } }; LOGUNIT_TEST_SUITE_REGISTRATION(TimeZoneTestCase); apache-log4cxx-1.3.1/src/test/cpp/helpers/charsetdecodertestcase.cpp0000644000175100001770000001056414721727031025113 0ustar runnerdocker/* * 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. */ #include #include #include #include "../logunit.h" #include "../insertwide.h" #include #include using namespace log4cxx; using namespace log4cxx::helpers; #define APR_SUCCESS ((log4cxx_status_t) 0) LOGUNIT_CLASS(CharsetDecoderTestCase) { LOGUNIT_TEST_SUITE(CharsetDecoderTestCase); LOGUNIT_TEST(decode1); LOGUNIT_TEST(decode2); LOGUNIT_TEST(decode3); LOGUNIT_TEST(decode4); LOGUNIT_TEST_SUITE_END(); enum { BUFSIZE = 256 }; public: void decode1() { char buf[] = "Hello, World"; ByteBuffer src(buf, strlen(buf)); CharsetDecoderPtr dec(CharsetDecoder::getDefaultDecoder()); LogString greeting; log4cxx_status_t stat = dec->decode(src, greeting); LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat); stat = dec->decode(src, greeting); LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat); LOGUNIT_ASSERT_EQUAL((size_t) 12, src.position()); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("Hello, World"), greeting); } void decode2() { char buf[BUFSIZE + 6]; memset(buf, 'A', BUFSIZE); buf[BUFSIZE - 3] = 0; strcat_s(buf, sizeof buf, "Hello"); ByteBuffer src(buf, strlen(buf)); CharsetDecoderPtr dec(CharsetDecoder::getDefaultDecoder()); LogString greeting; log4cxx_status_t stat = dec->decode(src, greeting); LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat); LOGUNIT_ASSERT_EQUAL((size_t) 0, src.remaining()); stat = dec->decode(src, greeting); LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat); LogString manyAs(BUFSIZE - 3, LOG4CXX_STR('A')); LOGUNIT_ASSERT_EQUAL(manyAs, greeting.substr(0, BUFSIZE - 3)); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("Hello")), greeting.substr(BUFSIZE - 3)); } void decode3() { char buf[] = { 'H', 'e', 'l', 'l', 'o', ',', 0, 'W', 'o', 'r', 'l', 'd'}; ByteBuffer src(buf, 12); CharsetDecoderPtr dec(CharsetDecoder::getDefaultDecoder()); LogString greeting; log4cxx_status_t stat = dec->decode(src, greeting); LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat); stat = dec->decode(src, greeting); LOGUNIT_ASSERT_EQUAL(APR_SUCCESS, stat); LOGUNIT_ASSERT_EQUAL((size_t) 12, src.position()); const logchar expected[] = { 0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x2C, 0x00, 0x57, 0x6F, 0x72, 0x6C, 0x64 }; LOGUNIT_ASSERT_EQUAL(LogString(expected, 12), greeting); } void decode4() { char utf8_greet[] = { 'A', (char) 0xD8, (char) 0x85, (char) 0xD4, (char) 0xB0, (char) 0xE0, (char) 0xA6, (char) 0x86, (char) 0xE4, (char) 0xB8, (char) 0x83, (char) 0xD0, (char) 0x80, 0 }; #if LOG4CXX_LOGCHAR_IS_WCHAR || LOG4CXX_LOGCHAR_IS_UNICHAR // arbitrary, hopefully meaningless, characters from // Latin, Arabic, Armenian, Bengali, CJK and Cyrillic const logchar greet[] = { L'A', 0x0605, 0x0530, 0x986, 0x4E03, 0x400, 0 }; #endif #if LOG4CXX_LOGCHAR_IS_UTF8 const logchar* greet = utf8_greet; #endif try { std::locale::global(std::locale("en_US.UTF-8")); auto dec = CharsetDecoder::getDecoder(LOG4CXX_STR("locale")); ByteBuffer in(utf8_greet, sizeof (utf8_greet)); LogString out; log4cxx_status_t stat = dec->decode(in, out); LOGUNIT_ASSERT_EQUAL(false, CharsetDecoder::isError(stat)); stat = dec->decode(in, out); LOGUNIT_ASSERT_EQUAL(false, CharsetDecoder::isError(stat)); LOGUNIT_ASSERT(out == greet); } catch (std::runtime_error& ex) { LogString msg; Transcoder::decode(ex.what(), msg); msg.append(LOG4CXX_STR(": ")); msg.append(LOG4CXX_STR("en_US.UTF-8")); LogLog::warn(msg); } } }; LOGUNIT_TEST_SUITE_REGISTRATION(CharsetDecoderTestCase); apache-log4cxx-1.3.1/src/test/cpp/helpers/CMakeLists.txt0000644000175100001770000000365214721727031022434 0ustar runnerdocker# # 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. # set(HELPER_TESTS absolutetimedateformattestcase cacheddateformattestcase casttestcase charsetdecodertestcase charsetencodertestcase cyclicbuffertestcase datetimedateformattestcase filewatchdogtest inetaddresstestcase iso8601dateformattestcase messagebuffertest optionconvertertestcase propertiestestcase relativetimedateformattestcase stringhelpertestcase stringtokenizertestcase timezonetestcase transcodertestcase threadutilitytestcase ) if(LOG4CXX_NETWORKING_SUPPORT) list(APPEND HELPER_TESTS syslogwritertest) endif() foreach(fileName IN LISTS HELPER_TESTS) add_executable(${fileName} "${fileName}.cpp") target_compile_definitions(${fileName} PRIVATE ${APR_COMPILE_DEFINITIONS} ${APR_UTIL_COMPILE_DEFINITIONS} ) target_include_directories(${fileName} PRIVATE ${CMAKE_CURRENT_LIST_DIR} $ ${APR_INCLUDE_DIR}) endforeach() target_sources(cacheddateformattestcase PRIVATE localechanger.cpp) target_sources(datetimedateformattestcase PRIVATE localechanger.cpp) set(ALL_LOG4CXX_TESTS ${ALL_LOG4CXX_TESTS} ${HELPER_TESTS} PARENT_SCOPE) apache-log4cxx-1.3.1/src/test/cpp/helpers/cacheddateformattestcase.cpp0000644000175100001770000004626414721727031025420 0ustar runnerdocker/* * 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. */ #include #include "../logunit.h" #include #include #include #include #include #include "../insertwide.h" #include #include #include "localechanger.h" using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::pattern; #define LOCALE_US "C" #if defined(_WIN32) #define LOCALE_JP "Japanese_japan" #else #define LOCALE_JP "ja_JP" #endif //Define INT64_C for compilers that don't have it #if (!defined(INT64_C)) #define INT64_C(value) value ##LL #endif #define LOG4CXX_TEST 1 #include /** * Unit test {@link CachedDateFormat}. */ LOGUNIT_CLASS(CachedDateFormatTestCase) { LOGUNIT_TEST_SUITE( CachedDateFormatTestCase ); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST(test3); LOGUNIT_TEST(test4); #if LOG4CXX_HAS_STD_LOCALE LOGUNIT_TEST(test5); #endif LOGUNIT_TEST(test6); LOGUNIT_TEST(test8); // Gump doesn't like this test // LOGUNIT_TEST(test9); LOGUNIT_TEST(test10); LOGUNIT_TEST(test11); LOGUNIT_TEST(test12); LOGUNIT_TEST(test13); LOGUNIT_TEST(test14); LOGUNIT_TEST(test15); LOGUNIT_TEST(test16); LOGUNIT_TEST(test17); LOGUNIT_TEST(test18); LOGUNIT_TEST(test19); LOGUNIT_TEST(test20); LOGUNIT_TEST(test21); LOGUNIT_TEST(test22); LOGUNIT_TEST_SUITE_END(); #define MICROSECONDS_PER_DAY APR_INT64_C(86400000000) public: /** * Test multiple calls in close intervals. */ void test1() { // subsequent calls within one minute // are optimized to reuse previous formatted value // make a couple of nearly spaced calls DateFormatPtr baseFormatter(new AbsoluteTimeDateFormat()); CachedDateFormat gmtFormat(baseFormatter, 1000000); gmtFormat.setTimeZone(TimeZone::getGMT()); apr_time_t jul1 = MICROSECONDS_PER_DAY * 12601L; Pool p; LogString actual; gmtFormat.format(actual, jul1, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,000"), actual); actual.erase(actual.begin(), actual.end()); gmtFormat.format(actual, jul1 + 8000, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,008"), actual); actual.erase(actual.begin(), actual.end()); gmtFormat.format(actual, jul1 + 17000, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,017"), actual); actual.erase(actual.begin(), actual.end()); gmtFormat.format(actual, jul1 + 237000, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,237"), actual); actual.erase(actual.begin(), actual.end()); gmtFormat.format(actual, jul1 + 1415000, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:01,415"), actual); actual.erase(actual.begin(), actual.end()); } /** * Check for interaction between caches. */ void test2() { apr_time_t jul2 = MICROSECONDS_PER_DAY * 12602; DateFormatPtr baseFormatter(new AbsoluteTimeDateFormat()); CachedDateFormat gmtFormat(baseFormatter, 1000000); gmtFormat.setTimeZone(TimeZone::getGMT()); DateFormatPtr chicagoBase(new AbsoluteTimeDateFormat()); CachedDateFormat chicagoFormat(chicagoBase, 1000000); chicagoFormat.setTimeZone(TimeZone::getTimeZone(LOG4CXX_STR("GMT-5"))); Pool p; LogString actual; gmtFormat.format(actual, jul2, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,000"), actual); actual.erase(actual.begin(), actual.end()); chicagoFormat.format(actual, jul2, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("19:00:00,000"), actual); actual.erase(actual.begin(), actual.end()); gmtFormat.format(actual, jul2, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,000"), actual); } /** * Test multiple calls in close intervals prior to 1 Jan 1970. */ void test3() { // subsequent calls within one minute // are optimized to reuse previous formatted value // make a couple of nearly spaced calls DateFormatPtr baseFormatter(new AbsoluteTimeDateFormat()); CachedDateFormat gmtFormat(baseFormatter, 1000000); gmtFormat.setTimeZone(TimeZone::getGMT()); apr_time_t ticks = MICROSECONDS_PER_DAY * -7; Pool p; LogString actual; gmtFormat.format(actual, ticks, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,000"), actual); actual.erase(actual.begin(), actual.end()); // // APR's explode_time method does not properly calculate tm_usec // prior to 1 Jan 1970 on Unix gmtFormat.format(actual, ticks + 8000, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,008"), actual); actual.erase(actual.begin(), actual.end()); gmtFormat.format(actual, ticks + 17000, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,017"), actual); actual.erase(actual.begin(), actual.end()); gmtFormat.format(actual, ticks + 237000, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,237"), actual); actual.erase(actual.begin(), actual.end()); gmtFormat.format(actual, ticks + 1423000, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:01,423"), actual); } void assertFormattedEquals( const DateFormatPtr & baseFormat, const CachedDateFormat & cachedFormat, apr_time_t date, Pool & p) { LogString expected; LogString actual; baseFormat->format(expected, date, p); cachedFormat.format(actual, date, p); LOGUNIT_ASSERT_EQUAL(expected, actual); } void test4() { // subsequent calls within one minute // are optimized to reuse previous formatted value // make a couple of nearly spaced calls #if LOG4CXX_HAS_STD_LOCALE std::locale loco(LOCALE_US); std::locale* localeEN = &loco; #else std::locale* localeEN = NULL; #endif DateFormatPtr baseFormat( new SimpleDateFormat(LOG4CXX_STR("EEE, MMM dd, HH:mm:ss.SSS Z"), localeEN)); CachedDateFormat cachedFormat(baseFormat, 1000000); // // use a date in 2000 to attempt to confuse the millisecond locator apr_time_t ticks = MICROSECONDS_PER_DAY * 11141; Pool p; assertFormattedEquals(baseFormat, cachedFormat, ticks, p); assertFormattedEquals(baseFormat, cachedFormat, ticks + 8000, p); assertFormattedEquals(baseFormat, cachedFormat, ticks + 17000, p); assertFormattedEquals(baseFormat, cachedFormat, ticks + 237000, p); assertFormattedEquals(baseFormat, cachedFormat, ticks + 1415000, p); } #if LOG4CXX_HAS_STD_LOCALE void test5() { // subsequent calls within one minute // are optimized to reuse previous formatted value // make a couple of nearly spaced calls LocaleChanger localeChange(LOCALE_JP); if (localeChange.isEffective()) { DateFormatPtr baseFormat(new SimpleDateFormat( LOG4CXX_STR("EEE, MMM dd, HH:mm:ss.SSS Z"))); CachedDateFormat cachedFormat(baseFormat, 1000000); // // use a date in 2000 to attempt to confuse the millisecond locator apr_time_t ticks = MICROSECONDS_PER_DAY * 11141; Pool p; assertFormattedEquals(baseFormat, cachedFormat, ticks, p); assertFormattedEquals(baseFormat, cachedFormat, ticks + 8000, p); assertFormattedEquals(baseFormat, cachedFormat, ticks + 17000, p); assertFormattedEquals(baseFormat, cachedFormat, ticks + 237000, p); assertFormattedEquals(baseFormat, cachedFormat, ticks + 1415000, p); } } #endif /** * Checks that numberFormat works as expected. */ void test6() { LogString numb; Pool p; AbsoluteTimeDateFormat formatter; formatter.numberFormat(numb, 87, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("87"), numb); } /** * Set time zone on cached and check that it is effective. */ void test8() { DateFormatPtr baseFormat(new SimpleDateFormat(LOG4CXX_STR("yyyy-MM-dd HH:mm:ss,SSS"))); baseFormat->setTimeZone(TimeZone::getGMT()); CachedDateFormat cachedFormat(baseFormat, 1000000); apr_time_t jul4 = MICROSECONDS_PER_DAY * 12603; Pool p; LogString actual; cachedFormat.format(actual, jul4, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("2004-07-04 00:00:00,000"), actual); cachedFormat.setTimeZone(TimeZone::getTimeZone(LOG4CXX_STR("GMT-6"))); actual.erase(actual.begin(), actual.end()); cachedFormat.format(actual, jul4, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("2004-07-03 18:00:00,000"), actual); } /** * Test of caching when less than three millisecond digits are specified. */ void test9() { std::locale localeUS(LOCALE_US); DateFormatPtr baseFormat = DateFormatPtr(new SimpleDateFormat( LOG4CXX_STR("yyyy-MMMM-dd HH:mm:ss,SS Z"), &localeUS)); DateFormatPtr cachedFormat = DateFormatPtr(new CachedDateFormat(baseFormat, 1000000)); TimeZonePtr cet = TimeZone::getTimeZone(LOG4CXX_STR("GMT+1")); cachedFormat->setTimeZone(cet); apr_time_exp_t c; memset(&c, 0, sizeof(c)); c.tm_year = 104; c.tm_mon = 11; c.tm_mday = 12; c.tm_hour = 19; c.tm_sec = 37; c.tm_usec = 23000; apr_time_t dec12; apr_status_t stat = apr_time_exp_gmt_get(&dec12, &c); const apr_status_t statOK = 0; LOGUNIT_ASSERT_EQUAL(statOK, stat); Pool p; LogString s; cachedFormat->format(s, dec12, p); LOGUNIT_ASSERT_EQUAL( (LogString) LOG4CXX_STR("2004-December-12 20:00:37,23 +0100"), s); memset(&c, 0, sizeof(c)); c.tm_year = 104; c.tm_mon = 11; c.tm_mday = 31; c.tm_hour = 23; c.tm_sec = 13; c.tm_usec = 905000; apr_time_t jan1; stat = apr_time_exp_gmt_get(&jan1, &c); LOGUNIT_ASSERT_EQUAL(statOK, stat); s.erase(s.begin(), s.end()); cachedFormat->format(s, jan1, p); LOGUNIT_ASSERT_EQUAL( (LogString) LOG4CXX_STR("2005-January-01 00:00:13,905 +0100"), s); } /** * Test when millisecond position moves but length remains constant. */ void test10() { #if LOG4CXX_HAS_STD_LOCALE std::locale loco("C"); std::locale* localeUS = &loco; #else std::locale* localeUS = NULL; #endif DateFormatPtr baseFormat = DateFormatPtr(new SimpleDateFormat( LOG4CXX_STR("MMMM SSS EEEEEE"), localeUS)); DateFormatPtr cachedFormat = DateFormatPtr(new CachedDateFormat(baseFormat, 1000000)); TimeZonePtr cet = TimeZone::getTimeZone(LOG4CXX_STR("GMT+1")); cachedFormat->setTimeZone(cet); apr_time_exp_t c; memset(&c, 0, sizeof(c)); c.tm_year = 104; c.tm_mon = 9; c.tm_mday = 5; c.tm_hour = 21; c.tm_sec = 37; c.tm_usec = 23000; apr_time_t oct5; apr_status_t stat = apr_time_exp_gmt_get(&oct5, &c); const apr_status_t statOK = 0; LOGUNIT_ASSERT_EQUAL(statOK, stat); Pool p; LogString s; cachedFormat->format(s, oct5, p); LOGUNIT_ASSERT_EQUAL( (LogString) LOG4CXX_STR("October 023 Tuesday"), s); memset(&c, 0, sizeof(c)); c.tm_year = 104; c.tm_mon = 10; c.tm_mday = 1; c.tm_usec = 23000; apr_time_t nov1; stat = apr_time_exp_gmt_get(&nov1, &c); LOGUNIT_ASSERT_EQUAL(statOK, stat); s.erase(s.begin(), s.end()); cachedFormat->format(s, nov1, p); LOGUNIT_ASSERT_EQUAL( (LogString) LOG4CXX_STR("November 023 Monday"), s); nov1 += 961000; s.erase(s.begin(), s.end()); cachedFormat->format(s, nov1, p); LOGUNIT_ASSERT_EQUAL( (LogString) LOG4CXX_STR("November 984 Monday"), s); } /** * Test that tests if caching is skipped if only "SS" * is specified. */ void test11() { // // Earlier versions could be tricked by "SS0" patterns. // LogString badPattern(LOG4CXX_STR("ss,SS0")); DateFormatPtr simpleFormat = DateFormatPtr(new SimpleDateFormat(badPattern)); DateFormatPtr gmtFormat = DateFormatPtr(new CachedDateFormat(simpleFormat, 1000000)); gmtFormat->setTimeZone(TimeZone::getGMT()); // // The first request has to 100 ms after an ordinal second // to push the literal zero out of the pattern check apr_time_t ticks = MICROSECONDS_PER_DAY * 11142L; apr_time_t jul2 = ticks + 120000; Pool p; LogString s; gmtFormat->format(s, jul2, p); LOGUNIT_ASSERT_EQUAL( (LogString) LOG4CXX_STR("00,1200"), s); jul2 = ticks + 87000; s.erase(s.begin(), s.end()); gmtFormat->format(s, jul2, p); LOGUNIT_ASSERT_EQUAL( (LogString) LOG4CXX_STR("00,870"), s); } /** * Check pattern location for ISO8601 */ void test12() { DateFormatPtr df = DateFormatPtr(new SimpleDateFormat(LOG4CXX_STR("yyyy-MM-dd HH:mm:ss,SSS"))); apr_time_t ticks = 11142L * MICROSECONDS_PER_DAY; Pool p; LogString formatted; df->format(formatted, ticks, p); int msStart = CachedDateFormat::findMillisecondStart(ticks, formatted, df, p); LOGUNIT_ASSERT_EQUAL(20, msStart); // Test for for milliseconds overlapping with the magic ones as per LOGCXX-420. apr_time_exp_t c; memset(&c, 0, sizeof(c)); c.tm_year = 110; c.tm_mon = 7; c.tm_mday = 12; c.tm_hour = 9; c.tm_min = 4; c.tm_sec = 50; c.tm_usec = 406000; LOGUNIT_ASSERT_EQUAL(0, apr_time_exp_gmt_get(&ticks, &c)); formatted.clear(); df->format(formatted, ticks, p); msStart = CachedDateFormat::findMillisecondStart(ticks, formatted, df, p); LOGUNIT_ASSERT_EQUAL(20, msStart); c.tm_usec = 609000; LOGUNIT_ASSERT_EQUAL(0, apr_time_exp_gmt_get(&ticks, &c)); formatted.clear(); df->format(formatted, ticks, p); msStart = CachedDateFormat::findMillisecondStart(ticks, formatted, df, p); LOGUNIT_ASSERT_EQUAL(20, msStart); } /** * Check pattern location for DATE */ void test13() { DateFormatPtr df = DateFormatPtr(new SimpleDateFormat(LOG4CXX_STR("yyyy-MM-dd"))); apr_time_t ticks = 11142L * MICROSECONDS_PER_DAY; Pool p; LogString formatted; df->format(formatted, ticks, p); int millisecondStart = CachedDateFormat::findMillisecondStart(ticks, formatted, df, p); LOGUNIT_ASSERT_EQUAL((int) CachedDateFormat::NO_MILLISECONDS, millisecondStart); } /** * Check pattern location for ABSOLUTE */ void test14() { DateFormatPtr df = DateFormatPtr(new SimpleDateFormat(LOG4CXX_STR("HH:mm:ss,SSS"))); apr_time_t ticks = 11142L * MICROSECONDS_PER_DAY; Pool p; LogString formatted; df->format(formatted, ticks, p); int millisecondStart = CachedDateFormat::findMillisecondStart(ticks, formatted, df, p); LOGUNIT_ASSERT_EQUAL(9, millisecondStart); } /** * Check pattern location for single S */ void test15() { DateFormatPtr df = DateFormatPtr(new SimpleDateFormat(LOG4CXX_STR("HH:mm:ss,S"))); apr_time_t ticks = 11142L * MICROSECONDS_PER_DAY; Pool p; LogString formatted; df->format(formatted, ticks, p); int millisecondStart = CachedDateFormat::findMillisecondStart(ticks, formatted, df, p); LOGUNIT_ASSERT_EQUAL((int) CachedDateFormat::UNRECOGNIZED_MILLISECONDS, millisecondStart); } /** * Check pattern location for single SS */ void test16() { DateFormatPtr df = DateFormatPtr(new SimpleDateFormat(LOG4CXX_STR("HH:mm:ss,SS"))); apr_time_t ticks = 11142L * MICROSECONDS_PER_DAY; Pool p; LogString formatted; df->format(formatted, ticks, p); int millisecondStart = CachedDateFormat::findMillisecondStart(ticks, formatted, df, p); LOGUNIT_ASSERT_EQUAL((int) CachedDateFormat::UNRECOGNIZED_MILLISECONDS, millisecondStart); } /** * Check caching when multiple SSS appear in pattern */ void test17() { apr_time_t jul2 = 12602L * MICROSECONDS_PER_DAY; LogString badPattern(LOG4CXX_STR("HH:mm:ss,SSS HH:mm:ss,SSS")); DateFormatPtr simpleFormat = DateFormatPtr(new SimpleDateFormat(badPattern)); simpleFormat->setTimeZone(TimeZone::getGMT()); DateFormatPtr cachedFormat = DateFormatPtr(new CachedDateFormat(simpleFormat, 1000000)); Pool p; LogString s; cachedFormat->format(s, jul2, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,000 00:00:00,000"), s); jul2 += 120000; s.erase(s.begin(), s.end()); simpleFormat->format(s, jul2, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,120 00:00:00,120"), s); s.erase(s.begin(), s.end()); int msStart = CachedDateFormat::findMillisecondStart(jul2, s, simpleFormat, p); LOGUNIT_ASSERT_EQUAL((int) CachedDateFormat::UNRECOGNIZED_MILLISECONDS, msStart); cachedFormat->format(s, jul2, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("00:00:00,120 00:00:00,120"), s) ; int maxValid = CachedDateFormat::getMaximumCacheValidity(badPattern); LOGUNIT_ASSERT_EQUAL(1000, maxValid); // Test overlapping millis with a magic string from CachedDateFormat for LOGCXX-420. s.clear(); jul2 += 286000; cachedFormat->format(s, jul2, p); msStart = CachedDateFormat::findMillisecondStart(jul2, s, simpleFormat, p); LOGUNIT_ASSERT_EQUAL((int) CachedDateFormat::UNRECOGNIZED_MILLISECONDS, msStart); s.clear(); jul2 += 203000; cachedFormat->format(s, jul2, p); msStart = CachedDateFormat::findMillisecondStart(jul2, s, simpleFormat, p); LOGUNIT_ASSERT_EQUAL((int) CachedDateFormat::UNRECOGNIZED_MILLISECONDS, msStart); } /** * Check that patterns not containing microseconds * are reported as being able to be cached for a full second. */ void test18() { int maxValid = CachedDateFormat::getMaximumCacheValidity( LOG4CXX_STR("yyyy-MM-dd")); LOGUNIT_ASSERT_EQUAL(1000000, maxValid); } /** * Check that patterns not containing 3 microseconds * are reported as being able to be cached for a full second. */ void test19() { int maxValid = CachedDateFormat::getMaximumCacheValidity( LOG4CXX_STR("yyyy-MM-dd SSS")); LOGUNIT_ASSERT_EQUAL(1000000, maxValid); } /** * Check that patterns not containing 2 S's * are reported as being able to be cached for only a millisecond. */ void test20() { int maxValid = CachedDateFormat::getMaximumCacheValidity( LOG4CXX_STR("yyyy-MM-dd SS")); LOGUNIT_ASSERT_EQUAL(1000, maxValid); } /** * Check that patterns not containing multi S groups * are reported as being able to be cached for only a millisecond. */ void test21() { int maxValid = CachedDateFormat::getMaximumCacheValidity( LOG4CXX_STR("yyyy-MM-dd SSS SSS")); LOGUNIT_ASSERT_EQUAL(1000, maxValid); } /** * Check that findMillisecondStart correctly handles timestamps * which use the magic millisecond value 654. */ void test22() { DateFormatPtr baseFormatter(new ISO8601DateFormat()); CachedDateFormat isoFormat(baseFormatter, 1000000); isoFormat.setTimeZone(TimeZone::getGMT()); Pool p; LogString formatted; isoFormat.format(formatted, 654000, p); LOGUNIT_ASSERT_EQUAL(LOG4CXX_STR("1970-01-01 00:00:00,654"), formatted); formatted.clear(); isoFormat.format(formatted, 999000, p); LOGUNIT_ASSERT_EQUAL(LOG4CXX_STR("1970-01-01 00:00:00,999"), formatted); formatted.clear(); isoFormat.format(formatted, 1654010, p); LOGUNIT_ASSERT_EQUAL(LOG4CXX_STR("1970-01-01 00:00:01,654"), formatted); formatted.clear(); isoFormat.format(formatted, 1999010, p); LOGUNIT_ASSERT_EQUAL(LOG4CXX_STR("1970-01-01 00:00:01,999"), formatted); } }; LOGUNIT_TEST_SUITE_REGISTRATION(CachedDateFormatTestCase); apache-log4cxx-1.3.1/src/test/cpp/helpers/datetimedateformattestcase.cpp0000644000175100001770000001575014721727031026001 0ustar runnerdocker/* * 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. */ #define __STDC_CONSTANT_MACROS #include #include #include "../logunit.h" #include #include "../insertwide.h" #include #include #include using namespace log4cxx; using namespace log4cxx::helpers; using namespace std; #define LOCALE_US "C" #if defined(_WIN32) #define LOCALE_FR "French_france" #else #define LOCALE_FR "fr_FR" #endif #define LOG4CXX_TEST 1 #include #if LOG4CXX_HAS_STD_LOCALE #include #include "localechanger.h" #define MAKE_LOCALE(ptr, id) \ std::locale loco(id); \ std::locale* ptr = &loco; #else #define MAKE_LOCALE(ptr, id) \ std::locale* ptr = NULL; #endif /** Unit test {@link DateTimeDateFormat}. */ LOGUNIT_CLASS(DateTimeDateFormatTestCase) { LOGUNIT_TEST_SUITE( DateTimeDateFormatTestCase ); LOGUNIT_TEST( test1 ); LOGUNIT_TEST( test2 ); LOGUNIT_TEST( test3 ); LOGUNIT_TEST( test4 ); LOGUNIT_TEST( test5 ); LOGUNIT_TEST( test6 ); #if LOG4CXX_HAS_STD_LOCALE LOGUNIT_TEST( test7 ); LOGUNIT_TEST( test8 ); #endif LOGUNIT_TEST_SUITE_END(); private: #define MICROSECONDS_PER_DAY APR_INT64_C(86400000000) /** Asserts that formatting the provided date results in the expected string. @param date Date date @param timeZone TimeZone timezone for conversion @param expected String expected string */ void assertFormattedTime( apr_time_t date, const std::locale * locale, const TimeZonePtr & timeZone, const LogString & expected ) { DateTimeDateFormat formatter(locale); formatter.setTimeZone(timeZone); LogString actual; Pool p; formatter.format(actual, date, p); LOGUNIT_ASSERT_EQUAL( expected, actual ); } public: /** Convert 02 Jan 2004 00:00:00 GMT for GMT. */ void test1() { // // 02 Jan 2004 00:00 GMT // apr_time_t jan2 = MICROSECONDS_PER_DAY * 12419; MAKE_LOCALE(localeUS, LOCALE_US); assertFormattedTime( jan2, localeUS, TimeZone::getGMT(), LOG4CXX_STR("02 Jan 2004 00:00:00,000")); } /** Convert 03 Jan 2004 00:00:00 GMT for America/Chicago. */ void test2() { // // 03 Jan 2004 00:00 GMT apr_time_t jan3 = MICROSECONDS_PER_DAY * 12420; MAKE_LOCALE(localeUS, LOCALE_US); assertFormattedTime( jan3, localeUS, TimeZone::getTimeZone(LOG4CXX_STR("GMT-6")), LOG4CXX_STR("02 Jan 2004 18:00:00,000")); } /** Convert 30 Jun 2004 00:00:00 GMT for GMT. */ void test3() { apr_time_t jun30 = MICROSECONDS_PER_DAY * 12599; MAKE_LOCALE(localeUS, LOCALE_US); assertFormattedTime( jun30, localeUS, TimeZone::getGMT(), LOG4CXX_STR("30 Jun 2004 00:00:00,000")); } /** Convert 29 Jun 2004 00:00:00 GMT for Chicago, daylight savings in effect. */ void test4() { apr_time_t jul1 = MICROSECONDS_PER_DAY * 12600; MAKE_LOCALE(localeUS, LOCALE_US); assertFormattedTime( jul1, localeUS, TimeZone::getTimeZone(LOG4CXX_STR("GMT-5")), LOG4CXX_STR("30 Jun 2004 19:00:00,000")); } /** Test multiple calls in close intervals. */ void test5() { // subsequent calls within one minute // are optimized to reuse previous formatted value // make a couple of nearly spaced calls apr_time_t ticks = MICROSECONDS_PER_DAY * 12601; MAKE_LOCALE(localeUS, LOCALE_US); assertFormattedTime( ticks, localeUS, TimeZone::getGMT(), LOG4CXX_STR("02 Jul 2004 00:00:00,000")); assertFormattedTime( ticks + 8000, localeUS, TimeZone::getGMT(), LOG4CXX_STR("02 Jul 2004 00:00:00,008")); assertFormattedTime( ticks + 17000, localeUS, TimeZone::getGMT(), LOG4CXX_STR("02 Jul 2004 00:00:00,017")); assertFormattedTime( ticks + 237000, localeUS, TimeZone::getGMT(), LOG4CXX_STR("02 Jul 2004 00:00:00,237")); assertFormattedTime( ticks + 1415000, localeUS, TimeZone::getGMT(), LOG4CXX_STR("02 Jul 2004 00:00:01,415")); } /** Check that caching does not disregard timezone. This test would fail for revision 1.4 of DateTimeDateFormat.java. */ void test6() { apr_time_t jul3 = MICROSECONDS_PER_DAY * 12602; MAKE_LOCALE(localeUS, LOCALE_US); assertFormattedTime( jul3, localeUS, TimeZone::getGMT(), LOG4CXX_STR("03 Jul 2004 00:00:00,000")); assertFormattedTime( jul3, localeUS, TimeZone::getTimeZone(LOG4CXX_STR("GMT-5")), LOG4CXX_STR("02 Jul 2004 19:00:00,000")); assertFormattedTime( jul3, localeUS, TimeZone::getGMT(), LOG4CXX_STR("03 Jul 2004 00:00:00,000")); } #if LOG4CXX_HAS_STD_LOCALE LogString formatDate(const std::locale & locale, const tm & date, const LogString & fmt) { // // output the using STL // std::basic_ostringstream buffer; #if defined(_MSC_VER) && _MSC_VER < 1300 _USEFAC(locale, std::time_put) .put(buffer, buffer, &date, fmt.c_str(), fmt.c_str() + fmt.length()); #else #if defined(_RWSTD_NO_TEMPLATE_ON_RETURN_TYPE) const std::time_put& facet = std::use_facet(locale, (std::time_put*) 0); #else const std::time_put& facet = std::use_facet >(locale); #endif facet.put(buffer, buffer, buffer.fill(), &date, fmt.c_str(), fmt.c_str() + fmt.length()); #endif return buffer.str(); } /** Check that format is locale sensitive. */ void test7() { apr_time_t avr11 = MICROSECONDS_PER_DAY * 12519; LocaleChanger localeChange(LOCALE_FR); if (localeChange.isEffective()) { LogString formatted; Pool p; SimpleDateFormat formatter(LOG4CXX_STR("MMM")); formatter.format(formatted, avr11, p); std::locale localeFR(LOCALE_FR); struct tm avr11tm = { 0, 0, 0, 11, 03, 104 }; LogString expected(formatDate(localeFR, avr11tm, LOG4CXX_STR("%b"))); LOGUNIT_ASSERT_EQUAL(expected, formatted); } } /** Check that format is locale sensitive. */ void test8() { apr_time_t apr11 = MICROSECONDS_PER_DAY * 12519; LocaleChanger localeChange(LOCALE_US); if (localeChange.isEffective()) { LogString formatted; Pool p; SimpleDateFormat formatter(LOG4CXX_STR("MMM")); formatter.setTimeZone(TimeZone::getGMT()); formatter.format(formatted, apr11, p); std::locale localeUS(LOCALE_US); struct tm apr11tm = { 0, 0, 0, 11, 03, 104 }; LogString expected(formatDate(localeUS, apr11tm, LOG4CXX_STR("%b"))); LOGUNIT_ASSERT_EQUAL(expected, formatted); } } #endif }; LOGUNIT_TEST_SUITE_REGISTRATION(DateTimeDateFormatTestCase); apache-log4cxx-1.3.1/src/test/cpp/helpers/propertiestestcase.cpp0000644000175100001770000002270714721727031024332 0ustar runnerdocker/* * 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. */ #include #include #include "../insertwide.h" #include "../logunit.h" using namespace log4cxx; using namespace log4cxx::helpers; LOGUNIT_CLASS(PropertiesTestCase) { LOGUNIT_TEST_SUITE(PropertiesTestCase); LOGUNIT_TEST(testLoad1); LOGUNIT_TEST(testTab1); LOGUNIT_TEST(testTab2); LOGUNIT_TEST(testTab3); LOGUNIT_TEST(testTab4); LOGUNIT_TEST(testTab5); LOGUNIT_TEST(testTab6); LOGUNIT_TEST(testTab7); LOGUNIT_TEST(testEscT1); LOGUNIT_TEST(testEscT2); LOGUNIT_TEST(testEscN1); LOGUNIT_TEST(testEscN2); LOGUNIT_TEST(testEscR1); LOGUNIT_TEST(testEscR2); LOGUNIT_TEST(testCRLF); LOGUNIT_TEST(testLF); LOGUNIT_TEST(testMixedLineEndings); LOGUNIT_TEST_SUITE_END(); public: void testLoad1() { // // read patternLayout1.properties FileInputStreamPtr propFile = FileInputStreamPtr( new FileInputStream(LOG4CXX_STR("input/patternLayout1.properties"))); Properties properties; properties.load(propFile); LogString pattern(properties.getProperty(LOG4CXX_STR("log4j.appender.testAppender.layout.ConversionPattern"))); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("%-5p - %m%n"), pattern); } /** * Test tab as separator between key and value, see LOGCXX-291. */ void testTab1() { FileInputStreamPtr propFile( new FileInputStream(LOG4CXX_STR("input/propertiestestcase.properties"))); Properties properties; properties.load(propFile); LogString actual(properties.getProperty(LOG4CXX_STR("propertiestestcase.tab1"))); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("tab delimited")), actual); } /** * Test tab as whitespace before key, see LOGCXX-291. */ void testTab2() { FileInputStreamPtr propFile( new FileInputStream(LOG4CXX_STR("input/propertiestestcase.properties"))); Properties properties; properties.load(propFile); LogString actual(properties.getProperty(LOG4CXX_STR("propertiestestcase.tab2"))); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("tab before key")), actual); } /** * Test tab as escaped within key, see LOGCXX-291. */ void testTab3() { FileInputStreamPtr propFile( new FileInputStream(LOG4CXX_STR("input/propertiestestcase.properties"))); Properties properties; properties.load(propFile); LogString key(LOG4CXX_STR("propertiestestcase.tab3")); key.append(1, 0x09); LogString actual(properties.getProperty(key)); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("key contains tab")), actual); } /** * Test tab after delimitor, see LOGCXX-291. */ void testTab4() { FileInputStreamPtr propFile( new FileInputStream(LOG4CXX_STR("input/propertiestestcase.properties"))); Properties properties; properties.load(propFile); LogString actual(properties.getProperty(LOG4CXX_STR("propertiestestcase.tab4"))); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("tab after equals")), actual); } /** * Test tab after continuation in key, see LOGCXX-291. */ void testTab5() { FileInputStreamPtr propFile( new FileInputStream(LOG4CXX_STR("input/propertiestestcase.properties"))); Properties properties; properties.load(propFile); LogString actual(properties.getProperty(LOG4CXX_STR("propertiestestcase.tab5"))); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("tab after continue")), actual); } /** * Test tab escaped in value, see LOGCXX-291. */ void testTab6() { FileInputStreamPtr propFile( new FileInputStream(LOG4CXX_STR("input/propertiestestcase.properties"))); Properties properties; properties.load(propFile); LogString actual(properties.getProperty(LOG4CXX_STR("propertiestestcase.tab6"))); LogString expected(1, 0x09); expected.append(LOG4CXX_STR(" in value")); LOGUNIT_ASSERT_EQUAL(expected, actual); } /** * Test tab in value continuation, see LOGCXX-291. */ void testTab7() { FileInputStreamPtr propFile( new FileInputStream(LOG4CXX_STR("input/propertiestestcase.properties"))); Properties properties; properties.load(propFile); LogString actual(properties.getProperty(LOG4CXX_STR("propertiestestcase.tab7"))); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("continuedvalue")), actual); } /** * Test tab as escaped within key, see LOGCXX-293. */ void testEscT1() { FileInputStreamPtr propFile( new FileInputStream(LOG4CXX_STR("input/propertiestestcase.properties"))); Properties properties; properties.load(propFile); LogString key(LOG4CXX_STR("propertiestestcase.esct1")); key.append(1, 0x09); LogString actual(properties.getProperty(key)); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("key contains tab")), actual); } /** * Test tab escaped in value, see LOGCXX-293. */ void testEscT2() { FileInputStreamPtr propFile( new FileInputStream(LOG4CXX_STR("input/propertiestestcase.properties"))); Properties properties; properties.load(propFile); LogString actual(properties.getProperty(LOG4CXX_STR("propertiestestcase.esct2"))); LogString expected(1, 0x09); expected.append(LOG4CXX_STR(" in value")); LOGUNIT_ASSERT_EQUAL(expected, actual); } /** * Test \n within key, see LOGCXX-293. */ void testEscN1() { FileInputStreamPtr propFile( new FileInputStream(LOG4CXX_STR("input/propertiestestcase.properties"))); Properties properties;; properties.load(propFile); LogString key(LOG4CXX_STR("propertiestestcase.escn1")); key.append(1, 0x0A); LogString actual(properties.getProperty(key)); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("key contains lf")), actual); } /** * Test \n in value, see LOGCXX-293. */ void testEscN2() { FileInputStreamPtr propFile( new FileInputStream(LOG4CXX_STR("input/propertiestestcase.properties"))); Properties properties; properties.load(propFile); LogString actual(properties.getProperty(LOG4CXX_STR("propertiestestcase.escn2"))); LogString expected(1, 0x0A); expected.append(LOG4CXX_STR(" in value")); LOGUNIT_ASSERT_EQUAL(expected, actual); } /** * Test \r within key, see LOGCXX-293. */ void testEscR1() { FileInputStreamPtr propFile( new FileInputStream(LOG4CXX_STR("input/propertiestestcase.properties"))); Properties properties; properties.load(propFile); LogString key(LOG4CXX_STR("propertiestestcase.escr1")); key.append(1, 0x0D); LogString actual(properties.getProperty(key)); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("key contains cr")), actual); } /** * Test \r in value, see LOGCXX-293. */ void testEscR2() { FileInputStreamPtr propFile( new FileInputStream(LOG4CXX_STR("input/propertiestestcase.properties"))); Properties properties; properties.load(propFile); LogString actual(properties.getProperty(LOG4CXX_STR("propertiestestcase.escr2"))); LogString expected(1, 0x0D); expected.append(LOG4CXX_STR(" in value")); LOGUNIT_ASSERT_EQUAL(expected, actual); } void testCRLF(){ FileInputStreamPtr propFile( new FileInputStream(LOG4CXX_STR("input/propertiestestcase-crlf.properties"))); Properties properties; properties.load(propFile); LogString value1(properties.getProperty(LOG4CXX_STR("propertiestestcase.value1"))); LogString value2(properties.getProperty(LOG4CXX_STR("propertiestestcase.value2"))); LogString value3(properties.getProperty(LOG4CXX_STR("propertiestestcase.value3"))); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("hi this is a test")), value1); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("multiline")), value2); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("some_value")), value3); } void testLF(){ FileInputStreamPtr propFile( new FileInputStream(LOG4CXX_STR("input/propertiestestcase-lf.properties"))); Properties properties; properties.load(propFile); LogString value1(properties.getProperty(LOG4CXX_STR("propertiestestcase.value1"))); LogString value2(properties.getProperty(LOG4CXX_STR("propertiestestcase.value2"))); LogString value3(properties.getProperty(LOG4CXX_STR("propertiestestcase.value3"))); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("hi this is a test")), value1); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("multiline")), value2); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("some_value")), value3); } void testMixedLineEndings(){ FileInputStreamPtr propFile( new FileInputStream(LOG4CXX_STR("input/propertiestestcase-mixed.properties"))); Properties properties; properties.load(propFile); LogString value1(properties.getProperty(LOG4CXX_STR("propertiestestcase.value1"))); LogString value2(properties.getProperty(LOG4CXX_STR("propertiestestcase.value2"))); LogString value3(properties.getProperty(LOG4CXX_STR("propertiestestcase.value3"))); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("hi this is a test")), value1); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("something")), value2); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("some_value")), value3); } }; LOGUNIT_TEST_SUITE_REGISTRATION(PropertiesTestCase); apache-log4cxx-1.3.1/src/test/cpp/helpers/iso8601dateformattestcase.cpp0000644000175100001770000001132414721727031025307 0ustar runnerdocker/* * 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. */ #include #include #include "../logunit.h" #define LOG4CXX_TEST #include #if LOG4CXX_HAS_STD_LOCALE #include #endif #include "../insertwide.h" #include #include using namespace log4cxx; using namespace log4cxx::helpers; /** Unit test {@link ISO8601DateFormat}. */ LOGUNIT_CLASS(ISO8601DateFormatTestCase) { LOGUNIT_TEST_SUITE( ISO8601DateFormatTestCase ); LOGUNIT_TEST( test1 ); LOGUNIT_TEST( test2 ); LOGUNIT_TEST( test3 ); LOGUNIT_TEST( test4 ); LOGUNIT_TEST( test5 ); LOGUNIT_TEST( test6 ); LOGUNIT_TEST( test7 ); LOGUNIT_TEST_SUITE_END(); /** * Asserts that formatting the provided date results * in the expected string. * * @param date Date date * @param timeZone TimeZone timezone for conversion * @param expected String expected string */ void assertFormattedTime(log4cxx_time_t date, const TimeZonePtr & timeZone, const LogString & expected) { ISO8601DateFormat formatter; formatter.setTimeZone(timeZone); LogString actual; Pool p; formatter.format(actual, date, p); LOGUNIT_ASSERT_EQUAL(expected, actual); } public: /** * Convert 02 Jan 2004 00:00:00 GMT for GMT. */ void test1() { log4cxx_time_t jan2 = Date::getMicrosecondsPerDay() * 12419; assertFormattedTime(jan2, TimeZone::getGMT(), LOG4CXX_STR("2004-01-02 00:00:00,000")); } /** * Convert 03 Jan 2004 00:00:00 GMT for America/Chicago. */ void test2() { // // 03 Jan 2004 00:00 GMT // (asking for the same time at a different timezone // will ignore the change of timezone) log4cxx_time_t jan3 = Date::getMicrosecondsPerDay() * 12420; assertFormattedTime(jan3, TimeZone::getTimeZone(LOG4CXX_STR("GMT-6")), LOG4CXX_STR("2004-01-02 18:00:00,000")); } /** * Convert 30 Jun 2004 00:00:00 GMT for GMT. */ void test3() { log4cxx_time_t jun30 = Date::getMicrosecondsPerDay() * 12599; assertFormattedTime(jun30, TimeZone::getGMT(), LOG4CXX_STR("2004-06-30 00:00:00,000")); } /** * Convert 1 Jul 2004 00:00:00 GMT for Chicago, daylight savings in effect. */ void test4() { log4cxx_time_t jul1 = Date::getMicrosecondsPerDay() * 12600; assertFormattedTime(jul1, TimeZone::getTimeZone(LOG4CXX_STR("GMT-5")), LOG4CXX_STR("2004-06-30 19:00:00,000")); } /** * Test multiple calls in close intervals. */ void test5() { // subsequent calls within one minute // are optimized to reuse previous formatted value // make a couple of nearly spaced calls log4cxx_time_t ticks = Date::getMicrosecondsPerDay() * 12601; assertFormattedTime(ticks, TimeZone::getGMT(), LOG4CXX_STR("2004-07-02 00:00:00,000")); assertFormattedTime(ticks + 8000, TimeZone::getGMT(), LOG4CXX_STR("2004-07-02 00:00:00,008")); assertFormattedTime(ticks + 17000, TimeZone::getGMT(), LOG4CXX_STR("2004-07-02 00:00:00,017")); assertFormattedTime(ticks + 237000, TimeZone::getGMT(), LOG4CXX_STR("2004-07-02 00:00:00,237")); assertFormattedTime(ticks + 1415000, TimeZone::getGMT(), LOG4CXX_STR("2004-07-02 00:00:01,415")); } /** * Check that caching does not disregard timezone. * This test would fail for revision 1.4 of DateTimeDateFormat.java. */ void test6() { log4cxx_time_t jul3 = Date::getMicrosecondsPerDay() * 12602; assertFormattedTime(jul3, TimeZone::getGMT(), LOG4CXX_STR("2004-07-03 00:00:00,000")); assertFormattedTime(jul3, TimeZone::getTimeZone(LOG4CXX_STR("GMT-5")), LOG4CXX_STR("2004-07-02 19:00:00,000")); assertFormattedTime(jul3, TimeZone::getGMT(), LOG4CXX_STR("2004-07-03 00:00:00,000")); } /** * Checks that numberFormat is implemented. */ void test7() { LogString number; ISO8601DateFormat formatter; Pool p; formatter.numberFormat(number, 87, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("87"), number); } }; LOGUNIT_TEST_SUITE_REGISTRATION(ISO8601DateFormatTestCase); apache-log4cxx-1.3.1/src/test/cpp/helpers/threadutilitytestcase.cpp0000644000175100001770000000634114721727031025025 0ustar runnerdocker/* * 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. */ #include "../logunit.h" #include "util/compare.h" #include #include #include #include #include using namespace log4cxx; using namespace log4cxx::helpers; LOGUNIT_CLASS(ThreadUtilityTest) { LOGUNIT_TEST_SUITE(ThreadUtilityTest); LOGUNIT_TEST(testNullFunctions); LOGUNIT_TEST(testCustomFunctions); LOGUNIT_TEST(testDefaultFunctions); #if LOG4CXX_HAS_PTHREAD_SETNAME || defined(_WIN32) LOGUNIT_TEST(testThreadNameLogging); #endif LOGUNIT_TEST_SUITE_END(); #ifdef _DEBUG struct Fixture { Fixture() { LogLog::setInternalDebugging(true); } } suiteFixture; #endif public: void testNullFunctions() { auto thrUtil = ThreadUtility::instance(); thrUtil->configureFuncs( nullptr, nullptr, nullptr ); std::thread t = thrUtil->createThread( LOG4CXX_STR("FooName"), []() {} ); t.join(); } void testCustomFunctions() { auto thrUtil = ThreadUtility::instance(); int num_pre = 0; int num_started = 0; int num_run = 0; int num_post = 0; thrUtil->configureFuncs( [&num_pre]() { num_pre++; }, [&num_started]( LogString, std::thread::id, std::thread::native_handle_type ) { num_started++; }, [&num_post]() { num_post++; } ); std::thread t = thrUtil->createThread( LOG4CXX_STR("FooName"), [&num_run]() { num_run++; } ); t.join(); LOGUNIT_ASSERT_EQUAL( num_pre, 1 ); LOGUNIT_ASSERT_EQUAL( num_started, 1 ); LOGUNIT_ASSERT_EQUAL( num_run, 1 ); LOGUNIT_ASSERT_EQUAL( num_post, 1 ); } void testDefaultFunctions() { ThreadUtility::configure( ThreadConfigurationType::BlockSignalsAndNameThread ); auto thrUtil = ThreadUtility::instance(); std::thread t = thrUtil->createThread( LOG4CXX_STR("FooName"), []() {} ); t.join(); } void testThreadNameLogging() { auto layout = std::make_shared(LOG4CXX_STR("%T %m%n")); LogString logFileName(LOG4CXX_STR("output/threadnametestcase.log")); AppenderPtr appender(new FileAppender(layout, logFileName, false)); auto logger = LogManager::getRootLogger(); logger->addAppender(appender); std::thread t = ThreadUtility::instance()->createThread( LOG4CXX_STR("FooName"), [logger]() { LOG4CXX_DEBUG(logger, "Test message"); }); t.join(); LOGUNIT_ASSERT(Compare::compare(logFileName, LOG4CXX_FILE("witness/threadnametestcase.1"))); } }; LOGUNIT_TEST_SUITE_REGISTRATION(ThreadUtilityTest); apache-log4cxx-1.3.1/src/test/cpp/helpers/absolutetimedateformattestcase.cpp0000644000175100001770000001301114721727031026666 0ustar runnerdocker/* * 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. */ #include "../logunit.h" #include #include #include "../insertwide.h" #include #include #include //Define INT64_C for compilers that don't have it #if (!defined(INT64_C)) #define INT64_C(value) value ## LL #endif using namespace log4cxx; using namespace log4cxx::helpers; /** Unit test {@link AbsoluteTimeDateFormat}. */ LOGUNIT_CLASS(AbsoluteTimeDateFormatTestCase) { LOGUNIT_TEST_SUITE(AbsoluteTimeDateFormatTestCase); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST(test3); LOGUNIT_TEST(test4); LOGUNIT_TEST(test5); LOGUNIT_TEST(test6); LOGUNIT_TEST(test7); LOGUNIT_TEST(test8); LOGUNIT_TEST_SUITE_END(); public: /** * Asserts that formatting the provided date results * in the expected string. * * @param date Date date * @param timeZone TimeZone timezone for conversion * @param expected String expected string */ private: void assertFormattedTime(apr_time_t date, const TimeZonePtr & timeZone, const LogString & expected) { AbsoluteTimeDateFormat formatter; formatter.setTimeZone(timeZone); LogString actual; Pool p; formatter.format(actual, date, p); LOGUNIT_ASSERT_EQUAL(expected, actual); } #define MICROSECONDS_PER_DAY APR_INT64_C(86400000000) public: /** * Convert 02 Jan 2004 00:00:00 GMT for GMT. */ void test1() { // // 02 Jan 2004 00:00 GMT // apr_time_t jan2 = MICROSECONDS_PER_DAY * 12419; assertFormattedTime(jan2, TimeZone::getGMT(), LOG4CXX_STR("00:00:00,000")); } /** * Convert 03 Jan 2004 00:00:00 GMT for America/Chicago. */ void test2() { // // 03 Jan 2004 00:00 GMT // (asking for the same time at a different timezone // will ignore the change of timezone) apr_time_t jan2 = MICROSECONDS_PER_DAY * 12420; assertFormattedTime(jan2, TimeZone::getTimeZone(LOG4CXX_STR("GMT-6")), LOG4CXX_STR("18:00:00,000")); } /** * Convert 29 Jun 2004 00:00:00 GMT for GMT. */ void test3() { apr_time_t jun29 = MICROSECONDS_PER_DAY * 12599; assertFormattedTime(jun29, TimeZone::getGMT(), LOG4CXX_STR("00:00:00,000")); } /** * Convert 29 Jun 2004 00:00:00 GMT for Chicago, daylight savings in effect. */ void test4() { apr_time_t jun30 = MICROSECONDS_PER_DAY * 12600; // // log4cxx doesn't support non-fixed timezones at this time // passing the fixed equivalent to Chicago's Daylight Savings Time // assertFormattedTime(jun30, TimeZone::getTimeZone(LOG4CXX_STR("GMT-5")), LOG4CXX_STR("19:00:00,000")); } /** * Test multiple calls in close intervals. */ void test5() { // subsequent calls within one minute // are optimized to reuse previous formatted value // make a couple of nearly spaced calls apr_time_t ticks = MICROSECONDS_PER_DAY * 12601; assertFormattedTime(ticks, TimeZone::getGMT(), LOG4CXX_STR("00:00:00,000")); assertFormattedTime(ticks + 8000, TimeZone::getGMT(), LOG4CXX_STR("00:00:00,008")); assertFormattedTime(ticks + 17000, TimeZone::getGMT(), LOG4CXX_STR("00:00:00,017")); assertFormattedTime(ticks + 237000, TimeZone::getGMT(), LOG4CXX_STR("00:00:00,237")); assertFormattedTime(ticks + 1415000, TimeZone::getGMT(), LOG4CXX_STR("00:00:01,415")); } /** * Check that caching does not disregard timezone. * This test would fail for revision 1.4 of AbsoluteTimeDateFormat.java. */ void test6() { apr_time_t jul2 = MICROSECONDS_PER_DAY * 12602; assertFormattedTime(jul2, TimeZone::getGMT(), LOG4CXX_STR("00:00:00,000")); assertFormattedTime(jul2, TimeZone::getTimeZone(LOG4CXX_STR("GMT-5")), LOG4CXX_STR("19:00:00,000")); } /** * Test multiple calls in close intervals predating 1 Jan 1970. */ void test7() { // subsequent calls within one minute // are optimized to reuse previous formatted value // make a couple of nearly spaced calls apr_time_t ticks = MICROSECONDS_PER_DAY * -7; assertFormattedTime(ticks, TimeZone::getGMT(), LOG4CXX_STR("00:00:00,000")); #if defined(_WIN32) // // These tests fail on Unix due to bug in APR's explode_time // // assertFormattedTime(ticks + 8000, TimeZone::getGMT(), LOG4CXX_STR("00:00:00,008")); // assertFormattedTime(ticks + 17000, TimeZone::getGMT(), LOG4CXX_STR("00:00:00,017")); // assertFormattedTime(ticks + 237000, TimeZone::getGMT(), LOG4CXX_STR("00:00:00,237")); // assertFormattedTime(ticks + 1415000, TimeZone::getGMT(), LOG4CXX_STR("00:00:01,415")); #endif } /** * Checks that numberFormat works as expected. */ void test8() { Pool p; LogString numb; AbsoluteTimeDateFormat formatter; formatter.numberFormat(numb, 87, p); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("87"), numb); } }; LOGUNIT_TEST_SUITE_REGISTRATION(AbsoluteTimeDateFormatTestCase); apache-log4cxx-1.3.1/src/test/cpp/helpers/transcodertestcase.cpp0000644000175100001770000002530214721727031024274 0ustar runnerdocker/* * 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. */ #include #include "../insertwide.h" #include "../logunit.h" #if LOG4CXX_CFSTRING_API #include #endif using namespace log4cxx; using namespace log4cxx::helpers; LOGUNIT_CLASS(TranscoderTestCase) { LOGUNIT_TEST_SUITE(TranscoderTestCase); LOGUNIT_TEST(decode1); #if LOG4CXX_WCHAR_T_API LOGUNIT_TEST(decode2); #endif LOGUNIT_TEST(decode3); #if LOG4CXX_WCHAR_T_API LOGUNIT_TEST(decode4); #endif #if LOG4CXX_CFSTRING_API LOGUNIT_TEST(decode5); #endif LOGUNIT_TEST(decode7); LOGUNIT_TEST(decode8); #if LOG4CXX_WCHAR_T_API LOGUNIT_TEST(encode1); #endif LOGUNIT_TEST(encode2); #if LOG4CXX_WCHAR_T_API LOGUNIT_TEST(encode3); LOGUNIT_TEST(encode3_1); #endif LOGUNIT_TEST(encode4); #if LOG4CXX_WCHAR_T_API LOGUNIT_TEST(encode5); #endif LOGUNIT_TEST(encode6); #if LOG4CXX_CFSTRING_API LOGUNIT_TEST(encode7); #endif LOGUNIT_TEST(testDecodeUTF8_1); LOGUNIT_TEST(testDecodeUTF8_2); LOGUNIT_TEST(testDecodeUTF8_3); LOGUNIT_TEST(testDecodeUTF8_4); #if LOG4CXX_UNICHAR_API LOGUNIT_TEST(udecode2); LOGUNIT_TEST(udecode4); LOGUNIT_TEST(uencode1); LOGUNIT_TEST(uencode3); LOGUNIT_TEST(uencode5); #endif #if LOG4CXX_LOGCHAR_IS_UTF8 LOGUNIT_TEST(encodeCharsetName1); LOGUNIT_TEST(encodeCharsetName2); LOGUNIT_TEST(encodeCharsetName3); #endif LOGUNIT_TEST_SUITE_END(); public: void decode1() { const char* greeting = "Hello, World"; LogString decoded(LOG4CXX_STR("foo\n")); Transcoder::decode(greeting, decoded); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("foo\nHello, World"), decoded); } #if LOG4CXX_WCHAR_T_API void decode2() { const wchar_t* greeting = L"Hello, World"; LogString decoded(LOG4CXX_STR("foo\n")); Transcoder::decode(greeting, decoded); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("foo\nHello, World"), decoded); } #endif void decode3() { const char* nothing = ""; LogString decoded(LOG4CXX_STR("foo\n")); Transcoder::decode(nothing, decoded); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("foo\n"), decoded); } #if LOG4CXX_WCHAR_T_API void decode4() { const wchar_t* nothing = L""; LogString decoded(LOG4CXX_STR("foo\n")); Transcoder::decode(nothing, decoded); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("foo\n"), decoded); } #endif #if LOG4CXX_CFSTRING_API void decode5() { LogString nothing; LogString decoded(LOG4CXX_STR("foo\n")); Transcoder::decode(nothing, decoded); LOGUNIT_ASSERT_EQUAL(LOG4CXX_STR("foo\n"), decoded); } #endif enum { BUFSIZE = 255 }; void decode7() { // // normal characters striding over a buffer boundary // std::string longMsg(BUFSIZE - 2, 'A'); longMsg.append("Hello"); LogString decoded; Transcoder::decode(longMsg, decoded); LOGUNIT_ASSERT_EQUAL((size_t) BUFSIZE + 3, decoded.length()); LOGUNIT_ASSERT_EQUAL(LogString(BUFSIZE - 2, LOG4CXX_STR('A')), decoded.substr(0, BUFSIZE - 2)); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("Hello"), decoded.substr(BUFSIZE - 2 )); } void decode8() { std::string msg("Hello, World."); LogString actual; Transcoder::decode(msg, actual); LogString expected(LOG4CXX_STR("Hello, World.")); LOGUNIT_ASSERT_EQUAL(expected, actual); } #if LOG4CXX_WCHAR_T_API void encode1() { const LogString greeting(LOG4CXX_STR("Hello, World")); std::wstring encoded; Transcoder::encode(greeting, encoded); LOGUNIT_ASSERT_EQUAL((std::wstring) L"Hello, World", encoded); } #endif void encode2() { const LogString greeting(LOG4CXX_STR("Hello, World")); std::string encoded; Transcoder::encode(greeting, encoded); LOGUNIT_ASSERT_EQUAL((std::string) "Hello, World", encoded); } #if LOG4CXX_WCHAR_T_API void encode3() { LogString greeting(BUFSIZE - 3, LOG4CXX_STR('A')); greeting.append(LOG4CXX_STR("Hello")); std::wstring encoded; Transcoder::encode(greeting, encoded); std::wstring manyAs(BUFSIZE - 3, L'A'); LOGUNIT_ASSERT_EQUAL(manyAs, encoded.substr(0, BUFSIZE - 3)); LOGUNIT_ASSERT_EQUAL(std::wstring(L"Hello"), encoded.substr(BUFSIZE - 3)); } void encode3_1() { // Test invalid multibyte string LogString greeting; greeting.push_back( logchar(0xff) ); std::wstring encoded; Transcoder::encode(greeting, encoded); std::wstring expected; expected.push_back( log4cxx::helpers::Transcoder::LOSSCHAR ); LOGUNIT_ASSERT_EQUAL(encoded, expected ); } #endif void encode4() { LogString greeting(BUFSIZE - 3, LOG4CXX_STR('A')); greeting.append(LOG4CXX_STR("Hello")); std::string encoded; Transcoder::encode(greeting, encoded); std::string manyAs(BUFSIZE - 3, 'A'); LOGUNIT_ASSERT_EQUAL(manyAs, encoded.substr(0, BUFSIZE - 3)); LOGUNIT_ASSERT_EQUAL(std::string("Hello"), encoded.substr(BUFSIZE - 3)); } #if LOG4CXX_WCHAR_T_API void encode5() { // arbitrary, hopefully meaningless, characters from // Latin, Arabic, Armenian, Bengali, CJK and Cyrillic const wchar_t greeting[] = { L'A', 0x0605, 0x0530, 0x984, 0x40E3, 0x400, 0 }; // // decode to LogString (UTF-16 or UTF-8) // LogString decoded; Transcoder::decode(greeting, decoded); // // decode to wstring // std::wstring encoded; Transcoder::encode(decoded, encoded); // // should be lossless // LOGUNIT_ASSERT_EQUAL((std::wstring) greeting, encoded); } #endif void encode6() { #if LOG4CXX_LOGCHAR_IS_WCHAR || LOG4CXX_LOGCHAR_IS_UNICHAR // arbitrary, hopefully meaningless, characters from // Latin, Arabic, Armenian, Bengali, CJK and Cyrillic const logchar greeting[] = { L'A', 0x0605, 0x0530, 0x984, 0x40E3, 0x400, 0 }; #endif #if LOG4CXX_LOGCHAR_IS_UTF8 const char greeting[] = { 'A', (char) 0xD8, (char) 0x85, (char) 0xD4, (char) 0xB0, (char) 0xE0, (char) 0xCC, (char) 0x84, (char) 0xE8, (char) 0x87, (char) 0x83, (char) 0xD0, (char) 0x80, 0 }; #endif // // decode to LogString (UTF-16 or UTF-8) // LogString decoded; Transcoder::decode(greeting, decoded); // // decode to wstring // std::string encoded; // // likely 'A\u0605\u0530\u0984\u40E3\u0400' // Transcoder::encode(decoded, encoded); } #if LOG4CXX_CFSTRING_API void encode7() { const LogString greeting(LOG4CXX_STR("Hello, World")); CFStringRef encoded = Transcoder::encode(greeting); LogString decoded; Transcoder::decode(encoded, decoded); LOGUNIT_ASSERT_EQUAL(LOG4CXX_STR("Hello, World"), decoded); } #endif void testDecodeUTF8_1() { std::string src("a"); LogString out; Transcoder::decodeUTF8(src, out); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("a")), out); } void testDecodeUTF8_2() { std::string src(1, char(0x80)); LogString out; Transcoder::decodeUTF8(src, out); LOGUNIT_ASSERT_EQUAL(LogString(1, Transcoder::LOSSCHAR), out); } void testDecodeUTF8_3() { std::string src("\xC2"); LogString out; Transcoder::decodeUTF8(src, out); LOGUNIT_ASSERT_EQUAL(LogString(1, Transcoder::LOSSCHAR), out); } void testDecodeUTF8_4() { std::string src("\xC2\xA9"); LogString out; Transcoder::decodeUTF8(src, out); LogString::const_iterator iter = out.begin(); unsigned int sv = Transcoder::decode(out, iter); LOGUNIT_ASSERT_EQUAL((unsigned int) 0xA9, sv); LOGUNIT_ASSERT_EQUAL(true, iter == out.end()); } #if LOG4CXX_UNICHAR_API void udecode2() { const UniChar greeting[] = { 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', 0 }; LogString decoded(LOG4CXX_STR("foo\n")); Transcoder::decode(greeting, decoded); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("foo\nHello, World"), decoded); } void udecode4() { const UniChar nothing[] = { 0 }; LogString decoded(LOG4CXX_STR("foo\n")); Transcoder::decode(nothing, decoded); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("foo\n"), decoded); } void uencode1() { const LogString greeting(LOG4CXX_STR("Hello, World")); std::basic_string encoded; Transcoder::encode(greeting, encoded); const UniChar expected[] = { 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', 0 }; LOGUNIT_ASSERT_EQUAL(std::basic_string(expected), encoded); } void uencode3() { LogString greeting(BUFSIZE - 3, LOG4CXX_STR('A')); greeting.append(LOG4CXX_STR("Hello")); std::basic_string encoded; Transcoder::encode(greeting, encoded); std::basic_string manyAs(BUFSIZE - 3, 'A'); LOGUNIT_ASSERT_EQUAL(manyAs, encoded.substr(0, BUFSIZE - 3)); const UniChar hello[] = { 'H', 'e', 'l', 'l', 'o', 0 }; LOGUNIT_ASSERT_EQUAL(std::basic_string(hello), encoded.substr(BUFSIZE - 3)); } void uencode5() { // arbitrary, hopefully meaningless, characters from // Latin, Arabic, Armenian, Bengali, CJK and Cyrillic const UniChar greeting[] = { L'A', 0x0605, 0x0530, 0x984, 0x40E3, 0x400, 0 }; // // decode to LogString (UTF-16 or UTF-8) // LogString decoded; Transcoder::decode(greeting, decoded); // // decode to basic_string // std::basic_string encoded; Transcoder::encode(decoded, encoded); // // should be lossless // LOGUNIT_ASSERT_EQUAL(std::basic_string(greeting), encoded); } #endif #if LOG4CXX_LOGCHAR_IS_UTF8 void encodeCharsetName1() { const logchar utf8[] = { 0x75, 0x74, 0x66, 0x2D, 0x38, 0x00 }; std::string encoded(Transcoder::encodeCharsetName(LogString(utf8))); LOGUNIT_ASSERT_EQUAL(std::string("utf-8"), encoded); } void encodeCharsetName2() { logchar lascii[0x60]; char ascii[0x60]; for (int i = 0; i < 0x5F; i++) { lascii[i] = i + 0x20; ascii[i] = i + 0x20; } lascii[0x5F] = 0; ascii[0x5F] = 0; std::string encoded(Transcoder::encodeCharsetName(LogString(ascii))); LOGUNIT_ASSERT_EQUAL(std::string(" !\"#$%&'()*+,-./"), encoded.substr(0, 0x10)); if (0x40 == 'A') { LOGUNIT_ASSERT_EQUAL(std::string(ascii), encoded); } } void encodeCharsetName3() { logchar unsupported[] = { 0x1F, 0x7F, static_cast(0x80), static_cast(0x81), 0x00 }; std::string encoded(Transcoder::encodeCharsetName(LogString(unsupported))); LOGUNIT_ASSERT_EQUAL(std::string("????"), encoded); } #endif }; LOGUNIT_TEST_SUITE_REGISTRATION(TranscoderTestCase); apache-log4cxx-1.3.1/src/test/cpp/helpers/messagebuffertest.cpp0000644000175100001770000001675214721727031024123 0ustar runnerdocker/* * 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. */ #include #include #include "../insertwide.h" #include "../logunit.h" #include #include #include #include #include "util/compare.h" #if LOG4CXX_CFSTRING_API #include #endif using namespace log4cxx; using namespace log4cxx::helpers; /** * Test MessageBuffer. */ LOGUNIT_CLASS(MessageBufferTest) { LOGUNIT_TEST_SUITE(MessageBufferTest); LOGUNIT_TEST(testInsertChar); LOGUNIT_TEST(testInsertConstStr); LOGUNIT_TEST(testInsertStr); LOGUNIT_TEST(testInsertString); LOGUNIT_TEST(testInsertNull); LOGUNIT_TEST(testInsertInt); LOGUNIT_TEST(testInsertManipulator); LOGUNIT_TEST(testBaseChange); #if LOG4CXX_WCHAR_T_API LOGUNIT_TEST(testInsertConstWStr); LOGUNIT_TEST(testInsertWString); LOGUNIT_TEST(testInsertWStr); #endif #if LOG4CXX_UNICHAR_API LOGUNIT_TEST(testInsertConstUStr); LOGUNIT_TEST(testInsertUString); #endif #if LOG4CXX_CFSTRING_API LOGUNIT_TEST(testInsertCFString); #endif LOGUNIT_TEST_SUITE_END(); #ifdef _DEBUG struct Fixture { Fixture() { helpers::LogLog::setInternalDebugging(true); } } suiteFixture; #endif public: void testInsertChar() { MessageBuffer buf; std::string greeting("Hello, World"); CharMessageBuffer& retval = buf << "Hello, Worl" << 'd'; LOGUNIT_ASSERT_EQUAL(greeting, buf.str(retval)); LOGUNIT_ASSERT_EQUAL(false, buf.hasStream()); } void testInsertConstStr() { MessageBuffer buf; std::string greeting("Hello, World"); CharMessageBuffer& retval = buf << "Hello" << ", World"; LOGUNIT_ASSERT_EQUAL(greeting, buf.str(retval)); LOGUNIT_ASSERT_EQUAL(false, buf.hasStream()); } void testInsertStr() { MessageBuffer buf; std::string greeting("Hello, World"); char* part1 = (char*) malloc(10 * sizeof(wchar_t)); strcpy(part1, "Hello"); char* part2 = (char*) malloc(10 * sizeof(wchar_t)); strcpy(part2, ", World"); CharMessageBuffer& retval = buf << part1 << part2; free(part1); free(part2); LOGUNIT_ASSERT_EQUAL(greeting, buf.str(retval)); LOGUNIT_ASSERT_EQUAL(false, buf.hasStream()); } void testInsertString() { MessageBuffer buf; std::string greeting("Hello, World"); CharMessageBuffer& retval = buf << std::string("Hello") << std::string(", World"); LOGUNIT_ASSERT_EQUAL(greeting, buf.str(retval)); LOGUNIT_ASSERT_EQUAL(false, buf.hasStream()); } void testInsertNull() { MessageBuffer buf; std::string greeting("Hello, null"); CharMessageBuffer& retval = buf << "Hello, " << (const char*) 0; LOGUNIT_ASSERT_EQUAL(greeting, buf.str(retval)); LOGUNIT_ASSERT_EQUAL(false, buf.hasStream()); } void testInsertInt() { MessageBuffer buf; std::string greeting("Hello, 5"); std::ostream& retval = buf << "Hello, " << 5; LOGUNIT_ASSERT_EQUAL(greeting, buf.str(retval)); LOGUNIT_ASSERT_EQUAL(true, buf.hasStream()); } void testInsertManipulator() { MessageBuffer buf; std::string greeting("pi=3.142"); std::ostream& retval = buf << "pi=" << std::setprecision(4) << 3.1415926; LOGUNIT_ASSERT_EQUAL(greeting, buf.str(retval)); LOGUNIT_ASSERT_EQUAL(true, buf.hasStream()); } void testBaseChange() { LoggerPtr root; LoggerPtr logger; root = Logger::getRootLogger(); logger = Logger::getLogger(LOG4CXX_STR("java.org.apache.log4j.PatternLayoutTest")); PropertyConfigurator::configure(LOG4CXX_FILE("input/messagebuffer1.properties")); int num = 220; LOG4CXX_INFO(logger, "number in hex: " << std::hex << num); LOG4CXX_INFO(logger, "number in dec: " << num); LOGUNIT_ASSERT(Compare::compare(LOG4CXX_STR("output/messagebuffer"), LOG4CXX_FILE("witness/messagebuffer.1"))); auto rep = root->getLoggerRepository(); if (rep) { rep->resetConfiguration(); } } #if LOG4CXX_WCHAR_T_API void testInsertConstWStr() { MessageBuffer buf; std::wstring greeting(L"Hello, World"); WideMessageBuffer& retval = buf << L"Hello" << L", World"; LOGUNIT_ASSERT_EQUAL(greeting, buf.str(retval)); LOGUNIT_ASSERT_EQUAL(false, buf.hasStream()); } void testInsertWString() { MessageBuffer buf; std::wstring greeting(L"Hello, World"); WideMessageBuffer& retval = buf << std::wstring(L"Hello") << std::wstring(L", World"); LOGUNIT_ASSERT_EQUAL(greeting, buf.str(retval)); LOGUNIT_ASSERT_EQUAL(false, buf.hasStream()); } void testInsertWStr() { MessageBuffer buf; std::wstring greeting(L"Hello, World"); wchar_t* part1 = (wchar_t*) malloc(10 * sizeof(wchar_t)); wcscpy(part1, L"Hello"); wchar_t* part2 = (wchar_t*) malloc(10 * sizeof(wchar_t)); wcscpy(part2, L", World"); WideMessageBuffer& retval = buf << part1 << part2; free(part1); free(part2); LOGUNIT_ASSERT_EQUAL(greeting, buf.str(retval)); LOGUNIT_ASSERT_EQUAL(false, buf.hasStream()); } #endif #if LOG4CXX_UNICHAR_API void testInsertConstUStr() { MessageBuffer buf; const log4cxx::UniChar hello[] = { 'H', 'e', 'l', 'l', 'o', 0 }; const log4cxx::UniChar world[] = { ',', ' ', 'W', 'o', 'r', 'l', 'd', 0 }; const log4cxx::UniChar greeting[] = { 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', 0 }; UniCharMessageBuffer& retval = buf << hello << world; LOGUNIT_ASSERT_EQUAL(std::basic_string(greeting), buf.str(retval)); LOGUNIT_ASSERT_EQUAL(false, buf.hasStream()); } void testInsertUString() { MessageBuffer buf; const log4cxx::UniChar hello[] = { 'H', 'e', 'l', 'l', 'o', 0 }; const log4cxx::UniChar world[] = { ',', ' ', 'W', 'o', 'r', 'l', 'd', 0 }; const log4cxx::UniChar greeting[] = { 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', 0 }; UniCharMessageBuffer& retval = buf << std::basic_string(hello) << std::basic_string(world); LOGUNIT_ASSERT_EQUAL(std::basic_string(greeting), buf.str(retval)); LOGUNIT_ASSERT_EQUAL(false, buf.hasStream()); } #endif #if LOG4CXX_UNICHAR_API && LOG4CXX_CFSTRING_API void testInsertCFString() { MessageBuffer buf; const log4cxx::UniChar greeting[] = { 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', 0 }; UniCharMessageBuffer& retval = buf << CFSTR("Hello") << CFSTR(", World"); LOGUNIT_ASSERT_EQUAL(std::basic_string(greeting), buf.str(retval)); LOGUNIT_ASSERT_EQUAL(false, buf.hasStream()); } #elif LOG4CXX_CFSTRING_API void testInsertCFString() { MessageBuffer buf; const log4cxx::logchar greeting[] = { 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', 0 }; CharMessageBuffer& retval = buf << CFSTR("Hello") << CFSTR(", World"); LOGUNIT_ASSERT_EQUAL(std::basic_string(greeting), buf.str(retval)); LOGUNIT_ASSERT_EQUAL(false, buf.hasStream()); } #endif }; LOGUNIT_TEST_SUITE_REGISTRATION(MessageBufferTest); apache-log4cxx-1.3.1/src/test/cpp/helpers/cyclicbuffertestcase.cpp0000644000175100001770000001010514721727031024563 0ustar runnerdocker/* * 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. */ #include #include "../logunit.h" #include #include #include #include #include "../testchar.h" using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::spi; #define MAX 1000 LOGUNIT_CLASS(CyclicBufferTestCase) { LOGUNIT_TEST_SUITE(CyclicBufferTestCase); LOGUNIT_TEST(test0); LOGUNIT_TEST(test1); LOGUNIT_TEST(testResize); LOGUNIT_TEST_SUITE_END(); LoggerPtr logger; std::vector e; public: void setUp() { e.reserve(1000); LoggingEventPtr event; for (int i = 0; i < MAX; i++) { event = LoggingEventPtr(new LoggingEvent(LOG4CXX_STR("x"), Level::getDebug(), LOG4CXX_STR("e"), log4cxx::spi::LocationInfo::getLocationUnavailable())); e.push_back(event); } } void tearDown() { LogManager::shutdown(); } void test0() { int size = 2; CyclicBuffer cb(size); LOGUNIT_ASSERT_EQUAL(size, cb.getMaxSize()); cb.add(e[0]); LOGUNIT_ASSERT_EQUAL(1, cb.length()); LOGUNIT_ASSERT_EQUAL(e[0], cb.get()); LOGUNIT_ASSERT_EQUAL(0, cb.length()); LOGUNIT_ASSERT(cb.get() == 0); LOGUNIT_ASSERT_EQUAL(0, cb.length()); CyclicBuffer cb2(size); cb2.add(e[0]); cb2.add(e[1]); LOGUNIT_ASSERT_EQUAL(2, cb2.length()); LOGUNIT_ASSERT_EQUAL(e[0], cb2.get()); LOGUNIT_ASSERT_EQUAL(1, cb2.length()); LOGUNIT_ASSERT_EQUAL(e[1], cb2.get()); LOGUNIT_ASSERT_EQUAL(0, cb2.length()); LOGUNIT_ASSERT(cb2.get() == 0); LOGUNIT_ASSERT_EQUAL(0, cb2.length()); } void test1() { for (int bufSize = 1; bufSize <= 128; bufSize *= 2) { doTest1(bufSize); } } void doTest1(int size) { //System.out.println("Doing test with size = "+size); CyclicBuffer cb(size); LOGUNIT_ASSERT_EQUAL(size, cb.getMaxSize()); int i; for (i = -(size + 10); i < (size + 10); i++) { LOGUNIT_ASSERT(cb.get(i) == 0); } for (i = 0; i < MAX; i++) { cb.add(e[i]); int limit = (i < (size - 1)) ? i : (size - 1); //System.out.println("\nLimit is " + limit + ", i="+i); for (int j = limit; j >= 0; j--) { //System.out.println("i= "+i+", j="+j); LOGUNIT_ASSERT_EQUAL(e[i - (limit - j)], cb.get(j)); } LOGUNIT_ASSERT(cb.get(-1) == 0); LOGUNIT_ASSERT(cb.get(limit + 1) == 0); } } void testResize() { for (int isize = 1; isize <= 128; isize *= 2) { doTestResize(isize, (isize / 2) + 1, (isize / 2) + 1); doTestResize(isize, (isize / 2) + 1, isize + 10); doTestResize(isize, isize + 10, (isize / 2) + 1); doTestResize(isize, isize + 10, isize + 10); } } void doTestResize(int initialSize, int numberOfAdds, int newSize) { //System.out.println("initialSize = "+initialSize+", numberOfAdds=" // +numberOfAdds+", newSize="+newSize); CyclicBuffer cb(initialSize); for (int i = 0; i < numberOfAdds; i++) { cb.add(e[i]); } cb.resize(newSize); int offset = numberOfAdds - initialSize; if (offset < 0) { offset = 0; } int len = (newSize < numberOfAdds) ? newSize : numberOfAdds; len = (len < initialSize) ? len : initialSize; //System.out.println("Len = "+len+", offset="+offset); for (int j = 0; j < len; j++) { LOGUNIT_ASSERT_EQUAL(e[offset + j], cb.get(j)); } } }; LOGUNIT_TEST_SUITE_REGISTRATION(CyclicBufferTestCase); apache-log4cxx-1.3.1/src/test/cpp/mdctestcase.cpp0000644000175100001770000000314514721727031021232 0ustar runnerdocker /* * 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. */ #include #include #include #include #include "insertwide.h" #include "logunit.h" #include "util/compare.h" using namespace log4cxx; LOGUNIT_CLASS(MDCTestCase) { LOGUNIT_TEST_SUITE(MDCTestCase); LOGUNIT_TEST(test1); LOGUNIT_TEST_SUITE_END(); public: void setUp() { } void tearDown() { auto rep = Logger::getRootLogger()->getLoggerRepository(); if (rep) { rep->resetConfiguration(); } } /** * log4cxx 0.10.0 did not replace previously set value. */ void test1() { std::string key("key1"); std::string expected("value2"); MDC::put(key, "value1"); MDC::put(key, expected); std::string actual(MDC::get(key)); LOGUNIT_ASSERT_EQUAL(expected, actual); } }; LOGUNIT_TEST_SUITE_REGISTRATION(MDCTestCase); apache-log4cxx-1.3.1/src/test/cpp/loggertestcase.cpp0000644000175100001770000004475114721727031021756 0ustar runnerdocker /* * 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. */ #include #include #include #include #include #include #include #include #include #include #include "insertwide.h" #include "testchar.h" #include "logunit.h" #include #include "vectorappender.h" using namespace log4cxx; using namespace log4cxx::spi; using namespace log4cxx::helpers; class CountingAppender; typedef std::shared_ptr CountingAppenderPtr; class CountingAppender : public AppenderSkeleton { public: int counter; CountingAppender() : counter(0) {} void close() override {} void append(const spi::LoggingEventPtr& /*event*/, Pool& /*p*/) override { counter++; } bool requiresLayout() const override { return true; } }; class CountingListener : public HierarchyEventListener{ public: DECLARE_LOG4CXX_OBJECT(CountingListener) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(CountingListener) END_LOG4CXX_CAST_MAP() int numRemoved = 0; int numAdded = 0; void addAppenderEvent( const Logger* logger, const Appender* appender) override { numAdded++; } void removeAppenderEvent( const Logger* logger, const Appender* appender) override { numRemoved++; } }; IMPLEMENT_LOG4CXX_OBJECT(CountingListener); LOGUNIT_CLASS(LoggerTestCase) { LOGUNIT_TEST_SUITE(LoggerTestCase); LOGUNIT_TEST(testAppender1); LOGUNIT_TEST(testAppender2); LOGUNIT_TEST(testAdditivity1); LOGUNIT_TEST(testAdditivity2); LOGUNIT_TEST(testAdditivity3); LOGUNIT_TEST(testDisable1); // LOGUNIT_TEST(testRB1); // LOGUNIT_TEST(testRB2); //TODO restore // LOGUNIT_TEST(testRB3); LOGUNIT_TEST(testExists); LOGUNIT_TEST(testHierarchy1); LOGUNIT_TEST(testLoggerInstance); LOGUNIT_TEST(testTrace); LOGUNIT_TEST(testIsTraceEnabled); LOGUNIT_TEST(testAddingListeners); LOGUNIT_TEST(testAddingAndRemovingListeners); LOGUNIT_TEST(testAddingAndRemovingListeners2); LOGUNIT_TEST_SUITE_END(); public: void setUp() { } void tearDown() { BasicConfigurator::resetConfiguration(); a1 = 0; a2 = 0; logger = 0; } /** Add an appender and see if it can be retrieved. */ void testAppender1() { logger = Logger::getLogger(LOG4CXX_TEST_STR("test")); a1 = FileAppenderPtr(new FileAppender()); a1->setName(LOG4CXX_STR("testAppender1")); logger->addAppender(a1); AppenderList list = logger->getAllAppenders(); AppenderPtr aHat = list.front(); LOGUNIT_ASSERT_EQUAL(a1, aHat); } /** Add an appender X, Y, remove X and check if Y is the only remaining appender. */ void testAppender2() { a1 = FileAppenderPtr(new FileAppender()); a1->setName(LOG4CXX_STR("testAppender2.1")); a2 = FileAppenderPtr(new FileAppender()); a2->setName(LOG4CXX_STR("testAppender2.2")); logger = Logger::getLogger(LOG4CXX_TEST_STR("test")); logger->addAppender(a1); logger->addAppender(a2); logger->removeAppender((LogString) LOG4CXX_STR("testAppender2.1")); AppenderList list = logger->getAllAppenders(); AppenderPtr aHat = list.front(); LOGUNIT_ASSERT_EQUAL(a2, aHat); LOGUNIT_ASSERT(list.size() == 1); } /** Test if LoggerPtr a.b inherits its appender from a. */ void testAdditivity1() { LoggerPtr a = Logger::getLogger(LOG4CXX_TEST_STR("a")); LoggerPtr ab = Logger::getLogger(LOG4CXX_TEST_STR("a.b")); CountingAppenderPtr ca = CountingAppenderPtr(new CountingAppender()); a->addAppender(ca); LOGUNIT_ASSERT_EQUAL(ca->counter, 0); ab->debug(MSG); LOGUNIT_ASSERT_EQUAL(ca->counter, 1); ab->info(MSG); LOGUNIT_ASSERT_EQUAL(ca->counter, 2); ab->warn(MSG); LOGUNIT_ASSERT_EQUAL(ca->counter, 3); ab->error(MSG); LOGUNIT_ASSERT_EQUAL(ca->counter, 4); } /** Test multiple additivity. */ void testAdditivity2() { LoggerPtr a = Logger::getLogger(LOG4CXX_TEST_STR("a")); LoggerPtr ab = Logger::getLogger(LOG4CXX_TEST_STR("a.b")); LoggerPtr abc = Logger::getLogger(LOG4CXX_TEST_STR("a.b.c")); LoggerPtr x = Logger::getLogger(LOG4CXX_TEST_STR("x")); CountingAppenderPtr ca1 = CountingAppenderPtr(new CountingAppender()); CountingAppenderPtr ca2 = CountingAppenderPtr(new CountingAppender()); CountingAppenderPtr xa = CountingAppenderPtr(new CountingAppender()); a->addAppender(ca1); abc->addAppender(ca2); x->addAppender(xa); LOGUNIT_ASSERT_EQUAL(ca1->counter, 0); LOGUNIT_ASSERT_EQUAL(ca2->counter, 0); ab->debug(MSG); LOGUNIT_ASSERT_EQUAL(ca1->counter, 1); LOGUNIT_ASSERT_EQUAL(ca2->counter, 0); abc->debug(MSG); LOGUNIT_ASSERT_EQUAL(ca1->counter, 2); LOGUNIT_ASSERT_EQUAL(ca2->counter, 1); x->debug(MSG); LOGUNIT_ASSERT_EQUAL(ca1->counter, 2); LOGUNIT_ASSERT_EQUAL(ca2->counter, 1); } /** Test additivity flag. */ void testAdditivity3() { LoggerPtr root = Logger::getRootLogger(); LoggerPtr a = Logger::getLogger(LOG4CXX_TEST_STR("a")); LoggerPtr ab = Logger::getLogger(LOG4CXX_TEST_STR("a.b")); LoggerPtr abc = Logger::getLogger(LOG4CXX_TEST_STR("a.b.c")); LoggerPtr x = Logger::getLogger(LOG4CXX_TEST_STR("x")); CountingAppenderPtr caRoot = CountingAppenderPtr(new CountingAppender()); CountingAppenderPtr caA = CountingAppenderPtr(new CountingAppender()); CountingAppenderPtr caABC = CountingAppenderPtr(new CountingAppender()); CountingAppenderPtr cab = CountingAppenderPtr(new CountingAppender()); root->addAppender(caRoot); a->addAppender(caA); abc->addAppender(caABC); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 0); LOGUNIT_ASSERT_EQUAL(caA->counter, 0); LOGUNIT_ASSERT_EQUAL(caABC->counter, 0); ab->setAdditivity(false); a->debug(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 1); LOGUNIT_ASSERT_EQUAL(caA->counter, 1); LOGUNIT_ASSERT_EQUAL(caABC->counter, 0); ab->addAppender(cab); ab->debug(MSG); LOGUNIT_ASSERT_EQUAL(cab->counter, 1); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 1); LOGUNIT_ASSERT_EQUAL(caA->counter, 1); LOGUNIT_ASSERT_EQUAL(caABC->counter, 0); abc->debug(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 1); LOGUNIT_ASSERT_EQUAL(caA->counter, 1); LOGUNIT_ASSERT_EQUAL(caABC->counter, 1); } void testDisable1() { CountingAppenderPtr caRoot = CountingAppenderPtr(new CountingAppender()); LoggerPtr root = Logger::getRootLogger(); root->addAppender(caRoot); auto h = LogManager::getLoggerRepository(); //h.disableDebug(); h->setThreshold(Level::getInfo()); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 0); root->debug(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 0); root->info(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 1); root->log(Level::getWarn(), MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 2); root->warn(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 3); //h.disableInfo(); h->setThreshold(Level::getWarn()); root->debug(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 3); root->info(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 3); root->log(Level::getWarn(), MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 4); root->error(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 5); root->log(Level::getError(), MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); //h.disableAll(); h->setThreshold(Level::getOff()); root->debug(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); root->info(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); root->log(Level::getWarn(), MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); root->error(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); root->log(Level::getFatal(), MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); root->log(Level::getFatal(), MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); //h.disable(Level::getFatalLevel()); h->setThreshold(Level::getOff()); root->debug(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); root->info(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); root->log(Level::getWarn(), MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); root->error(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); root->log(Level::getWarn(), MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); root->log(Level::getFatal(), MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); } ResourceBundlePtr getBundle(const LogString & lang, const LogString & region) { Locale l(lang, region); ResourceBundlePtr bundle( PropertyResourceBundle::getBundle(LOG4CXX_STR("L7D"), l)); LOGUNIT_ASSERT(bundle != 0); return bundle; } void testRB1() { ResourceBundlePtr rbUS(getBundle(LOG4CXX_STR("en"), LOG4CXX_STR("US"))); ResourceBundlePtr rbFR(getBundle(LOG4CXX_STR("fr"), LOG4CXX_STR("FR"))); ResourceBundlePtr rbCH(getBundle(LOG4CXX_STR("fr"), LOG4CXX_STR("CH"))); LoggerPtr root = Logger::getRootLogger(); root->setResourceBundle(rbUS); ResourceBundlePtr t = root->getResourceBundle(); LOGUNIT_ASSERT(t == rbUS); LoggerPtr x = Logger::getLogger(LOG4CXX_TEST_STR("x")); LoggerPtr x_y = Logger::getLogger(LOG4CXX_TEST_STR("x.y")); LoggerPtr x_y_z = Logger::getLogger(LOG4CXX_TEST_STR("x.y.z")); t = x->getResourceBundle(); LOGUNIT_ASSERT(t == rbUS); t = x_y->getResourceBundle(); LOGUNIT_ASSERT(t == rbUS); t = x_y_z->getResourceBundle(); LOGUNIT_ASSERT(t == rbUS); } void testRB2() { LoggerPtr root = Logger::getRootLogger(); ResourceBundlePtr rbUS(getBundle(LOG4CXX_STR("en"), LOG4CXX_STR("US"))); ResourceBundlePtr rbFR(getBundle(LOG4CXX_STR("fr"), LOG4CXX_STR("FR"))); ResourceBundlePtr rbCH(getBundle(LOG4CXX_STR("fr"), LOG4CXX_STR("CH"))); root->setResourceBundle(rbUS); ResourceBundlePtr t = root->getResourceBundle(); LOGUNIT_ASSERT(t == rbUS); LoggerPtr x = Logger::getLogger(LOG4CXX_TEST_STR("x")); LoggerPtr x_y = Logger::getLogger(LOG4CXX_TEST_STR("x.y")); LoggerPtr x_y_z = Logger::getLogger(LOG4CXX_TEST_STR("x.y.z")); x_y->setResourceBundle(rbFR); t = x->getResourceBundle(); LOGUNIT_ASSERT(t == rbUS); t = x_y->getResourceBundle(); LOGUNIT_ASSERT(t == rbFR); t = x_y_z->getResourceBundle(); LOGUNIT_ASSERT(t == rbFR); } void testRB3() { ResourceBundlePtr rbUS(getBundle(LOG4CXX_STR("en"), LOG4CXX_STR("US"))); ResourceBundlePtr rbFR(getBundle(LOG4CXX_STR("fr"), LOG4CXX_STR("FR"))); ResourceBundlePtr rbCH(getBundle(LOG4CXX_STR("fr"), LOG4CXX_STR("CH"))); LoggerPtr root = Logger::getRootLogger(); root->setResourceBundle(rbUS); ResourceBundlePtr t = root->getResourceBundle(); LOGUNIT_ASSERT(t == rbUS); LoggerPtr x = Logger::getLogger(LOG4CXX_TEST_STR("x")); LoggerPtr x_y = Logger::getLogger(LOG4CXX_TEST_STR("x.y")); LoggerPtr x_y_z = Logger::getLogger(LOG4CXX_TEST_STR("x.y.z")); x_y->setResourceBundle(rbFR); x_y_z->setResourceBundle(rbCH); t = x->getResourceBundle(); LOGUNIT_ASSERT(t == rbUS); t = x_y->getResourceBundle(); LOGUNIT_ASSERT(t == rbFR); t = x_y_z->getResourceBundle(); LOGUNIT_ASSERT(t == rbCH); } void testExists() { LoggerPtr a = Logger::getLogger(LOG4CXX_TEST_STR("a")); LoggerPtr a_b = Logger::getLogger(LOG4CXX_TEST_STR("a.b")); LoggerPtr a_b_c = Logger::getLogger(LOG4CXX_TEST_STR("a.b.c")); LoggerPtr t; t = LogManager::exists(LOG4CXX_TEST_STR("xx")); LOGUNIT_ASSERT(t == 0); t = LogManager::exists(LOG4CXX_TEST_STR("a")); LOGUNIT_ASSERT_EQUAL(a, t); t = LogManager::exists(LOG4CXX_TEST_STR("a.b")); LOGUNIT_ASSERT_EQUAL(a_b, t); t = LogManager::exists(LOG4CXX_TEST_STR("a.b.c")); LOGUNIT_ASSERT_EQUAL(a_b_c, t); } void testHierarchy1() { LoggerRepositoryPtr h = Hierarchy::create(); LoggerPtr root(h->getRootLogger()); root->setLevel(Level::getError()); LoggerPtr a0 = h->getLogger(LOG4CXX_STR("a")); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("a"), a0->getName()); LOGUNIT_ASSERT(a0->getLevel() == 0); LOGUNIT_ASSERT(Level::getError() == a0->getEffectiveLevel()); LoggerPtr a11 = h->getLogger(LOG4CXX_STR("a")); LOGUNIT_ASSERT_EQUAL(a0, a11); LoggerPtr abc = h->getLogger(LOG4CXX_STR("a.b.c")); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("a.b.c"), abc->getName()); LOGUNIT_ASSERT(abc->getLevel() == 0); LOGUNIT_ASSERT(Level::getError() == abc->getEffectiveLevel()); // Check the threshold is changed in children of root root->setLevel(Level::getTrace()); LOGUNIT_ASSERT(Level::getTrace() == abc->getEffectiveLevel()); LOGUNIT_ASSERT_EQUAL(true, a0->isTraceEnabled()); LOGUNIT_ASSERT_EQUAL(true, Logger::isTraceEnabledFor(a0)); LOGUNIT_ASSERT_EQUAL(true, abc->isTraceEnabled()); LOGUNIT_ASSERT_EQUAL(true, Logger::isTraceEnabledFor(abc)); } void testLoggerInstance() { LoggerInstancePtr initiallyNull; auto ca = std::make_shared(); Logger::getRootLogger()->addAppender(ca); // Check instance loggers are removed from the LoggerRepository std::vector instanceNames = { LOG4CXX_STR("xxx.zzz") , LOG4CXX_STR("xxx.aaaa") , LOG4CXX_STR("xxx.bbb") , LOG4CXX_STR("xxx.ccc") , LOG4CXX_STR("xxx.ddd") }; auto initialCount = LogManager::getCurrentLoggers().size(); int expectedCount = 0; for (auto loggerName : instanceNames) { LoggerInstancePtr instanceLogger(loggerName); instanceLogger->info("Hello, World."); ++expectedCount; } auto finalCount = LogManager::getCurrentLoggers().size(); LOGUNIT_ASSERT_EQUAL(initialCount, finalCount); LOGUNIT_ASSERT_EQUAL(ca->counter, expectedCount); // Check the logger is not removed when referenced elsewhere auto a = Logger::getLogger(LOG4CXX_TEST_STR("xxx.aaaa")); { LoggerInstancePtr instanceLogger(LOG4CXX_TEST_STR("xxx.aaaa")); instanceLogger->info("Hello, World."); ++expectedCount; } LOGUNIT_ASSERT(LogManager::exists(LOG4CXX_TEST_STR("xxx.aaaa"))); LOGUNIT_ASSERT_EQUAL(ca->counter, expectedCount); // Check reset initiallyNull.reset("InitiallyNullLoggerPtr"); LOGUNIT_ASSERT(initiallyNull); LOG4CXX_INFO(initiallyNull, "Hello, World."); } void compileTestForLOGCXX202() const { // // prior to fix, these line would compile. // (*logger).info("Hello, World."); ((Logger*) logger.get())->info("Hello, World."); // // this one would not. // logger->info("Hello, World."); } /** * Tests logger.trace(Object). * */ void testTrace() { VectorAppenderPtr appender = VectorAppenderPtr(new VectorAppender()); LoggerPtr root = Logger::getRootLogger(); root->addAppender(appender); root->setLevel(Level::getInfo()); LoggerPtr tracer = Logger::getLogger("com.example.Tracer"); tracer->setLevel(Level::getTrace()); LOG4CXX_TRACE(tracer, "Message 1"); LOG4CXX_TRACE(root, "Discarded Message"); LOG4CXX_TRACE(root, "Discarded Message"); std::vector msgs(appender->vector); LOGUNIT_ASSERT_EQUAL((size_t) 1, msgs.size()); LoggingEventPtr event = msgs[0]; LOGUNIT_ASSERT_EQUAL((int) Level::TRACE_INT, event->getLevel()->toInt()); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXX_STR("Message 1")), event->getMessage()); } /** * Tests isTraceEnabled. * */ void testIsTraceEnabled() { VectorAppenderPtr appender = VectorAppenderPtr(new VectorAppender()); LoggerPtr root = Logger::getRootLogger(); root->addAppender(appender); root->setLevel(Level::getInfo()); LoggerPtr tracer = Logger::getLogger("com.example.Tracer"); tracer->setLevel(Level::getTrace()); LOGUNIT_ASSERT_EQUAL(true, tracer->isTraceEnabled()); LOGUNIT_ASSERT_EQUAL(true, Logger::isTraceEnabledFor(tracer)); LOGUNIT_ASSERT_EQUAL(true, Logger::isDebugEnabledFor(tracer)); LOGUNIT_ASSERT_EQUAL(true, Logger::isInfoEnabledFor(tracer)); LOGUNIT_ASSERT_EQUAL(true, Logger::isWarnEnabledFor(tracer)); LOGUNIT_ASSERT_EQUAL(true, Logger::isErrorEnabledFor(tracer)); LOGUNIT_ASSERT_EQUAL(false, root->isTraceEnabled()); LOGUNIT_ASSERT_EQUAL(false, Logger::isTraceEnabledFor(root)); LOGUNIT_ASSERT_EQUAL(false, Logger::isDebugEnabledFor(root)); LOGUNIT_ASSERT_EQUAL(true, Logger::isInfoEnabledFor(root)); LOGUNIT_ASSERT_EQUAL(true, Logger::isWarnEnabledFor(root)); LOGUNIT_ASSERT_EQUAL(true, Logger::isErrorEnabledFor(root)); } void testAddingListeners() { auto appender = std::shared_ptr(new CountingAppender); LoggerPtr root = Logger::getRootLogger(); std::shared_ptr listener = std::shared_ptr(new CountingListener()); root->getLoggerRepository()->addHierarchyEventListener(listener); root->addAppender(appender); LOGUNIT_ASSERT_EQUAL(1, listener->numAdded); LOGUNIT_ASSERT_EQUAL(0, listener->numRemoved); } void testAddingAndRemovingListeners() { auto appender = std::shared_ptr(new CountingAppender); LoggerPtr root = Logger::getRootLogger(); std::shared_ptr listener = std::shared_ptr(new CountingListener()); root->getLoggerRepository()->addHierarchyEventListener(listener); root->addAppender(appender); LOGUNIT_ASSERT_EQUAL(1, listener->numAdded); LOGUNIT_ASSERT_EQUAL(0, listener->numRemoved); root->removeAppender(appender); LOGUNIT_ASSERT_EQUAL(1, listener->numAdded); LOGUNIT_ASSERT_EQUAL(1, listener->numRemoved); } void testAddingAndRemovingListeners2() { auto appender = std::shared_ptr(new CountingAppender); auto appender2 = std::shared_ptr(new CountingAppender); LoggerPtr root = Logger::getRootLogger(); std::shared_ptr listener = std::shared_ptr(new CountingListener()); root->getLoggerRepository()->addHierarchyEventListener(listener); root->addAppender(appender); LOGUNIT_ASSERT_EQUAL(1, listener->numAdded); LOGUNIT_ASSERT_EQUAL(0, listener->numRemoved); root->addAppender(appender2); LOGUNIT_ASSERT_EQUAL(2, listener->numAdded); LOGUNIT_ASSERT_EQUAL(0, listener->numRemoved); root->removeAllAppenders(); LOGUNIT_ASSERT_EQUAL(2, listener->numAdded); LOGUNIT_ASSERT_EQUAL(2, listener->numRemoved); } protected: static LogString MSG; LoggerPtr logger; AppenderPtr a1; AppenderPtr a2; }; LogString LoggerTestCase::MSG(LOG4CXX_STR("M")); LOGUNIT_TEST_SUITE_REGISTRATION(LoggerTestCase); apache-log4cxx-1.3.1/src/test/cpp/nt/0000755000175100001770000000000014721727031016645 5ustar runnerdockerapache-log4cxx-1.3.1/src/test/cpp/nt/nteventlogappendertestcase.cpp0000644000175100001770000000617214721727031025017 0ustar runnerdocker/* * 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. */ #if defined(_WIN32) && !defined(_WIN32_WCE) #include #include "../appenderskeletontestcase.h" #include "windows.h" #include #include #include #include "../insertwide.h" #include "../logunit.h" #include using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::nt; using namespace log4cxx::spi; /** Unit tests of log4cxx::nt::NTEventLogAppender */ class NTEventLogAppenderTestCase : public AppenderSkeletonTestCase { LOGUNIT_TEST_SUITE(NTEventLogAppenderTestCase); // // tests inherited from AppenderSkeletonTestCase // LOGUNIT_TEST(testDefaultThreshold); LOGUNIT_TEST(testSetOptionThreshold); LOGUNIT_TEST(testHelloWorld); LOGUNIT_TEST_SUITE_END(); public: AppenderSkeleton* createAppenderSkeleton() const { return new log4cxx::nt::NTEventLogAppender(); } void testHelloWorld() { DWORD expectedId = 1; HANDLE hEventLog = ::OpenEventLogW(NULL, L"log4cxx_test"); if (hEventLog != NULL) { BOOL stat = GetNumberOfEventLogRecords(hEventLog, &expectedId); DWORD oldest; if (stat) { stat = GetOldestEventLogRecord(hEventLog, &oldest); } CloseEventLog(hEventLog); LOGUNIT_ASSERT(stat); expectedId += oldest; } Pool p; Date now; DWORD expectedTime = now.getTime() / Date::getMicrosecondsPerSecond(); { NTEventLogAppenderPtr appender(new NTEventLogAppender()); appender->setSource(LOG4CXX_STR("log4cxx_test")); LayoutPtr layout(new PatternLayout(LOG4CXX_STR("%c - %m%n"))); appender->setLayout(layout); appender->activateOptions(p); LoggingEventPtr event(new LoggingEvent( LOG4CXX_STR("org.foobar"), Level::getInfo(), LOG4CXX_STR("Hello, World"), LOG4CXX_LOCATION)); appender->doAppend(event, p); } hEventLog = ::OpenEventLogW(NULL, L"log4cxx_test"); LOGUNIT_ASSERT(hEventLog != NULL); DWORD actualId; BOOL stat = GetNumberOfEventLogRecords(hEventLog, &actualId); DWORD oldest; if (stat) { stat = GetOldestEventLogRecord(hEventLog, &oldest); } actualId += oldest; actualId--; CloseEventLog(hEventLog); LOGUNIT_ASSERT(stat); LOGUNIT_ASSERT_EQUAL(expectedId, actualId); } }; LOGUNIT_TEST_SUITE_REGISTRATION(NTEventLogAppenderTestCase); #endif apache-log4cxx-1.3.1/src/test/cpp/nt/CMakeLists.txt0000644000175100001770000000020414721727031021401 0ustar runnerdockeradd_executable(eventlogtests nteventlogappendertestcase.cpp) set(ALL_LOG4CXX_TESTS ${ALL_LOG4CXX_TESTS} eventlogtests PARENT_SCOPE) apache-log4cxx-1.3.1/src/test/cpp/logunit.cpp0000644000175100001770000001365514721727031020423 0ustar runnerdocker/* * 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. */ #include "logunit.h" #include #include #include #include void initialize() { setlocale(LC_CTYPE, ""); const char* ctype = setlocale(LC_CTYPE, 0); if (ctype == 0) { puts("LC_CTYPE: NULL"); } else { printf("LC_CTYPE: %s\n", ctype); } apr_initialize(); } extern const char** testlist; static bool suite_sort(const LogUnit::SuiteList::value_type& lhs, const LogUnit::SuiteList::value_type& rhs) { return lhs.first < rhs.first; } abts_suite* abts_run_suites(abts_suite* suite) { LogUnit::SuiteList sorted(LogUnit::getAllSuites()); #if !defined(_MSC_VER) std::sort(sorted.begin(), sorted.end(), suite_sort); #endif for (LogUnit::SuiteList::const_iterator iter = sorted.begin(); iter != sorted.end(); iter++) { // // if there is an explicit testlist or if the suite is not by default disabled // pump suite through filter if (testlist || !iter->second->isDisabled()) { suite = iter->second->run(suite); } } apr_terminate(); return suite; } using namespace LogUnit; using namespace std; TestException::TestException() {} TestException::TestException(const TestException& src) : std::exception(src) { } TestException& TestException::operator=(const TestException& src) { exception::operator=(src); return *this; } AssertException::AssertException(std::string message, int line) : msg(message), lineno(line) {} AssertException::AssertException(bool expected, const char* actualExpr, int line) : msg(actualExpr), lineno(line) { if (expected) { msg.append(" was expected to be true, was false."); } else { msg.append(" was expected to be true, was false."); } } AssertException::AssertException(const AssertException& src) : std::exception(src), msg(src.msg), lineno(src.lineno) { } AssertException::~AssertException() throw() { } AssertException& AssertException::operator=(const AssertException& src) { exception::operator=(src); msg = src.msg; lineno = src.lineno; return *this; } std::string AssertException::getMessage() const { return msg; } int AssertException::getLine() const { return lineno; } TestFixture::TestFixture() : tc(0) {} TestFixture::~TestFixture() {} void TestFixture::setCase(abts_case* newtc) { tc = newtc; } void TestFixture::setUp() {} void TestFixture::tearDown() {} void TestFixture::assertEquals(const char* expected, const char* actual, const char* expectedExpr, const char* actualExpr, int lineno) { abts_str_equal(tc, expected, actual, lineno); if ((expected == 0 || actual != 0) || (expected != 0 || actual == 0) || (expected != 0 && strcmp(expected, actual) != 0)) { throw TestException(); } } void TestFixture::assertEquals(const std::string expected, const std::string actual, const char* expectedExpr, const char* actualExpr, int lineno) { abts_str_equal(tc, expected.c_str(), actual.c_str(), lineno); if (expected != actual) { throw TestException(); } } template static void transcode(std::string& dst, const S& src) { for (typename S::const_iterator iter = src.begin(); iter != src.end(); iter++) { if (*iter <= 0x7F) { dst.append(1, (char) *iter); } else { dst.append(1, '?'); } } } #if LOG4CXX_LOGCHAR_IS_WCHAR || LOG4CXX_WCHAR_T_API void TestFixture::assertEquals(const std::wstring expected, const std::wstring actual, const char* expectedExpr, const char* actualExpr, int lineno) { if (expected != actual) { std::string exp, act; transcode(exp, expected); transcode(act, actual); abts_str_equal(tc, exp.c_str(), act.c_str(), lineno); throw TestException(); } } #endif #if LOG4CXX_LOGCHAR_IS_UNICHAR || LOG4CXX_UNICHAR_API void TestFixture::assertEquals(const std::basic_string expected, const std::basic_string actual, const char* expectedExpr, const char* actualExpr, int lineno) { if (expected != actual) { std::string exp, act; transcode(exp, expected); transcode(act, actual); abts_str_equal(tc, exp.c_str(), act.c_str(), lineno); throw TestException(); } } #endif void TestFixture::assertEquals(const int expected, const int actual, int lineno) { abts_int_equal(tc, expected, actual, lineno); if (expected != actual) { throw TestException(); } } LogUnit::TestSuite::TestSuite(const char* fname) : filename(fname), disabled(false) { #if defined(_WIN32) for (size_t i = filename.find('\\'); i != std::string::npos; i = filename.find('\\', i + 1)) { filename.replace(i, 1, 1, '/'); } #endif } void LogUnit::TestSuite::addTest(const char* test_name, test_func func) { test_funcs.push_back({test_name,func}); } std::string LogUnit::TestSuite::getName() const { return filename; } void LogUnit::TestSuite::setDisabled(bool newVal) { disabled = newVal; } bool LogUnit::TestSuite::isDisabled() const { return disabled; } abts_suite* TestSuite::run(abts_suite* suite) const { suite = abts_add_suite(suite, filename.c_str()); for (TestList::const_iterator iter = test_funcs.begin(); iter != test_funcs.end(); iter++) { abts_run_test(suite, iter->first, *iter->second, NULL); } return suite; } LogUnit::SuiteList& LogUnit::getAllSuites() { static LogUnit::SuiteList allSuites; return allSuites; } apache-log4cxx-1.3.1/src/test/cpp/patternlayouttest.cpp0000644000175100001770000003613014721727031022546 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include "util/compare.h" #include "util/transformer.h" #include "util/absolutedateandtimefilter.h" #include "util/iso8601filter.h" #include "util/absolutetimefilter.h" #include "util/relativetimefilter.h" #include "util/controlfilter.h" #include "util/threadfilter.h" #include "util/linenumberfilter.h" #include "util/filenamefilter.h" #include #include #include #include #include #include "testchar.h" #include "logunit.h" #include #include #define REGEX_STR(x) x #define PAT0 REGEX_STR("\\[[0-9A-FXx]*]\\ (DEBUG|INFO|WARN|ERROR|FATAL) .* - Message [0-9]\\{1,2\\}") #define PAT1 ISO8601_PAT REGEX_STR(" ") PAT0 #define PAT2 ABSOLUTE_DATE_AND_TIME_PAT REGEX_STR(" ") PAT0 #define PAT3 ABSOLUTE_TIME_PAT REGEX_STR(" ") PAT0 #define PAT4 RELATIVE_TIME_PAT REGEX_STR(" ") PAT0 #define PAT5 REGEX_STR("\\[[0-9A-FXx]*]\\ (DEBUG|INFO|WARN|ERROR|FATAL) .* : Message [0-9]\\{1,2\\}") #define PAT6 REGEX_STR("\\[[0-9A-FXx]*]\\ (DEBUG|INFO |WARN |ERROR|FATAL) .*patternlayouttest.cpp\\([0-9]\\{1,4\\}\\): Message [0-9]\\{1,3\\}") #define PAT11a REGEX_STR("^(DEBUG|INFO |WARN |ERROR|FATAL) \\[[0-9A-FXx]*]\\ log4j.PatternLayoutTest: Message [0-9]\\{1,2\\}") #define PAT11b REGEX_STR("^(DEBUG|INFO |WARN |ERROR|FATAL) \\[[0-9A-FXx]*]\\ root: Message [0-9]\\{1,2\\}") #define PAT12 REGEX_STR("^\\[[0-9A-FXx]*]\\ (DEBUG|INFO |WARN |ERROR|FATAL) ")\ REGEX_STR(".*patternlayouttest.cpp([0-9]\\{1,4\\}): ")\ REGEX_STR("Message [0-9]\\{1,2\\}") #define PAT_MDC_1 REGEX_STR("") using namespace log4cxx; using namespace log4cxx::helpers; LOGUNIT_CLASS(PatternLayoutTest) { LOGUNIT_TEST_SUITE(PatternLayoutTest); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST(test3); LOGUNIT_TEST(test4); LOGUNIT_TEST(test5); LOGUNIT_TEST(test6); LOGUNIT_TEST(test7); LOGUNIT_TEST(test8); LOGUNIT_TEST(test9); LOGUNIT_TEST(test10); LOGUNIT_TEST(test11); LOGUNIT_TEST(test12); LOGUNIT_TEST(test13); LOGUNIT_TEST(test14); LOGUNIT_TEST(testMDC1); LOGUNIT_TEST(testMDC2); LOGUNIT_TEST_SUITE_END(); LoggerPtr root; LoggerPtr logger; public: void setUp() { root = Logger::getRootLogger(); MDC::clear(); logger = Logger::getLogger(LOG4CXX_TEST_STR("java.org.apache.log4j.PatternLayoutTest")); } void tearDown() { MDC::clear(); auto rep = root->getLoggerRepository(); if (rep) { rep->resetConfiguration(); } } void test1() { PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout1.properties")); common(); LOGUNIT_ASSERT(Compare::compare(TEMP, LOG4CXX_FILE("witness/patternLayout.1"))); } void test2() { PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout2.properties")); common(); ControlFilter filter1; filter1 << PAT1; ISO8601Filter filter2; ThreadFilter filter3; std::vector filters; filters.push_back(&filter1); filters.push_back(&filter2); filters.push_back(&filter3); try { Transformer::transform(TEMP, FILTERED, filters); } catch (UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/patternLayout.2"))); } void test3() { PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout3.properties")); common(); ControlFilter filter1; filter1 << PAT1; ISO8601Filter filter2; ThreadFilter filter3; std::vector filters; filters.push_back(&filter1); filters.push_back(&filter2); filters.push_back(&filter3); try { Transformer::transform(TEMP, FILTERED, filters); } catch (UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/patternLayout.3"))); } // Output format: // 06 avr. 2002 18:30:58,937 [12345] DEBUG atternLayoutTest - Message 0 void test4() { PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout4.properties")); common(); ControlFilter filter1; filter1 << PAT2; AbsoluteDateAndTimeFilter filter2; ThreadFilter filter3; std::vector filters; filters.push_back(&filter1); filters.push_back(&filter2); filters.push_back(&filter3); try { Transformer::transform(TEMP, FILTERED, filters); } catch (UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/patternLayout.4"))); } void test5() { PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout5.properties")); common(); ControlFilter filter1; filter1 << PAT2; AbsoluteDateAndTimeFilter filter2; ThreadFilter filter3; std::vector filters; filters.push_back(&filter1); filters.push_back(&filter2); filters.push_back(&filter3); try { Transformer::transform(TEMP, FILTERED, filters); } catch (UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/patternLayout.5"))); } void test6() { PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout6.properties")); common(); ControlFilter filter1; filter1 << PAT3; AbsoluteTimeFilter filter2; ThreadFilter filter3; std::vector filters; filters.push_back(&filter1); filters.push_back(&filter2); filters.push_back(&filter3); try { Transformer::transform(TEMP, FILTERED, filters); } catch (UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/patternLayout.6"))); } void test7() { PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout7.properties")); common(); ControlFilter filter1; filter1 << PAT3; AbsoluteTimeFilter filter2; ThreadFilter filter3; std::vector filters; filters.push_back(&filter1); filters.push_back(&filter2); filters.push_back(&filter3); try { Transformer::transform(TEMP, FILTERED, filters); } catch (UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/patternLayout.7"))); } void test8() { PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout8.properties")); common(); ControlFilter filter1; filter1 << PAT4; // // combo of relative time and thread identifier // (the \\\\1 preserve a leading space) Filter filter2(".*]", "[main]"); std::vector filters; filters.push_back(&filter1); filters.push_back(&filter2); try { Transformer::transform(TEMP, FILTERED, filters); } catch (UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/patternLayout.8"))); } void test9() { PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout9.properties")); common(); ControlFilter filter1; filter1 << PAT5; ThreadFilter filter2; std::vector filters; filters.push_back(&filter1); filters.push_back(&filter2); try { Transformer::transform(TEMP, FILTERED, filters); } catch (UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/patternLayout.9"))); } void test10() { PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout10.properties")); common(); ControlFilter filter1; filter1 << PAT6; ThreadFilter filter2; LineNumberFilter filter3; FilenameFilter filenameFilter(__FILE__, "patternlayouttest.cpp"); std::vector filters; filters.push_back(&filenameFilter); filters.push_back(&filter1); filters.push_back(&filter2); filters.push_back(&filter3); try { Transformer::transform(TEMP, FILTERED, filters); } catch (UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/patternLayout.10"))); } void test11() { PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout11.properties")); common(); ControlFilter filter1; filter1 << PAT11a << PAT11b; ThreadFilter filter2; std::vector filters; filters.push_back(&filter1); filters.push_back(&filter2); try { Transformer::transform(TEMP, FILTERED, filters); } catch (UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/patternLayout.11"))); } void test12() { PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout12.properties")); common(); ControlFilter filter1; filter1 << PAT12; ThreadFilter filter2; LineNumberFilter filter3; FilenameFilter filenameFilter(__FILE__, "patternlayouttest.cpp"); std::vector filters; filters.push_back(&filenameFilter); filters.push_back(&filter1); filters.push_back(&filter2); filters.push_back(&filter3); try { Transformer::transform(TEMP, FILTERED, filters); } catch (UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/patternLayout.12"))); } void test13() { PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout13.properties")); common(); LOGUNIT_ASSERT(Compare::compare(TEMP, LOG4CXX_FILE("witness/patternLayout.13"))); } void test14() { PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout14.properties")); common(); LOGUNIT_ASSERT(Compare::compare(TEMP, LOG4CXX_FILE("witness/patternLayout.14"))); } void testMDC1() { PropertyConfigurator::configure(LOG4CXX_FILE("input/patternLayout.mdc.1.properties")); MDC::put(LOG4CXX_TEST_STR("key1"), LOG4CXX_TEST_STR("va11")); MDC::put(LOG4CXX_TEST_STR("key2"), LOG4CXX_TEST_STR("va12")); logger->debug(LOG4CXX_TEST_STR("Hello World")); MDC::clear(); LOGUNIT_ASSERT(Compare::compare(TEMP, LOG4CXX_FILE("witness/patternLayout.mdc.1"))); } void testMDC2() { LogString OUTPUT_FILE = LOG4CXX_STR("output/patternLayout.mdc.2"); File WITNESS_FILE = LOG4CXX_FILE("witness/patternLayout.mdc.2"); LogString mdcMsgPattern1 = LOG4CXX_STR("%m : %X%n"); LogString mdcMsgPattern2 = LOG4CXX_STR("%m : %X{key1}%n"); LogString mdcMsgPattern3 = LOG4CXX_STR("%m : %X{key2}%n"); LogString mdcMsgPattern4 = LOG4CXX_STR("%m : %X{key3}%n"); LogString mdcMsgPattern5 = LOG4CXX_STR("%m : %X{key1},%X{key2},%X{key3}%n"); // set up appender PatternLayoutPtr layout = PatternLayoutPtr(new PatternLayout(LOG4CXX_STR("%m%n"))); AppenderPtr appender = FileAppenderPtr(new FileAppender(layout, OUTPUT_FILE, false)); // set appender on root and set level to debug root->addAppender(appender); root->setLevel(Level::getDebug()); // output starting message root->debug(LOG4CXX_TEST_STR("starting mdc pattern test")); layout->setConversionPattern(mdcMsgPattern1); log4cxx::helpers::Pool pool; layout->activateOptions(pool); root->debug(LOG4CXX_TEST_STR("empty mdc, no key specified in pattern")); layout->setConversionPattern(mdcMsgPattern2); layout->activateOptions(pool); root->debug(LOG4CXX_TEST_STR("empty mdc, key1 in pattern")); layout->setConversionPattern(mdcMsgPattern3); layout->activateOptions(pool); root->debug(LOG4CXX_TEST_STR("empty mdc, key2 in pattern")); layout->setConversionPattern(mdcMsgPattern4); layout->activateOptions(pool); root->debug(LOG4CXX_TEST_STR("empty mdc, key3 in pattern")); layout->setConversionPattern(mdcMsgPattern5); layout->activateOptions(pool); root->debug(LOG4CXX_TEST_STR("empty mdc, key1, key2, and key3 in pattern")); MDC::put(LOG4CXX_TEST_STR("key1"), LOG4CXX_TEST_STR("value1")); MDC::put(LOG4CXX_TEST_STR("key2"), LOG4CXX_TEST_STR("value2")); layout->setConversionPattern(mdcMsgPattern1); layout->activateOptions(pool); root->debug(LOG4CXX_TEST_STR("filled mdc, no key specified in pattern")); layout->setConversionPattern(mdcMsgPattern2); layout->activateOptions(pool); root->debug(LOG4CXX_TEST_STR("filled mdc, key1 in pattern")); layout->setConversionPattern(mdcMsgPattern3); layout->activateOptions(pool); root->debug(LOG4CXX_TEST_STR("filled mdc, key2 in pattern")); layout->setConversionPattern(mdcMsgPattern4); layout->activateOptions(pool); root->debug(LOG4CXX_TEST_STR("filled mdc, key3 in pattern")); layout->setConversionPattern(mdcMsgPattern5); layout->activateOptions(pool); root->debug(LOG4CXX_TEST_STR("filled mdc, key1, key2, and key3 in pattern")); MDC::remove(LOG4CXX_TEST_STR("key1")); MDC::remove(LOG4CXX_TEST_STR("key2")); layout->setConversionPattern(LOG4CXX_STR("%m%n")); layout->activateOptions(pool); root->debug(LOG4CXX_TEST_STR("finished mdc pattern test")); LOGUNIT_ASSERT(Compare::compare(OUTPUT_FILE, WITNESS_FILE)); } std::string createMessage(Pool & pool, int i) { std::string msg("Message "); msg.append(pool.itoa(i)); return msg; } void common() { int i = -1; Pool pool; LOG4CXX_DEBUG(logger, createMessage(pool, ++i)); LOG4CXX_DEBUG(root, createMessage(pool, i)); LOG4CXX_INFO(logger, createMessage(pool, ++i)); LOG4CXX_INFO(root, createMessage(pool, i)); LOG4CXX_WARN(logger, createMessage(pool, ++i)); LOG4CXX_WARN(root, createMessage(pool, i)); LOG4CXX_ERROR(logger, createMessage(pool, ++i)); LOG4CXX_ERROR(root, createMessage(pool, i)); LOG4CXX_FATAL(logger, createMessage(pool, ++i)); LOG4CXX_FATAL(root, createMessage(pool, i)); } private: static const LogString FILTERED; static const LogString TEMP; }; const LogString PatternLayoutTest::TEMP(LOG4CXX_STR("output/patternlayout")); const LogString PatternLayoutTest::FILTERED(LOG4CXX_STR("output/patternlayoutfiltered")); LOGUNIT_TEST_SUITE_REGISTRATION(PatternLayoutTest); apache-log4cxx-1.3.1/src/cmake/0000755000175100001770000000000014721727031015543 5ustar runnerdockerapache-log4cxx-1.3.1/src/cmake/SQLAllocHandleTest.cpp0000644000175100001770000000055114721727031021636 0ustar runnerdocker// SQLAllocHandleTest.cpp // compile with: odbc32.lib user32.lib #include #include int main() { SQLHENV henv; SQLRETURN retcode; retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv); if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) { SQLFreeHandle(SQL_HANDLE_ENV, henv); } return 1; }apache-log4cxx-1.3.1/src/cmake/LibFuzzerTest.cpp0000644000175100001770000000176414721727031021033 0ustar runnerdocker/* * 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. */ #include extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, const size_t size) { FuzzedDataProvider dataProvider(data, size); dataProvider.ConsumeBool(); return 0; } apache-log4cxx-1.3.1/src/cmake/pthread/0000755000175100001770000000000014721727031017172 5ustar runnerdockerapache-log4cxx-1.3.1/src/cmake/pthread/log4cxx-pthread.cmake0000644000175100001770000000057014721727031023213 0ustar runnerdockerinclude(FindThreads) try_compile(PTHREAD_SETNAME_NP_FOUND "${CMAKE_BINARY_DIR}/pthread-compile-tests" "${CMAKE_CURRENT_LIST_DIR}/test-pthread-setname.cpp" LINK_LIBRARIES Threads::Threads ) try_compile(PTHREAD_GETNAME_NP_FOUND "${CMAKE_BINARY_DIR}/pthread-compile-tests" "${CMAKE_CURRENT_LIST_DIR}/test-pthread-getname.cpp" LINK_LIBRARIES Threads::Threads ) apache-log4cxx-1.3.1/src/cmake/pthread/test-pthread-getname.cpp0000644000175100001770000000017014721727031023716 0ustar runnerdocker#include int main(){ pthread_t tid; char buffer[16]; pthread_getname_np(tid, buffer, sizeof(buffer)); } apache-log4cxx-1.3.1/src/cmake/pthread/test-pthread-setname.cpp0000644000175100001770000000012614721727031023733 0ustar runnerdocker#include int main(){ pthread_t tid; pthread_setname_np(tid, "name"); } apache-log4cxx-1.3.1/src/cmake/win32_target_environment_path.cmake0000644000175100001770000000304714721727031024521 0ustar runnerdocker# Put the list of runtime path directories into varName. function(get_target_environment_path varName) get_filename_component(APR_DLL_DIR "${APR_DLL}" DIRECTORY) get_filename_component(APR_UTIL_DLL_DIR "${APR_UTIL_DLL}" DIRECTORY) get_filename_component(EXPAT_LIB_DIR "${EXPAT_LIBRARY}" DIRECTORY) set(EXPAT_DLL_DIR "${EXPAT_LIB_DIR}/../bin") set(LOG4CXX_DLL_DIR "$>;") set(PATH_FOR_TESTS ${CMAKE_PROGRAM_PATH};${APR_DLL_DIR};${APR_UTIL_DLL_DIR};${LOG4CXX_DLL_DIR};${EXPAT_DLL_DIR}\;) if(LOG4CXX_QT_SUPPORT) list(APPEND PATH_FOR_TESTS "$>\;") endif(LOG4CXX_QT_SUPPORT) list(REMOVE_DUPLICATES PATH_FOR_TESTS) # Note: we need to include the APR DLLs on our path so that the tests will run. # The way that CMake sets the environment is that it actually generates a secondary file, # CTestTestfile.cmake, which sets the final properties of the test. # However, this results in a secondary quirk to the running of the tests: CMake uses # a semicolon to deliminate entries in a list! Since the Windows PATH is semicolon-delimited # as well, CMake uses only the first entry in the list when setting the path. # So, we need to do a triple escape on the PATH that we want to set in order for CMake to # properly interpret the PATH set(NORMAL_PATH $ENV{PATH}) set(ESCAPED_PATH "") foreach( ENTRY ${PATH_FOR_TESTS}${NORMAL_PATH} ) set(ESCAPED_PATH "${ESCAPED_PATH}${ENTRY}\\\;") endforeach() set(${varName} ${ESCAPED_PATH} PARENT_SCOPE) endfunction() apache-log4cxx-1.3.1/src/cmake/FindAPR.cmake0000644000175100001770000000560214721727031017773 0ustar runnerdocker# Locate APR include paths and libraries include(FindPackageHandleStandardArgs) # This module defines # APR_INCLUDE_DIR, where to find apr.h, etc. # APR_LIBRARIES, the libraries to link against to use APR. # APR_DLL_DIR, where to find libapr-1.dll # APR_FOUND, set to 'yes' if found macro(_apr_invoke _varname) execute_process( COMMAND ${APR_CONFIG_EXECUTABLE} ${ARGN} OUTPUT_VARIABLE _apr_output RESULT_VARIABLE _apr_failed ) if(_apr_failed) message(FATAL_ERROR "apr-1-config ${ARGN} failed with result ${_apr_failed}") else(_apr_failed) string(REGEX REPLACE "[\r\n]" "" _apr_output "${_apr_output}") string(REGEX REPLACE " +$" "" _apr_output "${_apr_output}") string(REGEX REPLACE "^ +" "" _apr_output "${_apr_output}") separate_arguments(_apr_output) set(${_varname} "${_apr_output}") endif(_apr_failed) endmacro(_apr_invoke) if(NOT APR_STATIC) # apr-1-config does not support --static used in FindPkgConfig.cmake find_package(PkgConfig) pkg_check_modules(APR apr-1) endif() if(APR_FOUND) find_path(APR_INCLUDE_DIR NAMES apr.h HINTS ${APR_INCLUDE_DIRS} PATH_SUFFIXES apr-1) if (APR_STATIC OR NOT BUILD_SHARED_LIBS) set(APR_COMPILE_DEFINITIONS APR_DECLARE_STATIC) set(APR_LIBRARIES ${APR_STATIC_LINK_LIBRARIES}) if(WIN32) set(APR_SYSTEM_LIBS ws2_32 mswsock rpcrt4) else() set(APR_SYSTEM_LIBS pthread) endif() else() set(APR_LIBRARIES ${APR_LINK_LIBRARIES}) endif() if(WIN32) list(APPEND APR_COMPILE_DEFINITIONS WIN32) endif() else() find_program(APR_CONFIG_EXECUTABLE apr-1-config PATHS /usr/local/opt/apr/bin $ENV{ProgramFiles}/apr/bin ) mark_as_advanced(APR_CONFIG_EXECUTABLE) if(EXISTS ${APR_CONFIG_EXECUTABLE}) _apr_invoke(APR_INCLUDE_DIR --includedir) if (APR_STATIC OR NOT BUILD_SHARED_LIBS) _apr_invoke(_apr_link_args --link-ld) string(REGEX MATCH "-L([^ ]+)" _apr_L_flag ${_apr_link_args}) find_library(APR_LIBRARIES NAMES libapr-1.a PATHS "${CMAKE_MATCH_1}") set(APR_SYSTEM_LIBS pthread) set(APR_COMPILE_DEFINITIONS APR_DECLARE_STATIC) else() _apr_invoke(APR_LIBRARIES --link-ld) endif() else() find_path(APR_INCLUDE_DIR apr.h PATH_SUFFIXES apr-1) if (APR_STATIC OR NOT BUILD_SHARED_LIBS) if(WIN32) set(APR_SYSTEM_LIBS ws2_32 mswsock rpcrt4) else() set(APR_SYSTEM_LIBS pthread) endif() set(APR_COMPILE_DEFINITIONS APR_DECLARE_STATIC) find_library(APR_LIBRARIES NAMES apr-1) else() find_library(APR_LIBRARIES NAMES libapr-1) find_program(APR_DLL libapr-1.dll) endif() endif() if(WIN32) list(APPEND APR_COMPILE_DEFINITIONS WIN32) endif() endif() find_package_handle_standard_args(APR APR_INCLUDE_DIR APR_LIBRARIES) apache-log4cxx-1.3.1/src/cmake/FindLibFuzzer.cmake0000644000175100001770000000221114721727031021256 0ustar runnerdocker# # 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 module sets `LIBFUZZER_FOUND` to `1` if libFuzzer[1] is found. # # [1] https://llvm.org/docs/LibFuzzer.html if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang") try_compile(LIBFUZZER_FOUND "${CMAKE_BINARY_DIR}/LibFuzzerTest" "${CMAKE_CURRENT_LIST_DIR}/LibFuzzerTest.cpp" CMAKE_FLAGS -DCOMPILE_DEFINITIONS=-fsanitize=fuzzer) else() set(LIBFUZZER_FOUND 0) endif() apache-log4cxx-1.3.1/src/cmake/projectVersionDetails.cmake0000644000175100001770000000035314721727031023070 0ustar runnerdocker# This file should contain nothing but the following line # setting the project version. The variable name must not # clash with the log4cxx_VERSION* variables automatically # defined by the project() command. set(log4cxx_VER 1.3.1.0) apache-log4cxx-1.3.1/src/cmake/FindAPR-Util.cmake0000644000175100001770000000522014721727031020702 0ustar runnerdocker# Locate APR-Util include paths and libraries include(FindPackageHandleStandardArgs) # This module defines # APR_UTIL_INCLUDE_DIR, where to find apr.h, etc. # APR_UTIL_LIBRARIES, the libraries to link against to use APR. # APR_UTIL_DLL_DIR, where to find libaprutil-1.dll # APR_UTIL_FOUND, set to yes if found macro(_apu_invoke _varname) execute_process( COMMAND ${APR_UTIL_CONFIG_EXECUTABLE} ${ARGN} OUTPUT_VARIABLE _apr_output RESULT_VARIABLE _apr_failed ) if(_apr_failed) message(FATAL_ERROR "apu-1-config ${ARGN} failed with result ${_apr_failed}") else(_apr_failed) string(REGEX REPLACE "[\r\n]" "" _apr_output "${_apr_output}") string(REGEX REPLACE " +$" "" _apr_output "${_apr_output}") string(REGEX REPLACE "^ +" "" _apr_output "${_apr_output}") separate_arguments(_apr_output) set(${_varname} "${_apr_output}") endif(_apr_failed) endmacro(_apu_invoke) if(NOT APU_STATIC) # apu-1-config does not yet support --static used in FindPkgConfig.cmake find_package(PkgConfig) pkg_check_modules(APR_UTIL apr-util-1) endif() if(APR_UTIL_FOUND) find_path(APR_UTIL_INCLUDE_DIR NAMES apu.h HINTS ${APR_UTIL_INCLUDE_DIRS} PATH_SUFFIXES apr-1) if (APU_STATIC OR NOT BUILD_SHARED_LIBS) set(APR_UTIL_COMPILE_DEFINITIONS APU_DECLARE_STATIC) set(APR_UTIL_LIBRARIES ${APR_UTIL_STATIC_LINK_LIBRARIES}) else() set(APR_UTIL_LIBRARIES ${APR_UTIL_LINK_LIBRARIES}) endif() else() find_program(APR_UTIL_CONFIG_EXECUTABLE apu-1-config PATHS /usr/local/opt/apr-util/bin $ENV{ProgramFiles}/apr-util/bin ) mark_as_advanced(APR_UTIL_CONFIG_EXECUTABLE) if(EXISTS ${APR_UTIL_CONFIG_EXECUTABLE}) _apu_invoke(APR_UTIL_INCLUDE_DIR --includedir) if (APU_STATIC OR NOT BUILD_SHARED_LIBS) _apu_invoke(_apu_util_link_args --link-ld) string(REGEX MATCH "-L([^ ]+)" _apu_util_L_flag ${_apu_util_link_args}) find_library(APR_UTIL_LIBRARIES NAMES libaprutil-1.a PATHS "${CMAKE_MATCH_1}") set(APR_UTIL_COMPILE_DEFINITIONS APU_DECLARE_STATIC) else() _apu_invoke(APR_UTIL_LIBRARIES --link-ld) endif() else() find_path(APR_UTIL_INCLUDE_DIR apu.h PATH_SUFFIXES apr-1) if (APU_STATIC OR NOT BUILD_SHARED_LIBS) set(APR_UTIL_COMPILE_DEFINITIONS APU_DECLARE_STATIC) find_library(APR_UTIL_LIBRARIES NAMES aprutil-1) else() find_library(APR_UTIL_LIBRARIES NAMES libaprutil-1) find_program(APR_UTIL_DLL libaprutil-1.dll) endif() endif() endif() find_package_handle_standard_args(APR-Util APR_UTIL_INCLUDE_DIR APR_UTIL_LIBRARIES) apache-log4cxx-1.3.1/src/cmake/boost-fallback/0000755000175100001770000000000014721727031020426 5ustar runnerdockerapache-log4cxx-1.3.1/src/cmake/boost-fallback/boost-std-configuration.h.cmake0000644000175100001770000000133514721727031026443 0ustar runnerdocker#ifndef BOOST_STD_CONFIGURATION_H #define BOOST_STD_CONFIGURATION_H #cmakedefine01 STD_FILESYSTEM_FOUND #cmakedefine01 Boost_FILESYSTEM_FOUND #cmakedefine01 STD_EXPERIMENTAL_FILESYSTEM_FOUND #if STD_FILESYSTEM_FOUND #include namespace ${NAMESPACE_ALIAS} { namespace filesystem { typedef std::filesystem::path path; } } #elif STD_EXPERIMENTAL_FILESYSTEM_FOUND #include namespace ${NAMESPACE_ALIAS} { namespace filesystem { typedef std::experimental::filesystem::path path; } } #elif Boost_FILESYSTEM_FOUND #include namespace ${NAMESPACE_ALIAS} { namespace filesystem { typedef boost::filesystem::path path; } } #endif #endif /* BOOST_STD_CONFIGURATION_H */ apache-log4cxx-1.3.1/src/cmake/boost-fallback/test-boostmutex.cpp0000644000175100001770000000014014721727031024313 0ustar runnerdocker#include int main(int argc, char** argv){ boost::mutex mutex; return 0; } apache-log4cxx-1.3.1/src/cmake/boost-fallback/test-boostsharedptr.cpp0000644000175100001770000000020614721727031025150 0ustar runnerdocker#include struct foo{ int x; }; int main(int argc, char** argv){ boost::shared_ptr fooptr; return 0; } apache-log4cxx-1.3.1/src/cmake/boost-fallback/test-stdmutex.cpp0000644000175100001770000000012314721727031023760 0ustar runnerdocker#include int main(int argc, char** argv){ std::mutex mutex; return 0; } apache-log4cxx-1.3.1/src/cmake/boost-fallback/test-stdfilesystem.cpp0000644000175100001770000000012414721727031025003 0ustar runnerdocker#include int main(int argc, char** argv){ std::filesystem::path p; } apache-log4cxx-1.3.1/src/cmake/boost-fallback/test-stdthread.cpp0000644000175100001770000000012214721727031024064 0ustar runnerdocker#include int main(int argc, char** argv){ std::thread th; return 0; } apache-log4cxx-1.3.1/src/cmake/boost-fallback/test-stdsharedptr.cpp0000644000175100001770000000016714721727031024622 0ustar runnerdocker#include struct foo{ int x; }; int main(int argc, char** argv){ std::shared_ptr fooptr; return 0; } apache-log4cxx-1.3.1/src/cmake/boost-fallback/boost-fallback.cmake0000644000175100001770000000276314721727031024323 0ustar runnerdocker# This module checks for C++ standard classes and their boost counterparts # Filesystem variables set: # STD_FILESYSTEM_FOUND - if std::filesystem is found # STD_EXPERIMENTAL_FILESYSTEM_FOUND - if std::experimental::filesystem is found # Boost_FILESYSTEM_FOUND - if boost::filesystem is found include(FindThreads) try_compile(STD_FILESYSTEM_FOUND "${CMAKE_BINARY_DIR}/boost-fallback-compile-tests" "${CMAKE_CURRENT_LIST_DIR}/test-stdfilesystem.cpp") try_compile(STD_EXPERIMENTAL_FILESYSTEM_FOUND "${CMAKE_BINARY_DIR}/boost-fallback-compile-tests" "${CMAKE_CURRENT_LIST_DIR}/test-stdexpfilesystem.cpp") # Check for standard headers that we need, fall back to boost if they're not found set(NAMESPACE_ALIAS ${LOG4CXX_NS}) option(PREFER_BOOST "Prefer Boost over std:: equivalents" OFF) if( ${PREFER_BOOST} OR NOT ( ${STD_FILESYSTEM_FOUND} OR ${STD_EXPERIMENTAL_FILESYSTEM_FOUND} ) ) find_package(Boost COMPONENTS filesystem) if( ${Boost_FOUND} ) try_compile(Boost_FILESYSTEM_FOUND "${CMAKE_BINARY_DIR}/boost-fallback-compile-tests" "${CMAKE_CURRENT_LIST_DIR}/test-boostfilesystem.cpp") endif( ${Boost_FOUND} ) endif() if( ${STD_FILESYSTEM_FOUND} AND NOT ${PREFER_BOOST} ) set( FILESYSTEM_IMPL "std::filesystem" ) elseif( ${STD_EXPERIMENTAL_FILESYSTEM_FOUND} AND NOT ${PREFER_BOOST} ) set( FILESYSTEM_IMPL "std::experimental::filesystem" ) elseif( ${Boost_FILESYSTEM_FOUND} ) set( FILESYSTEM_IMPL "boost::filesystem" ) else() set( FILESYSTEM_IMPL "NONE" ) endif() apache-log4cxx-1.3.1/src/cmake/boost-fallback/test-stdexpfilesystem.cpp0000644000175100001770000000015714721727031025526 0ustar runnerdocker#include int main(int argc, char** argv){ std::experimental::filesystem::path p; } apache-log4cxx-1.3.1/src/cmake/boost-fallback/test-boostthread.cpp0000644000175100001770000000013614721727031024425 0ustar runnerdocker#include int main(int argc, char** argv){ boost::thread th; return 0; } apache-log4cxx-1.3.1/src/cmake/boost-fallback/test-stdatomic.cpp0000644000175100001770000000011414721727031024072 0ustar runnerdocker#include int main(int argc, char** argv){ std::atomic b; } apache-log4cxx-1.3.1/src/cmake/boost-fallback/test-boostatomic.cpp0000644000175100001770000000013114721727031024425 0ustar runnerdocker#include int main(int argc, char** argv){ boost::atomic b; } apache-log4cxx-1.3.1/src/cmake/boost-fallback/test-stdsharedmutex.cpp0000644000175100001770000000014214721727031025150 0ustar runnerdocker#include int main(int argc, char** argv){ std::shared_mutex shared; return 0; } apache-log4cxx-1.3.1/src/cmake/boost-fallback/test-boostsharedmutex.cpp0000644000175100001770000000016214721727031025506 0ustar runnerdocker#include int main(int argc, char** argv){ boost::shared_mutex mtx; return 0; } apache-log4cxx-1.3.1/src/cmake/boost-fallback/test-boostfilesystem.cpp0000644000175100001770000000014114721727031025336 0ustar runnerdocker#include int main(int argc, char** argv){ boost::filesystem::path p; } apache-log4cxx-1.3.1/src/cmake/FindODBC.cmake0000644000175100001770000000343314721727031020060 0ustar runnerdocker# Locate odbcinst include paths and libraries include(FindPackageHandleStandardArgs) # This module defines # ODBC_INCLUDE_DIR, where to find odbc.h, etc. # ODBC_LIBRARIES, the libraries to link against to use odbc. # ODBC_FOUND, set to 1 if found set(ODBC_FOUND 0) if(WIN32) set(ODBC_LIBRARIES odbc32.lib user32.lib) try_compile(ODBC_FOUND "${CMAKE_BINARY_DIR}/find-odbc" "${CMAKE_CURRENT_LIST_DIR}/SQLAllocHandleTest.cpp" LINK_LIBRARIES ${ODBC_LIBRARIES}) else() option(ODBC_STATIC "Link to the odbc static library" OFF) if(NOT ODBC_STATIC) # 'pkg-config --static odbc' does not provide libodbc.a file path find_package(PkgConfig) pkg_check_modules(odbc odbc) set(ODBC_FOUND ${odbc_FOUND}) endif() #message("ODBC_FOUND=${ODBC_FOUND}") if(ODBC_FOUND) #message("odbc_INCLUDE_DIRS=${odbc_INCLUDE_DIRS}") #message("odbc_LINK_LIBRARIES=${odbc_LINK_LIBRARIES}") #message("odbc_STATIC_LINK_LIBRARIES=${odbc_STATIC_LINK_LIBRARIES}") find_path(ODBC_INCLUDE_DIR NAMES odbcinst.h HINTS ${odbc_INCLUDE_DIRS} PATH_SUFFIXES odbc) if (ODBC_STATIC OR NOT BUILD_SHARED_LIBS) set(ODBC_LIBRARIES ${odbc_STATIC_LINK_LIBRARIES}) else() set(ODBC_LIBRARIES ${odbc_LINK_LIBRARIES}) endif() else() find_path(ODBC_INCLUDE_DIR odbcinst.h) if (ODBC_STATIC OR NOT BUILD_SHARED_LIBS) find_library(ODBC_LIBRARIES NAMES libodbc.a HINTS ${ODBC_LIBRARY_DIRS} ) else() find_library(ODBC_LIBRARIES NAMES odbc HINTS ${ODBC_LIBRARY_DIRS} ) endif() if(ODBC_INCLUDE_DIR AND ODBC_LIBRARIES) set(ODBC_FOUND 1) endif() endif() #message("ODBC_INCLUDE_DIR=${ODBC_INCLUDE_DIR}") #message("ODBC_LIBRARIES=${ODBC_LIBRARIES}") find_package_handle_standard_args(ODBC ODBC_LIBRARIES) endif() apache-log4cxx-1.3.1/src/cmake/compiler-features/0000755000175100001770000000000014721727031021171 5ustar runnerdockerapache-log4cxx-1.3.1/src/cmake/compiler-features/test-make-unique.cpp0000644000175100001770000000013414721727031025071 0ustar runnerdocker#include int main(int argc, char** argv){ std::make_unique(5); return 0; } apache-log4cxx-1.3.1/src/cmake/compiler-features/test-thread-local.cpp0000644000175100001770000000026314721727031025212 0ustar runnerdocker#include std::string& getCurrentThreadVar() { thread_local std::string thread_id_string; return thread_id_string; } int main(){ getCurrentThreadVar() = "name"; } apache-log4cxx-1.3.1/src/cmake/compiler-features/test-unicode.cpp0000644000175100001770000000063414721727031024303 0ustar runnerdocker/* Prevent error C2491: 'std::numpunct<_Elem>::id': definition of dllimport static data member not allowed */ #if defined(_MSC_VER) #define __FORCE_INSTANCE #endif #include #include using UniChar = unsigned short; using StringType = std::basic_string; using StreamType = std::basic_ostringstream; int main() { StringType str; StreamType ss; ss << str; return 0; } apache-log4cxx-1.3.1/src/cmake/compiler-features/makeunique.h.cmake0000644000175100001770000000056114721727031024567 0ustar runnerdocker#ifndef LOG4CXX_MAKE_UNIQUE_H #define LOG4CXX_MAKE_UNIQUE_H #include #cmakedefine01 STD_MAKE_UNIQUE_FOUND #if !STD_MAKE_UNIQUE_FOUND namespace std { template unique_ptr make_unique( Args&& ...args ) { return unique_ptr( new T( forward(args)... ) ); } } // namespace std #endif #endif /* LOG4CXX_MAKE_UNIQUE_H */ apache-log4cxx-1.3.1/src/cmake/compiler-features/check-compiler-support.cmake0000644000175100001770000000207414721727031026575 0ustar runnerdocker# This module checks compiler and standard library support # # Does the compiler support thread_local? if(MINGW) # As at 2024-7-19 the msys2 ucrt-x86_64 runtime terminates with error c0000374 during thread local data cleanup set(HAS_THREAD_LOCAL FALSE) else() try_compile(HAS_THREAD_LOCAL "${CMAKE_BINARY_DIR}/Testing/thread-local-test" "${CMAKE_CURRENT_LIST_DIR}/test-thread-local.cpp" CXX_STANDARD 11 ) endif() # Does the standard library support std::make_unique>? try_compile(STD_MAKE_UNIQUE_FOUND "${CMAKE_BINARY_DIR}/boost-fallback-compile-tests" "${CMAKE_CURRENT_LIST_DIR}/test-make-unique.cpp") if( ${STD_MAKE_UNIQUE_FOUND} ) set(STD_MAKE_UNIQUE_IMPL "std::make_unique") set(STD_MAKE_UNIQUE_FOUND 1) else() set(STD_MAKE_UNIQUE_IMPL "log4cxx std::make_unique") set(STD_MAKE_UNIQUE_FOUND 0) endif() # Does the standard library support std::basic_string and std::basic_ostream? try_compile(STD_LIB_HAS_UNICODE_STRING "${CMAKE_BINARY_DIR}/Testing/unicode-test" "${CMAKE_CURRENT_LIST_DIR}/test-unicode.cpp" ) apache-log4cxx-1.3.1/src/cmake/FindESMTP.cmake0000644000175100001770000000503014721727031020234 0ustar runnerdocker# Locate libesmtp include paths and libraries include(FindPackageHandleStandardArgs) # This module defines # ESMTP_INCLUDE_DIR, where to find libesmtp.h, etc. # ESMTP_LIBRARIES, the libraries to link against to use libesmtp. # ESMTP_FOUND, set to 'yes' if found macro(_esmtp_invoke _varname) execute_process( COMMAND ${_esmtp_CONFIG_EXECUTABLE} ${ARGN} OUTPUT_VARIABLE _esmtp_output RESULT_VARIABLE _esmtp_failed ) if(_esmtp_failed) message(FATAL_ERROR "${_esmtp_CONFIG_EXECUTABLE} ${ARGN} failed with result ${_esmtp_failed}") else() string(REGEX REPLACE "[\r\n]" "" _esmtp_output "${_esmtp_output}") string(REGEX REPLACE " +$" "" _esmtp_output "${_esmtp_output}") string(REGEX REPLACE "^ +" "" _esmtp_output "${_esmtp_output}") separate_arguments(_esmtp_output) set(${_varname} "${_esmtp_output}") endif(_esmtp_failed) endmacro(_esmtp_invoke) if(NOT LIBESMTP_STATIC) # libesmtp-config does not support --static used in FindPkgConfig.cmake find_package(PkgConfig) pkg_check_modules(esmtp esmtp) #message("esmtp_FOUND=${esmtp_FOUND}") endif() if(esmtp_FOUND) find_path(ESMTP_INCLUDE_DIR NAMES libesmtp.h HINTS ${ESMTP_INCLUDE_DIRS} PATH_SUFFIXES esmtp) if (LIBESMTP_STATIC OR NOT BUILD_SHARED_LIBS) set(ESMTP_LIBRARIES ${LIBESMTP_STATIC_LINK_LIBRARIES}) else() set(ESMTP_LIBRARIES ${ESMTP_LINK_LIBRARIES}) endif() else() find_program(_esmtp_CONFIG_EXECUTABLE libesmtp-config PATHS /usr/local/opt/libesmtp/bin $ENV{ProgramFiles}/esmtp/bin ) mark_as_advanced(_esmtp_CONFIG_EXECUTABLE) if(EXISTS ${_esmtp_CONFIG_EXECUTABLE}) _esmtp_invoke(_esmtp_cflags_args --cflags) #message("_esmtp_cflags_args=${_esmtp_cflags_args}") string(REGEX MATCH "-I([^ ;]+)" _esmtp_include_flag "${_esmtp_cflags_args}") set(ESMTP_INCLUDE_DIR "${CMAKE_MATCH_1}") if (LIBESMTP_STATIC OR NOT BUILD_SHARED_LIBS) find_library(ESMTP_LIBRARIES NAMES libesmtp.a) else() _esmtp_invoke(ESMTP_LIBRARIES --libs) endif() else() find_path(ESMTP_INCLUDE_DIR libesmtp.h PATH_SUFFIXES esmtp) if (LIBESMTP_STATIC OR NOT BUILD_SHARED_LIBS) find_library(ESMTP_LIBRARIES NAMES libesmtp.a) else() find_library(ESMTP_LIBRARIES NAMES esmtp) endif() endif() endif() #message("ESMTP_INCLUDE_DIR=${ESMTP_INCLUDE_DIR}") #message("ESMTP_LIBRARIES=${ESMTP_LIBRARIES}") find_package_handle_standard_args(ESMTP ESMTP_INCLUDE_DIR ESMTP_LIBRARIES) apache-log4cxx-1.3.1/src/examples/0000755000175100001770000000000014721727031016301 5ustar runnerdockerapache-log4cxx-1.3.1/src/examples/config/0000755000175100001770000000000014721727031017546 5ustar runnerdockerapache-log4cxx-1.3.1/src/examples/config/async-example.xml0000644000175100001770000000240514721727031023037 0ustar runnerdocker apache-log4cxx-1.3.1/src/examples/cpp/0000755000175100001770000000000014721727031017063 5ustar runnerdockerapache-log4cxx-1.3.1/src/examples/cpp/ndc-example.cpp0000644000175100001770000000313114721727031021762 0ustar runnerdocker/* * 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. */ #include #include #include #include #include using namespace log4cxx; int main() { setlocale(LC_ALL, ""); // Use the user-preferred locale int result = EXIT_SUCCESS; try { BasicConfigurator::configure(); LoggerPtr rootLogger = Logger::getRootLogger(); NDC context1("[outer]"); LOG4CXX_INFO(rootLogger, "info message"); // log entry contains "[outer]" { NDC context2("[inner]"); LOG4CXX_DEBUG(rootLogger, "debug message"); // log entry contains "[outer] [inner]" } LOG4CXX_WARN(rootLogger, "warn message"); // log entry contains "[outer]" } catch(std::exception&) { result = EXIT_FAILURE; } return result; } apache-log4cxx-1.3.1/src/examples/cpp/auto-configured.xml0000644000175100001770000000101014721727031022670 0ustar runnerdocker apache-log4cxx-1.3.1/src/examples/cpp/format-string.cpp0000644000175100001770000000525514721727031022372 0ustar runnerdocker/* * 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. */ #include #include #include #include #if LOG4CXX_USING_STD_FORMAT #include #else #include #include #include #endif #include struct MyStruct { int x; }; std::ostream& operator<<( std::ostream& stream, const MyStruct& mystruct ){ stream << "[MyStruct x:" << mystruct.x << "]"; return stream; } #if LOG4CXX_USING_STD_FORMAT template struct basic_ostream_formatter : std::formatter, Char> { template auto format(const T& value, std::basic_format_context& ctx) const -> OutputIt { std::basic_stringstream ss; ss << value; return std::formatter, Char>::format(ss.view(), ctx); } }; template <> struct std::formatter : basic_ostream_formatter {}; #elif FMT_VERSION >= (9 * 10000) template <> struct fmt::formatter : ostream_formatter {}; #endif int main() { setlocale(LC_ALL, ""); using namespace log4cxx; BasicConfigurator::configure(); auto rootLogger = Logger::getRootLogger(); LOG4CXX_INFO_FMT( rootLogger, "This is a {} mesage", "test" ); #if !LOG4CXX_USING_STD_FORMAT LOG4CXX_INFO_FMT( rootLogger, fmt::fg(fmt::color::red), "Messages can be colored" ); #endif LOG4CXX_INFO_FMT( rootLogger, "We can also align text to the {:<10} or {:>10}", "left", "right" ); MyStruct mine{ 42 }; LOG4CXX_INFO_FMT( rootLogger, "This custom type {} can also be logged, since it implements operator<<", mine ); LOG4CXX_INFO( rootLogger, "Numbers can be formatted with excessive operator<<: " << std::setprecision(3) << 22.456 << " And as hex: " << std::setbase( 16 ) << 123 ); LOG4CXX_INFO_FMT( rootLogger, "Numbers can be formatted with a format string {:.1f} and as hex: {:x}", 22.456, 123 ); return 0; } apache-log4cxx-1.3.1/src/examples/cpp/stream.cpp0000644000175100001770000000363714721727031021073 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include using namespace log4cxx; using namespace log4cxx::helpers; int main() { setlocale(LC_ALL, ""); int result = EXIT_SUCCESS; try { BasicConfigurator::configure(); LoggerPtr rootLogger = Logger::getRootLogger(); NDC::push("trivial context"); log4cxx::logstream logstream(rootLogger, Level::getDebug()); logstream << "debug message " << 1 << LOG4CXX_ENDMSG; logstream.setLevel(Level::getInfo()); logstream << "info message" << LOG4CXX_ENDMSG; logstream << Level::getWarn() << "warn message" << LOG4CXX_ENDMSG; logstream << Level::getError() << "error message" << LOG4CXX_ENDMSG; logstream << Level::getFatal() << "fatal message" << LOG4CXX_ENDMSG; NDC::pop(); } catch(std::exception&) { result = EXIT_FAILURE; } return result; } apache-log4cxx-1.3.1/src/examples/cpp/auto-configured.cpp0000644000175100001770000000210514721727031022660 0ustar runnerdocker/* * 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. */ #include "com/foo/config.h" auto rootLogger = com::foo::getLogger(); struct ExampleStaticData { ExampleStaticData() { LOG4CXX_DEBUG(rootLogger, "static initializer message"); } } static_object; int main() { LOG4CXX_INFO(rootLogger, "main function message"); return EXIT_SUCCESS; } apache-log4cxx-1.3.1/src/examples/cpp/com/0000755000175100001770000000000014721727031017641 5ustar runnerdockerapache-log4cxx-1.3.1/src/examples/cpp/com/foo/0000755000175100001770000000000014721727031020424 5ustar runnerdockerapache-log4cxx-1.3.1/src/examples/cpp/com/foo/config-qt.cpp0000644000175100001770000000510514721727031023020 0ustar runnerdocker/* * 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. */ #include "config-qt.h" #include #include #include #include #include #include #include #include namespace com { namespace foo { // Provide the name of the configuration file to Log4cxx. // Reload the configuration on a QFileSystemWatcher::fileChanged event. void ConfigureLogging() { using namespace log4cxx; static struct log4cxx_finalizer { ~log4cxx_finalizer() { LogManager::shutdown(); } } finaliser; QFileInfo app{QCoreApplication::applicationFilePath()}; QString basename{app.baseName()}; QVector paths = { QString(".") , app.absoluteDir().absolutePath() }; QVector names = { QString(basename + ".xml") , QString(basename + ".properties") , QString("MyApp.properties") , QString("log4cxx.xml") , QString("log4cxx.properties") , QString("log4j.xml") , QString("log4j.properties") }; #if defined(_DEBUG) helpers::LogLog::setInternalDebugging(true); #endif auto status = spi::ConfigurationStatus::NotConfigured; auto selectedPath = QString(); std::tie(status, selectedPath) = qt::Configuration::configureFromFileAndWatch(paths, names); if (status == spi::ConfigurationStatus::NotConfigured) BasicConfigurator::configure(); // Send events to the console } // Retrieve the \c name logger pointer. auto getLogger(const QString& name) -> LoggerPtr { using namespace log4cxx; return name.isEmpty() ? LogManager::getRootLogger() : LogManager::getLogger(name.toStdString()); } // Retrieve the \c name logger pointer. auto getLogger(const char* name) -> LoggerPtr { using namespace log4cxx; return name ? LogManager::getLogger(name) : LogManager::getRootLogger(); } } } // namespace com::foo apache-log4cxx-1.3.1/src/examples/cpp/com/foo/config.h0000644000175100001770000000065314721727031022046 0ustar runnerdocker#ifndef COM_FOO_CONFIG_H_ #define COM_FOO_CONFIG_H_ #include /// Types specific to foo.com namespace com { namespace foo { /// The logger pointer we use using LoggerPtr = log4cxx::LoggerPtr; /// Retrieve the \c name logger pointer. /// Configure Log4cxx on the first call. extern auto getLogger(const std::string& name = std::string()) -> LoggerPtr; } } // namespace com::foo #endif // COM_FOO_CONFIG_H_ apache-log4cxx-1.3.1/src/examples/cpp/com/foo/config3.cpp0000644000175100001770000001323714721727031022466 0ustar runnerdocker/* * 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. */ #include "config.h" #include #include #include #include #include #include #include #include #ifdef _WIN32 #include #elif __APPLE__ #include #elif (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 500) || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L) #include // getpid #else #include // strncpy #endif // Local functions namespace { using namespace log4cxx; // Get a list of file base names that may contain configuration data // and put an alternate path into \c altPrefix auto DefaultConfigurationFileNames(std::string& altPrefix) -> std::vector { std::vector result; // Find the executable file name static const int bufSize = 4096; char buf[bufSize+1] = {0}, pathSepar = '/'; uint32_t bufCount = 0; #if defined(_WIN32) GetModuleFileName(NULL, buf, bufSize); pathSepar = '\\'; #elif defined(__APPLE__) _NSGetExecutablePath(buf, &bufCount); #elif (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 500) || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L) std::ostringstream exeLink; exeLink << "/proc/" << getpid() << "/exe"; bufCount = readlink(exeLink.str().c_str(), buf, bufSize); if (0 < bufCount) buf[bufCount] = 0; #else strncpy(buf, "auto-configured", bufSize); #endif std::string programFileName(buf); auto slashIndex = programFileName.rfind(pathSepar); if (std::string::npos != slashIndex) { // Extract the path altPrefix = programFileName.substr(0, slashIndex + 1); if (helpers::LogLog::isDebugEnabled()) { LogString msg = LOG4CXX_STR("Alternate prefix ["); helpers::Transcoder::decode(altPrefix, msg); msg += LOG4CXX_STR("]"); helpers::LogLog::debug(msg); } // Add a local directory relative name result.push_back(programFileName.substr(slashIndex + 1)); if (helpers::LogLog::isDebugEnabled()) { LogString msg(LOG4CXX_STR("Alternate configuration file name [")); helpers::Transcoder::decode(result.back(), msg); msg += LOG4CXX_STR("]"); helpers::LogLog::debug(msg); } // Add a local directory relative name without any extension auto dotIndex = result.back().rfind('.'); if (std::string::npos != dotIndex) { result.push_back(result.back()); result.back().erase(dotIndex); if (helpers::LogLog::isDebugEnabled()) { LogString msg(LOG4CXX_STR("Alternate configuration file name [")); helpers::Transcoder::decode(result.back(), msg); msg += LOG4CXX_STR("]"); helpers::LogLog::debug(msg); } } } else if (!programFileName.empty()) { auto dotIndex = result.back().rfind('.'); if (std::string::npos != dotIndex) { programFileName.erase(dotIndex); result.push_back(programFileName); if (helpers::LogLog::isDebugEnabled()) { LogString msg(LOG4CXX_STR("Alternate configuration file name [")); helpers::Transcoder::decode(result.back(), msg); msg += LOG4CXX_STR("]"); helpers::LogLog::debug(msg); } } } result.push_back("log4cxx"); result.push_back("log4j"); return result; } // Provide the name of the configuration file to [DefaultConfigurator](@ref log4cxx.DefaultConfigurator). // Set up a background thread that will check for changes every 5 seconds and reload the configuration void SelectConfigurationFile() { #if defined(_DEBUG) helpers::LogLog::setInternalDebugging(true); #endif const char* extension[] = { ".xml", ".properties", 0 }; std::string altPrefix; helpers::Pool pool; for (auto baseName : DefaultConfigurationFileNames(altPrefix)) { int i = 0; for (; extension[i]; ++i) { File current_working_dir_candidate(baseName + extension[i]); if (current_working_dir_candidate.exists(pool)) { DefaultConfigurator::setConfigurationFileName(current_working_dir_candidate.getPath()); DefaultConfigurator::setConfigurationWatchSeconds(5); break; } if (!altPrefix.empty()) { File alt_dir_candidate(altPrefix + baseName + extension[i]); if (alt_dir_candidate.exists(pool)) { DefaultConfigurator::setConfigurationFileName(alt_dir_candidate.getPath()); DefaultConfigurator::setConfigurationWatchSeconds(5); break; } } } if (extension[i]) // Found a configuration file? return; } // Configuration file not found - send events to the console BasicConfigurator::configure(); } } // namespace namespace com { namespace foo { // Retrieve the \c name logger pointer. // Configure Log4cxx on the first call. auto getLogger(const std::string& name) -> LoggerPtr { using namespace log4cxx; static struct log4cxx_initializer { log4cxx_initializer() { SelectConfigurationFile(); } ~log4cxx_initializer() { LogManager::shutdown(); } } initialiser; return name.empty() ? LogManager::getRootLogger() : LogManager::getLogger(name); } } } // namespace com::foo apache-log4cxx-1.3.1/src/examples/cpp/com/foo/bar.h0000644000175100001770000000035614721727031021345 0ustar runnerdocker#ifndef COM_FOO_BAR_H_ #define COM_FOO_BAR_H_ #include "com/foo/config.h" namespace com { namespace foo { class Bar { static LoggerPtr m_logger; public: void doIt(); }; } } // namespace com::foo #endif // COM_FOO_BAR_H_ apache-log4cxx-1.3.1/src/examples/cpp/com/foo/bar-qt.cpp0000644000175100001770000000035114721727031022315 0ustar runnerdocker#include "com/foo/bar.h" #include "com/foo/config-qt.h" using namespace com::foo; LoggerPtr Bar::m_logger(getLogger("com.foo.bar")); void Bar::doIt() { LOG4CXX_DEBUG(m_logger, QString("Did it again!") << QString(" - again!")); } apache-log4cxx-1.3.1/src/examples/cpp/com/foo/bar.cpp0000644000175100001770000000025114721727031021672 0ustar runnerdocker#include "com/foo/bar.h" using namespace com::foo; LoggerPtr Bar::m_logger(getLogger("com.foo.bar")); void Bar::doIt() { LOG4CXX_DEBUG(m_logger, "Did it again!"); } apache-log4cxx-1.3.1/src/examples/cpp/com/foo/config1.cpp0000644000175100001770000000107314721727031022457 0ustar runnerdocker#include "com/foo/config.h" #include #include namespace com { namespace foo { auto getLogger(const std::string& name) -> LoggerPtr { using namespace log4cxx; static struct log4cxx_initializer { log4cxx_initializer() { // Set up a simple configuration that logs on the console. BasicConfigurator::configure(); } ~log4cxx_initializer() { LogManager::shutdown(); } } initAndShutdown; return name.empty() ? LogManager::getRootLogger() : LogManager::getLogger(name); } } } // namespace com::foo apache-log4cxx-1.3.1/src/examples/cpp/com/foo/config2.cpp0000644000175100001770000000125514721727031022462 0ustar runnerdocker#include "com/foo/config.h" #include #include #include namespace com { namespace foo { auto getLogger(const std::string& name) -> LoggerPtr { using namespace log4cxx; static struct log4cxx_initializer { log4cxx_initializer() { if (PropertyConfigurator::configure("MyApp.properties") == spi::ConfigurationStatus::NotConfigured) BasicConfigurator::configure(); // Send events to the console } ~log4cxx_initializer() { LogManager::shutdown(); } } initAndShutdown; return name.empty() ? LogManager::getRootLogger() : LogManager::getLogger(name); } } } // namespace com::foo apache-log4cxx-1.3.1/src/examples/cpp/com/foo/config-qt.h0000644000175100001770000000106714721727031022470 0ustar runnerdocker#ifndef COM_FOO_CONFIG_QT_H_ #define COM_FOO_CONFIG_QT_H_ #include /// Methods specific to foo.com namespace com { namespace foo { // Provide the name of the configuration file to Log4cxx. void ConfigureLogging(); /// The logger pointer we use using LoggerPtr = log4cxx::LoggerPtr; /// Retrieve the \c name logger pointer. extern auto getLogger(const QString& name) -> LoggerPtr; /// Retrieve the \c name logger pointer. extern auto getLogger(const char* name = NULL) -> LoggerPtr; } } // namespace com::foo #endif // COM_FOO_CONFIG_QT_H_ apache-log4cxx-1.3.1/src/examples/cpp/custom-appender.xml0000644000175100001770000000134414721727031022715 0ustar runnerdocker apache-log4cxx-1.3.1/src/examples/cpp/MyApp1.cpp0000644000175100001770000000147214721727031020702 0ustar runnerdocker#include #include static auto logger = log4cxx::Logger::getLogger("MyApp"); void foo() { // Get a logger that is a child of the statically declared logger auto fooLogger = log4cxx::Logger::getLogger("MyApp.foo"); LOG4CXX_TRACE(fooLogger, "Doing foo at trace level"); LOG4CXX_DEBUG(fooLogger, "Doing foo at debug level"); LOG4CXX_INFO(fooLogger, "Doing foo at info level"); LOG4CXX_WARN(fooLogger, "Doing foo at warn level"); LOG4CXX_ERROR(fooLogger, "Doing foo at error level"); LOG4CXX_FATAL(fooLogger, "Doing foo at fatal level"); } int main(int argc, char **argv) { // Log to standard output. log4cxx::BasicConfigurator::configure(); LOG4CXX_INFO(logger, "Entering application."); foo(); LOG4CXX_INFO(logger, "Exiting application."); return EXIT_SUCCESS; } apache-log4cxx-1.3.1/src/examples/cpp/CMakeLists.txt0000644000175100001770000000700014721727031021620 0ustar runnerdocker# # 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. # set(ALL_LOG4CXX_EXAMPLES auto-configured console delayedloop stream ndc-example custom-appender MyApp1 MyApp2) if(NOT LOG4CXX_DOMCONFIGURATOR_SUPPORT) list(REMOVE_ITEM ALL_LOG4CXX_EXAMPLES delayedloop custom-appender) endif() if(LOG4CXX_QT_SUPPORT) list(APPEND ALL_LOG4CXX_EXAMPLES MyApp-qt) endif(LOG4CXX_QT_SUPPORT) if( WIN32 ) include(win32_target_environment_path) get_target_environment_path(ESCAPED_PATH) elseif(CMAKE_BUILD_TYPE) string(TOUPPER ${CMAKE_BUILD_TYPE} UPPER_BUILD_TYPE) if (UPPER_BUILD_TYPE STREQUAL "DEBUG") set(EXAMPLE_COMPILE_DEFINITIONS _DEBUG) endif() else() set(EXAMPLE_COMPILE_DEFINITIONS _DEBUG) endif() foreach(exampleName IN LISTS ALL_LOG4CXX_EXAMPLES) set(PROGRAM_NAME "${exampleName}") add_executable(${PROGRAM_NAME} ${exampleName}.cpp) if(${exampleName} STREQUAL MyApp2) target_sources(${PROGRAM_NAME} PRIVATE com/foo/config2.cpp com/foo/bar.cpp) endif() if(${exampleName} STREQUAL MyApp-qt) target_sources(${PROGRAM_NAME} PRIVATE com/foo/config-qt.cpp com/foo/bar-qt.cpp) target_link_libraries(${PROGRAM_NAME} PRIVATE log4cxx-qt) endif() if(${exampleName} STREQUAL auto-configured) target_sources(${PROGRAM_NAME} PRIVATE com/foo/config3.cpp ) endif() target_compile_definitions(${PROGRAM_NAME} PRIVATE ${EXAMPLE_COMPILE_DEFINITIONS} ${LOG4CXX_COMPILE_DEFINITIONS} ${APR_COMPILE_DEFINITIONS} ${APR_UTIL_COMPILE_DEFINITIONS} ) target_include_directories(${PROGRAM_NAME} PRIVATE ${CMAKE_CURRENT_LIST_DIR} $) target_link_libraries(${PROGRAM_NAME} PRIVATE log4cxx ${APR_UTIL_LIBRARIES} ${EXPAT_LIBRARIES} ${APR_LIBRARIES} ${APR_SYSTEM_LIBS}) if( WIN32 ) set_target_properties(${PROGRAM_NAME} PROPERTIES VS_DEBUGGER_ENVIRONMENT "PATH=${ESCAPED_PATH}" VS_DEBUGGER_WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} FOLDER Examples ) endif() endforeach() # Custom handling for format string example, since it utilizes libfmt if(${fmt_FOUND}) add_executable( format-string format-string.cpp ) target_compile_definitions(format-string PRIVATE ${LOG4CXX_COMPILE_DEFINITIONS} ${APR_COMPILE_DEFINITIONS} ${APR_UTIL_COMPILE_DEFINITIONS} ) target_include_directories(format-string PRIVATE ${CMAKE_CURRENT_LIST_DIR} $) target_link_libraries(format-string PRIVATE log4cxx ${APR_UTIL_LIBRARIES} ${EXPAT_LIBRARIES} ${APR_LIBRARIES} ${APR_SYSTEM_LIBS} fmt::fmt) if( WIN32 ) set_target_properties( format-string PROPERTIES VS_DEBUGGER_ENVIRONMENT "PATH=${ESCAPED_PATH}" VS_DEBUGGER_WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} FOLDER Examples ) endif() endif(${fmt_FOUND}) apache-log4cxx-1.3.1/src/examples/cpp/custom-appender.cpp0000644000175100001770000000435714721727031022706 0ustar runnerdocker/* * 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. */ #include #include #include #include using namespace LOG4CXX_NS; namespace com::foo { class NullWriterAppender : public AppenderSkeleton { public: DECLARE_LOG4CXX_OBJECT(NullWriterAppender) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(NullWriterAppender) LOG4CXX_CAST_ENTRY_CHAIN(AppenderSkeleton) END_LOG4CXX_CAST_MAP() NullWriterAppender(){} void close() override{} bool requiresLayout() const override { return false; } void append(const spi::LoggingEventPtr& event, helpers::Pool& p) override { // This gets called whenever there is a valid event for our appender. } void activateOptions(helpers::Pool& /* pool */) override { // Given all of our options, do something useful(e.g. open a file) } void setOption(const LogString& option, const LogString& value) override { if (helpers::StringHelper::equalsIgnoreCase ( option , LOG4CXX_STR("SOMEVALUE") , LOG4CXX_STR("somevalue") )) { // Do something with the 'value' here. } } }; IMPLEMENT_LOG4CXX_OBJECT(NullWriterAppender) } int main( int argc, char** argv ) { xml::DOMConfigurator::configure( "custom-appender.xml" ); LoggerPtr rootLogger = Logger::getRootLogger(); LoggerPtr nullLogger = Logger::getLogger( "NullLogger" ); LOG4CXX_INFO( rootLogger, "This is some root message" ); LOG4CXX_INFO( nullLogger, "This message will be discarded" ); } apache-log4cxx-1.3.1/src/examples/cpp/MyApp-qt.cpp0000644000175100001770000000074414721727031021244 0ustar runnerdocker#include #include "com/foo/config-qt.h" #include "com/foo/bar.h" int main(int argc, char **argv) { int result = EXIT_SUCCESS; QCoreApplication app(argc, argv); com::foo::ConfigureLogging(); try { auto logger = com::foo::getLogger("MyApp"); LOG4CXX_INFO(logger, QString("Message %1").arg(1)); com::foo::Bar bar; bar.doIt(); LOG4CXX_INFO(logger, QString("Message %1").arg(2)); } catch(std::exception&) { result = EXIT_FAILURE; } return result; } apache-log4cxx-1.3.1/src/examples/cpp/console.cpp0000644000175100001770000000736414721727031021243 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include /** * Configures console appender. * @param err if true, use stderr, otherwise stdout. */ static void configure(bool err) { using namespace log4cxx; auto r = LogManager::getLoggerRepository(); r->ensureIsConfigured([r,err]() { auto appender = std::make_shared ( std::make_shared() , err ? ConsoleAppender::getSystemErr() : ConsoleAppender::getSystemOut() ); r->getRootLogger()->addAppender(appender); }); } /** * Program to test compatibility of C RTL, C++ STL and log4cxx output to standard * output and error streams. * * See bug LOGCXX_126. * * */ int main(int argc, char** argv) { setlocale(LC_ALL, ""); if (argc <= 1) { puts("Console test program\nUsage: console [-err] [ puts | putws | cout | wcout | configure | log | wide | byte ]*\n"); } bool configured = false; bool err = false; for (int i = 1; i < argc; i++) { if (strcmp("-err", argv[i]) == 0) { err = true; } else if (strcmp("puts", argv[i]) == 0) { fputs("Hello, fputs\n", err ? stderr : stdout); #if LOG4CXX_WCHAR_T_API } else if (strcmp("putws", argv[i]) == 0) { fputws(L"Hello, fputws\n", err ? stderr : stdout); #endif } else if (strcmp("cout", argv[i]) == 0) { if (err) { std::cerr << "Hello, cout" << std::endl; } else { std::cout << "Hello, cout" << std::endl; } } else if (strcmp("wcout", argv[i]) == 0) { if (err) { #if LOG4CXX_HAS_STD_WCOUT std::wcerr << L"Hello, wcout" << std::endl; #else std::cerr << "Log4cxx has not wcout" << std::endl; #endif } else { #if LOG4CXX_HAS_STD_WCOUT std::wcout << L"Hello, wcout" << std::endl; #else std::cout << "Log4cxx has not wcout" << std::endl; #endif } } else if (strcmp("configure", argv[i]) == 0) { configure(err); configured = true; } else if (strcmp("log", argv[i]) == 0) { if (!configured) { configure(err); configured = true; } log4cxx::Logger::getRootLogger()->info("Hello, log4cxx"); #if LOG4CXX_WCHAR_T_API } else if (strcmp("wide", argv[i]) == 0) { fwide(err ? stderr : stdout, 1); } else if (strcmp("byte", argv[i]) == 0) { fwide(err ? stderr : stdout, -1); #endif } else { fputs("Unrecognized option: ", stderr); fputs(argv[i], stderr); fputs("\n", stderr); fflush(stderr); } } return 0; } apache-log4cxx-1.3.1/src/examples/cpp/MyApp.properties0000644000175100001770000000123614721727031022231 0ustar runnerdocker# Append log events onto stdout and R log4j.rootLogger=DEBUG, stdout, R log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout # Pattern to output the caller's file name and line number. log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%f:%L) - %m%n log4j.appender.R=org.apache.log4j.RollingFileAppender log4j.appender.R.File=example.log # Move example.log to example.log.1 at 100 KB in size log4j.appender.R.MaxFileSize=100KB # Keep one backup file log4j.appender.R.MaxBackupIndex=1 log4j.appender.R.layout=org.apache.log4j.PatternLayout log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n apache-log4cxx-1.3.1/src/examples/cpp/MyApp2.cpp0000644000175100001770000000057014721727031020701 0ustar runnerdocker#include "com/foo/config.h" #include "com/foo/bar.h" int main(int argc, char **argv) { int result = EXIT_SUCCESS; try { auto logger = com::foo::getLogger("MyApp"); LOG4CXX_INFO(logger, "Entering application."); com::foo::Bar bar; bar.doIt(); LOG4CXX_INFO(logger, "Exiting application."); } catch(std::exception&) { result = EXIT_FAILURE; } return result; } apache-log4cxx-1.3.1/src/examples/cpp/delayedloop.cpp0000644000175100001770000000631114721727031022071 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #include #include using namespace log4cxx; using namespace log4cxx::helpers; /** This test program sits in a loop and logs things. Its logging is configured by a configuration file. Changes to this configuration file are monitored and when a change occurs, the config file is re-read. */ class DelayedLoop { static LoggerPtr logger; public: static void main(int argc, const char * const argv[]) { if(argc == 2) { init(argv[1]); } else { usage(argv[0], "Wrong number of arguments."); } test(); } static void usage(const char * programName, const char * msg) { std::cout << msg << std::endl; std::cout << "Usage: " << programName << " configFile" << std::endl; exit(1); } static void init(const std::string& configFile) { if(configFile.length() > 4 && configFile.substr(configFile.length() - 4) == ".xml") { xml::DOMConfigurator::configureAndWatch(configFile, 3000); } else { PropertyConfigurator::configureAndWatch(configFile, 3000); } } static void test() { int i = 0; while(true) { LOG4CXX_DEBUG(logger, "MSG " << i++); try { apr_sleep(1000000); } catch(std::exception&) { } } } }; LoggerPtr DelayedLoop::logger = Logger::getLogger("DelayedLoop"); int main(int argc, const char * const argv[]) { apr_app_initialize(&argc, &argv, NULL); int result = EXIT_SUCCESS; try { DelayedLoop::main(argc, argv); } catch(std::exception&) { result = EXIT_FAILURE; } apr_terminate(); return result; } apache-log4cxx-1.3.1/src/main/0000755000175100001770000000000014721727031015407 5ustar runnerdockerapache-log4cxx-1.3.1/src/main/cpp-qt/0000755000175100001770000000000014721727031016613 5ustar runnerdockerapache-log4cxx-1.3.1/src/main/cpp-qt/messagehandler.cpp0000644000175100001770000000362314721727031022305 0ustar runnerdocker/* * 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. */ #include #include #include namespace LOG4CXX_NS { namespace qt { void messageHandler(QtMsgType type, const QMessageLogContext& context, const QString& message ) { LOG4CXX_NS::LoggerPtr qtLogger = LOG4CXX_NS::Logger::getLogger( context.category ); LOG4CXX_NS::spi::LocationInfo location( context.file, LOG4CXX_NS::spi::LocationInfo::calcShortFileName(context.file), context.function, context.line ); switch ( type ) { case QtMsgType::QtDebugMsg: qtLogger->debug( message.toStdString(), location ); break; case QtMsgType::QtWarningMsg: qtLogger->warn( message.toStdString(), location ); break; #if QT_VERSION >= QT_VERSION_CHECK(5, 5, 0) case QtMsgType::QtInfoMsg: qtLogger->info( message.toStdString(), location ); break; #endif case QtMsgType::QtCriticalMsg: qtLogger->error( message.toStdString(), location ); break; case QtMsgType::QtFatalMsg: qtLogger->fatal( message.toStdString(), location ); std::abort(); } } } /* namespace qt */ } /* namespace log4cxx */ apache-log4cxx-1.3.1/src/main/cpp-qt/configuration.cpp0000644000175100001770000001040214721727031022163 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #include #include namespace LOG4CXX_NS { namespace qt { using LOG4CXX_NS::helpers::LogLog; static std::unique_ptr watcher; static QString configFilename; static void loadXMLFile(const QString& path){ QFileInfo fi(configFilename); if(!fi.exists()){ return; } LOG4CXX_NS::xml::DOMConfigurator::configure(path.toStdString()); } static void loadPropertiesFile(const QString& path){ QFileInfo fi(configFilename); if(!fi.exists()){ return; } LOG4CXX_NS::PropertyConfigurator::configure(path.toStdString()); } static void dirChanged(const QString&){ QFileInfo fi(configFilename); if(fi.exists()){ // From the Qt docs: // Note that QFileSystemWatcher stops monitoring files once they have been renamed // or removed from disk, and directories once they have been removed from disk. // // Some text editing programs will replace the file with a new one, which deletes // the old file(thus causing Qt to remove the watch), so we need to add in the // file whenever the directory changes. // See also: https://stackoverflow.com/questions/18300376/qt-qfilesystemwatcher-signal-filechanged-gets-emited-only-once watcher->addPath(configFilename); } } Configuration::Configuration(){} LOG4CXX_NS::spi::ConfigurationStatus Configuration::tryLoadFile(const QString& filename){ LOG4CXX_NS::spi::ConfigurationStatus stat =LOG4CXX_NS::spi::ConfigurationStatus::NotConfigured; bool isXML = false; if(filename.endsWith(".xml")){ stat = LOG4CXX_NS::xml::DOMConfigurator::configure(filename.toStdString()); isXML = true; }else if(filename.endsWith(".properties")){ stat = LOG4CXX_NS::PropertyConfigurator::configure(filename.toStdString()); } if( stat == LOG4CXX_NS::spi::ConfigurationStatus::Configured ){ watcher = std::make_unique(); configFilename = filename; QFileInfo fi(filename); watcher->addPath(fi.dir().absolutePath()); watcher->addPath(filename); QObject::connect(watcher.get(), &QFileSystemWatcher::directoryChanged, &dirChanged); if(isXML){ QObject::connect(watcher.get(), &QFileSystemWatcher::fileChanged, &loadXMLFile); }else{ QObject::connect(watcher.get(), &QFileSystemWatcher::fileChanged, &loadPropertiesFile); } } return stat; } std::tuple Configuration::configureFromFileAndWatch(const QVector& directories, const QVector& filenames){ for( QString dir : directories ){ for( QString fname : filenames ){ QString canidate_str = dir + "/" + fname; QFile candidate(canidate_str); if (LogLog::isDebugEnabled()) { LOG4CXX_DECODE_QSTRING(msg, "Checking file " + canidate_str); LogLog::debug(msg); } if (candidate.exists()) { LOG4CXX_NS::spi::ConfigurationStatus configStatus = tryLoadFile(canidate_str); if( configStatus == LOG4CXX_NS::spi::ConfigurationStatus::Configured ){ return {configStatus, canidate_str}; } if (LogLog::isDebugEnabled()) { LOG4CXX_DECODE_QSTRING(failmsg, "Unable to load " + canidate_str + ": trying next"); LogLog::debug(failmsg); } } } } return {LOG4CXX_NS::spi::ConfigurationStatus::NotConfigured, QString()}; } } //namespace helpers } //namespace log4cxx apache-log4cxx-1.3.1/src/main/cpp-qt/CMakeLists.txt0000644000175100001770000000326114721727031021355 0ustar runnerdocker# # 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. # # Log4cxx Qt support, if enabled if(LOG4CXX_QT_SUPPORT) find_package(Qt5 COMPONENTS Core REQUIRED) add_library(log4cxx-qt) if(BUILD_SHARED_LIBS) target_compile_definitions(log4cxx-qt PRIVATE LOG4CXX) else() target_compile_definitions(log4cxx-qt PUBLIC LOG4CXX_STATIC) endif() add_dependencies(log4cxx-qt log4cxx-qt-include) target_compile_definitions(log4cxx-qt PRIVATE "QT_NO_KEYWORDS") target_link_libraries(log4cxx-qt Qt5::Core log4cxx) target_sources(log4cxx-qt PRIVATE messagehandler.cpp configuration.cpp ) set_target_properties(log4cxx-qt PROPERTIES VERSION ${LIBLOG4CXX_LIB_VERSION} SOVERSION ${LIBLOG4CXX_LIB_SOVERSION} OUTPUT_NAME ${LOG4CXX_LIB_NAME}-qt PDB_NAME ${LOG4CXX_LIB_NAME}-qt COMPILE_PDB_NAME ${LOG4CXX_LIB_NAME}-qt EXPORT_NAME ${LOG4CXX_LIB_NAME}-qt ) endif( LOG4CXX_QT_SUPPORT) apache-log4cxx-1.3.1/src/main/include/0000755000175100001770000000000014721727031017032 5ustar runnerdockerapache-log4cxx-1.3.1/src/main/include/log4cxx-qt/0000755000175100001770000000000014721727031021044 5ustar runnerdockerapache-log4cxx-1.3.1/src/main/include/log4cxx-qt/transcoder.h0000644000175100001770000000635214721727031023367 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_QT_TRANSCODER_H #define _LOG4CXX_QT_TRANSCODER_H #include #include #if LOG4CXX_LOGCHAR_IS_UTF8 /** Create a log4cxx::LogString equivalent of \c src. Defines a log4cxx::LogString variable \c var initialized with characters equivalent to the QString \c src contents. @param var The name of the new log4cxx::LogString variable. @param src The QString variable. */ #define LOG4CXX_DECODE_QSTRING(var, src) \ LOG4CXX_NS::LogString var = (src).toStdString() /** Create a QString equivalent of \c src. Defines a QString variable \c var initialized with characters equivalent to the log4cxx::LogString \c src contents. @param var The name of the new QString variable. @param src The log4cxx::LogString variable. */ #define LOG4CXX_ENCODE_QSTRING(var, src) \ QString var = QString::fromStdString(src) #endif // LOG4CXX_LOGCHAR_IS_UTF8 #if LOG4CXX_LOGCHAR_IS_WCHAR /** Create a log4cxx::LogString equivalent of \c src. Defines a log4cxx::LogString variable \c var initialized with characters equivalent to the QString \c src contents. @param var The name of the new log4cxx::LogString variable. @param src The QString variable. */ #define LOG4CXX_DECODE_QSTRING(var, src) \ LOG4CXX_NS::LogString var = (src).toStdWString() /** Create a QString equivalent of \c src. Defines a QString variable \c var initialized with characters equivalent to the log4cxx::LogString \c src contents. @param var The name of the new QString variable. @param src The log4cxx::LogString variable. */ #define LOG4CXX_ENCODE_QSTRING(var, src) \ QString var = QString::fromStdWString(src) #endif // LOG4CXX_LOGCHAR_IS_WCHAR #if LOG4CXX_LOGCHAR_IS_UNICHAR /** Create a log4cxx::LogString equivalent of \c src. Defines a log4cxx::LogString variable \c var initialized with characters equivalent to the QString \c src contents. @param var The name of the new log4cxx::LogString variable. @param src The QString variable. */ #define LOG4CXX_DECODE_QSTRING(var, src) \ LOG4CXX_NS::LogString var = (src).utf16() /** Create a QString equivalent of \c src. Defines a QString variable \c var initialized with characters equivalent to the log4cxx::LogString \c src contents. @param var The name of the new QString variable. @param src The log4cxx::LogString variable. */ #define LOG4CXX_ENCODE_QSTRING(var, src) \ QString var = QString::fromUtf16((char16_t*)src.c_str()) #endif // LOG4CXX_LOGCHAR_IS_UNICHAR #endif // _LOG4CXX_QT_TRANSCODER_H apache-log4cxx-1.3.1/src/main/include/log4cxx-qt/messagehandler.h0000644000175100001770000000266014721727031024203 0ustar runnerdocker/* * 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. */ #ifndef LOG4CXX_QT_MESSAGEHANDLER_H #define LOG4CXX_QT_MESSAGEHANDLER_H #include #include "log4cxx/log4cxx.h" namespace LOG4CXX_NS { namespace qt { /** * The messageHandler function is a log4cxx replacement of the standard * Qt message handler. * * Use this function as follows: * qInstallMessageHandler( log4cxx::qt::messageHandler ); * * Note that similar to Qt, upon receipt of a fatal message this calls * std::abort(). */ LOG4CXX_EXPORT void messageHandler(QtMsgType type, const QMessageLogContext& context, const QString& message); } /* namespace qt */ } /* namespace log4cxx */ #endif /* LOG4CXX_QT_MESSAGEHANDLER_H */ apache-log4cxx-1.3.1/src/main/include/log4cxx-qt/logger.h0000644000175100001770000000167714721727031022507 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_QT_LOGGER_H #define _LOG4CXX_QT_LOGGER_H #include #include #endif // _LOG4CXX_QT_LOGGER_H apache-log4cxx-1.3.1/src/main/include/log4cxx-qt/configuration.h0000644000175100001770000000314214721727031024064 0ustar runnerdocker/* * 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. */ #ifndef LOG4CXX_QT_CONFIGURATION_H #define LOG4CXX_QT_CONFIGURATION_H #include #include #include #include namespace LOG4CXX_NS { namespace qt { class LOG4CXX_EXPORT Configuration { private: Configuration(); static LOG4CXX_NS::spi::ConfigurationStatus tryLoadFile(const QString& filename); public: /** * Configure Log4cxx and watch the file for changes. See also DefaultConfigurator::configureFromFile. * * @param directories * @param filenames * @return */ static std::tuple configureFromFileAndWatch(const QVector& directories, const QVector& filenames); }; } /* namespace qt */ } /* namespace log4cxx */ #endif /* LOG4CXX_QT_CONFIGURATION_H */ apache-log4cxx-1.3.1/src/main/include/log4cxx-qt/messagebuffer.h0000644000175100001770000000460714721727031024042 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_QT_MESSAGE_BUFFER_H #define _LOG4CXX_QT_MESSAGE_BUFFER_H #include #if LOG4CXX_UNICHAR_API || LOG4CXX_LOGCHAR_IS_UNICHAR inline LOG4CXX_NS::helpers::UniCharMessageBuffer& operator<<(LOG4CXX_NS::helpers::UniCharMessageBuffer& mb, const QString& msg) { return mb << msg.utf16(); } #if LOG4CXX_WCHAR_T_API inline LOG4CXX_NS::helpers::WideMessageBuffer& operator<<(LOG4CXX_NS::helpers::WideMessageBuffer& mb, const QString& msg) { return mb << msg.toStdWString(); } inline LOG4CXX_NS::helpers::WideMessageBuffer& operator<<(LOG4CXX_NS::helpers::MessageBuffer& mb, const QString& msg) { return mb << msg.toStdWString(); } #else // !LOG4CXX_WCHAR_T_API inline LOG4CXX_NS::helpers::UniCharMessageBuffer& operator<<(LOG4CXX_NS::helpers::MessageBuffer& mb, const QString& msg) { return mb << msg.utf16(); } #endif // !LOG4CXX_WCHAR_T_API #else // !(LOG4CXX_UNICHAR_API || LOG4CXX_LOGCHAR_IS_UNICHAR) #if LOG4CXX_WCHAR_T_API inline LOG4CXX_NS::helpers::WideMessageBuffer& operator<<(LOG4CXX_NS::helpers::WideMessageBuffer& mb, const QString& msg) { return mb << msg.toStdWString(); } inline LOG4CXX_NS::helpers::WideMessageBuffer& operator<<(LOG4CXX_NS::helpers::MessageBuffer& mb, const QString& msg) { return mb << msg.toStdWString(); } #else // !LOG4CXX_WCHAR_T_API inline LOG4CXX_NS::helpers::CharMessageBuffer& operator<<(LOG4CXX_NS::helpers::CharMessageBuffer& mb, const QString& msg) { LOG4CXX_DECODE_QSTRING(tmp, msg); return mb << tmp; } #endif // !LOG4CXX_WCHAR_T_API #endif // !(LOG4CXX_UNICHAR_API || LOG4CXX_LOGCHAR_IS_UNICHAR) #endif // _LOG4CXX_QT_MESSAGE_BUFFER_H apache-log4cxx-1.3.1/src/main/include/CMakeLists.txt0000644000175100001770000001726114721727031021601 0ustar runnerdocker# # 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. # set(GENERATED_HEADERS) # Configure log4cxx.h set(LOG4CXX_CHAR "utf-8" CACHE STRING "Internal character representation, choice of utf-8, wchar_t, unichar") set_property(CACHE LOG4CXX_CHAR PROPERTY STRINGS "utf-8" "wchar_t" "unichar") if(${LOG4CXX_CHAR} STREQUAL "unichar") set(LOGCHAR_IS_UNICHAR 1) set(LOGCHAR_IS_WCHAR 0) set(LOGCHAR_IS_UTF8 0) elseif(${LOG4CXX_CHAR} STREQUAL "wchar_t") set(LOGCHAR_IS_WCHAR 1) set(LOGCHAR_IS_UNICHAR 0) set(LOGCHAR_IS_UTF8 0) else() set(LOGCHAR_IS_UNICHAR 0) set(LOGCHAR_IS_WCHAR 0) set(LOGCHAR_IS_UTF8 1) endif() option(LOG4CXX_WCHAR_T "Enable wchar_t API methods" ON) option(LOG4CXX_UNICHAR "Enable UniChar API methods" OFF) set(INIT_IOS_BASE 0) if(APPLE) option(LOG4CXX_CFSTRING "Enable CFString API methods, requires Mac OS/X CoreFoundation" OFF) set(INIT_IOS_BASE 1) endif() set(CHAR_API 1) foreach(varName WCHAR_T UNICHAR CFSTRING ) if(${LOG4CXX_${varName}}) set("${varName}_API" 1) else() set("${varName}_API" 0) endif() endforeach() option(LOG4CXX_NETWORKING_SUPPORT "Support logging over a network socket" ON) if(LOG4CXX_NETWORKING_SUPPORT) set(NETWORKING_SUPPORT 1) else() set(NETWORKING_SUPPORT 0) endif() option(LOG4CXX_DOMCONFIGURATOR_SUPPORT "Support XML as a configuration method" ON) if(LOG4CXX_DOMCONFIGURATOR_SUPPORT) set(DOMCONFIGURATOR_SUPPORT 1) else() set(DOMCONFIGURATOR_SUPPORT 0) endif() if(ENABLE_FMT_LAYOUT) set(FMT_LAYOUT_SUPPORT 1) else() set(FMT_LAYOUT_SUPPORT 0) endif() option(LOG4CXX_MULTIPROCESS_ROLLING_FILE_APPENDER "Support multiple processes logging to the same file" OFF) if(LOG4CXX_MULTIPROCESS_ROLLING_FILE_APPENDER) set(MULTIPROCESS_RFA 1) else() set(MULTIPROCESS_RFA 0) endif() option(LOG4CXX_EVENTS_AT_EXIT "Prevent static data cleanup to allow event logging during application exit. Note: Appenders should not configure the \"BufferedIO\" option to true." OFF) if(LOG4CXX_EVENTS_AT_EXIT ) set(EVENTS_AT_EXIT 1) else() set(EVENTS_AT_EXIT 0) endif() set(LOG4CXX_DECLARE_DEFAULT_NS_ALIAS 0) if(NOT "log4cxx" STREQUAL "${LOG4CXX_NS}") set(LOG4CXX_DECLARE_DEFAULT_NS_ALIAS 1) endif() set(LOG4CXX_FORMAT_NAMESPACE "fmt" CACHE STRING "format() function namespace, choice of fmt (default), std") set_property(CACHE LOG4CXX_FORMAT_NAMESPACE PROPERTY STRINGS "fmt" "std") set(LOG4CXX_USE_STANDARD_FORMAT 0) if("std" STREQUAL "${LOG4CXX_FORMAT_NAMESPACE}") set(LOG4CXX_USE_STANDARD_FORMAT 1) endif() # Configure log4cxx_private.h set(LOG4CXX_CHARSET "utf-8" CACHE STRING "LogString characters, choice of utf-8 (default), ISO-8859-1, US-ASCII, EBCDIC, locale") set_property(CACHE LOG4CXX_CHARSET PROPERTY STRINGS "utf-8" "ISO-8859-1" "US-ASCII" "EBCDIC" "locale") set(CHARSET_EBCDIC 0) set(CHARSET_USASCII 0) set(CHARSET_ISO88591 0) set(CHARSET_UTF8 0) if(${LOG4CXX_CHARSET} STREQUAL "EBCDIC") set(CHARSET_EBCDIC 1) elseif(${LOG4CXX_CHARSET} STREQUAL "US-ASCII") set(CHARSET_USASCII 1) elseif(${LOG4CXX_CHARSET} STREQUAL "ISO-8859-1") set(CHARSET_ISO88591 1) elseif(${LOG4CXX_CHARSET} STREQUAL "utf-8") set(CHARSET_UTF8 1) endif() # # Test for various functions # include(CheckFunctionExists) include(CheckCXXSymbolExists) include(CheckIncludeFileCXX) include(CheckLibraryExists) CHECK_INCLUDE_FILE_CXX(locale HAS_STD_LOCALE) CHECK_SYMBOL_EXISTS(mbsrtowcs "cwchar" HAS_MBSRTOWCS) CHECK_SYMBOL_EXISTS(wcstombs "cstdlib" HAS_WCSTOMBS) CHECK_SYMBOL_EXISTS(fwide "cwchar" HAS_FWIDE ) CHECK_SYMBOL_EXISTS(syslog "syslog.h" HAS_SYSLOG) if(NOT MSVC) set(CMAKE_REQUIRED_LIBRARIES "pthread") # pthread_sigmask exists on MINGW but with no function if(NOT MINGW) CHECK_SYMBOL_EXISTS(pthread_sigmask "signal.h" HAS_PTHREAD_SIGMASK) endif() CHECK_SYMBOL_EXISTS(pthread_self "pthread.h" HAS_PTHREAD_SELF) # Check for the (linux) pthread_setname_np. # OSX and BSD are special apparently. OSX only lets you name # the current thread, while BSD calls it pthread_set_name_np. # Since this is really not a core feature and the end-user can configure # it anyway, we're only going to worry about linux. include(${LOG4CXX_SOURCE_DIR}/src/cmake/pthread/log4cxx-pthread.cmake) if(${PTHREAD_SETNAME_NP_FOUND}) set(HAS_PTHREAD_SETNAME 1) endif() if(${PTHREAD_GETNAME_NP_FOUND}) set(HAS_PTHREAD_GETNAME 1) endif() endif() foreach(varName HAS_THREAD_LOCAL HAS_STD_LOCALE HAS_ODBC HAS_MBSRTOWCS HAS_WCSTOMBS HAS_FWIDE HAS_LIBESMTP HAS_SYSLOG HAS_PTHREAD_SELF HAS_PTHREAD_SIGMASK HAS_PTHREAD_SETNAME HAS_PTHREAD_GETNAME ) if(${varName} EQUAL 0) continue() elseif(${varName} EQUAL 1) continue() elseif(${varName} STREQUAL "ON" OR ${varName} STREQUAL "TRUE") set(${varName} 1 ) else() set(${varName} 0 ) endif() endforeach() # Configure both our private header and our public header configure_file(${LOG4CXX_SOURCE_DIR}/src/cmake/compiler-features/makeunique.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/log4cxx/helpers/makeunique.h ) list(APPEND GENERATED_HEADERS ${CMAKE_CURRENT_BINARY_DIR}/log4cxx/helpers/makeunique.h) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/log4cxx/private/log4cxx_private.h.in ${CMAKE_CURRENT_BINARY_DIR}/log4cxx/private/log4cxx_private.h @ONLY ) list(APPEND GENERATED_HEADERS ${CMAKE_CURRENT_BINARY_DIR}/log4cxx/private/log4cxx_private.h) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/log4cxx/log4cxx.h.in ${CMAKE_CURRENT_BINARY_DIR}/log4cxx/log4cxx.h @ONLY ) list(APPEND GENERATED_HEADERS ${CMAKE_CURRENT_BINARY_DIR}/log4cxx/log4cxx.h) configure_file(${LOG4CXX_SOURCE_DIR}/src/cmake/boost-fallback/boost-std-configuration.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/log4cxx/private/boost-std-configuration.h ) list(APPEND GENERATED_HEADERS ${CMAKE_CURRENT_BINARY_DIR}/log4cxx/private/boost-std-configuration.h) if(WIN32) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/log4cxx/version_info.h.in ${CMAKE_CURRENT_BINARY_DIR}/log4cxx/version_info.h @ONLY ) list(APPEND GENERATED_HEADERS ${CMAKE_CURRENT_BINARY_DIR}/log4cxx/version_info.h) endif() # A target for the convenience of working with headers in the IDE file(GENERATE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/empty-lib-stub.cpp CONTENT "namespace {int someUnused{};}\n" ) file(GLOB_RECURSE HEADERS log4cxx/*) if(NOT LOG4CXX_DOMCONFIGURATOR_SUPPORT) list(REMOVE_ITEM HEADERS "xml/domconfigurator.h") endif() add_library(log4cxx-include STATIC ${HEADERS} ${GENERATED_HEADERS} ${CMAKE_CURRENT_BINARY_DIR}/empty-lib-stub.cpp) target_include_directories(log4cxx-include PUBLIC . ${CMAKE_CURRENT_BINARY_DIR}) # And the same for Qt option(LOG4CXX_QT_SUPPORT "Qt support/integration" OFF) if(LOG4CXX_QT_SUPPORT) file(GLOB_RECURSE HEADERS_QT log4cxx-qt/*) add_library(log4cxx-qt-include STATIC ${HEADERS_QT} ${CMAKE_CURRENT_BINARY_DIR}/empty-lib-stub.cpp) target_include_directories(log4cxx-qt-include PUBLIC . ${CMAKE_CURRENT_BINARY_DIR}) add_dependencies(log4cxx-qt-include log4cxx-include) endif() apache-log4cxx-1.3.1/src/main/include/log4cxx/0000755000175100001770000000000014721727031020422 5ustar runnerdockerapache-log4cxx-1.3.1/src/main/include/log4cxx/file.h0000644000175100001770000001242114721727031021512 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_FILE_H #define _LOG4CXX_FILE_H #include #include extern "C" { struct apr_file_t; struct apr_finfo_t; } namespace LOG4CXX_NS { namespace helpers { class Transcoder; class Pool; } /** * An abstract representation of file and directory path names. */ class LOG4CXX_EXPORT File { public: /** * Construct a new instance. */ File(); /** * Construct a new instance. Use setPath to specify path using a LogString. * @param path file path in local encoding. */ File(const char* path); /** * Construct a new instance. Use setPath to specify path using a LogString. * @param path file path in current encoding. */ File(const std::string& path); #if LOG4CXX_WCHAR_T_API /** * Construct a new instance. Use setPath to specify path using a LogString. * @param path file path. */ File(const wchar_t* path); /** * Construct a new instance. Use setPath to specify path using a LogString. * @param path file path. */ File(const std::wstring& path); #endif #if LOG4CXX_UNICHAR_API || LOG4CXX_LOGCHAR_IS_UNICHAR /** * Construct a new instance. Use setPath to specify path using a LogString. * @param path file path. */ File(const UniChar* path); /** * Construct a new instance. Use setPath to specify path using a LogString. * @param path file path. */ File(const std::basic_string& path); #endif #if LOG4CXX_CFSTRING_API /** * Construct a new instance. Use setPath to specify path using a LogString. * @param path file path. */ File(const CFStringRef& path); #endif /** * Copy constructor. */ File(const File& src); /** * Assignment operator. */ File& operator=(const File& src); /** * Destructor. */ ~File(); /** * Determines if file exists. * @param p pool. * @return true if file exists. */ bool exists(LOG4CXX_NS::helpers::Pool& p) const; /** * Determines length of file. May not be accurate if file is current open. * @param p pool. * @return length of file. */ size_t length(LOG4CXX_NS::helpers::Pool& p) const; /** * Determines last modification date. * @param p pool. * @return length of file. */ log4cxx_time_t lastModified(LOG4CXX_NS::helpers::Pool& p) const; /** * Get final portion of file path. * @return file name. */ LogString getName() const; /** * Get file path. * @return file path. */ LogString getPath() const; /** * Set file path */ File& setPath(const LogString&); /** * Open file. See apr_file_open for details. * @param file APR file handle. * @param flags flags. * @param perm permissions. * @param p pool. * @return APR_SUCCESS if successful. */ log4cxx_status_t open(apr_file_t** file, int flags, int perm, LOG4CXX_NS::helpers::Pool& p) const; /** * List files if current file is a directory. * @param p pool. * @return list of files in this directory, operation of non-directory returns empty list. */ std::vector list(LOG4CXX_NS::helpers::Pool& p) const; /** * Delete file. * @param p pool. * @return true if file successfully deleted. */ bool deleteFile(LOG4CXX_NS::helpers::Pool& p) const; /** * Rename file. * @param dest new path for file. * @param p pool. * @return true if file successfully renamed. */ bool renameTo(const File& dest, LOG4CXX_NS::helpers::Pool& p) const; /** * Get path of parent directory. * @param p pool. * @return path of parent directory. */ LogString getParent(LOG4CXX_NS::helpers::Pool& p) const; /** * Make directories recursively. * @param p pool. * @return true if all requested directories existed or have been created. */ bool mkdirs(LOG4CXX_NS::helpers::Pool& p) const; /** * Set the file to be deleted when this object is destroyed. * @param autoDelete If true, delete file upon destruction. If true, do not delete file. */ void setAutoDelete(bool autoDelete); /** * Return the value of the autodelete setting. If true, this file will be deleted when the * destructor is called. * * @return True if the file is deleted upon destruction. */ bool getAutoDelete() const; private: LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(FilePrivate, m_priv) static char* convertBackSlashes(char*); char* getPath(LOG4CXX_NS::helpers::Pool& p) const; }; } // namespace log4cxx #define LOG4CXX_FILE(name) LOG4CXX_NS::File(name) #endif // _LOG4CXX_FILE_H apache-log4cxx-1.3.1/src/main/include/log4cxx/asyncappender.h0000644000175100001770000001462014721727031023432 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_ASYNC_APPENDER_H #define _LOG4CXX_ASYNC_APPENDER_H #include #include #include namespace LOG4CXX_NS { LOG4CXX_LIST_DEF(LoggingEventList, spi::LoggingEventPtr); /** The AsyncAppender decouples logging event creation from output by processing log events asynchronously. The AsyncAppender stores the logging event in a bounded buffer and then returns control to the application. A separate thread forwards events to the attached appender(s). You can attach multiple appenders to an AsyncAppender. The AsyncAppender is useful when outputting to a slow event sink, for example, a remote SMTP server or a database. Attaching a FileAppender to AsyncAppender is not recommended as the inter-thread communication overhead can exceed the time to write directly to a file. When the application produces logging events faster than the background thread is able to process, the bounded buffer can become full. In this situation AsyncAppender will either block until the bounded buffer has a free slot or discard the event. The Blocking property controls which behaviour is used. When events are discarded, the logged output will indicate this with a log message prefixed with Discarded. The output may contain one Discarded message per logger name, the logging event of the highest level for each logger whose events have been discarded. To determine whether the application produces logging events faster than the background thread is able to process, enable [Log4cxx internal debugging](internal-debugging.html). The AsyncAppender will output a histogram of queue length frequencies when closed. Important note: The AsyncAppender can only be script configured using the {@link xml::DOMConfigurator DOMConfigurator}. */ class LOG4CXX_EXPORT AsyncAppender : public virtual spi::AppenderAttachable, public virtual AppenderSkeleton { protected: struct AsyncAppenderPriv; public: DECLARE_LOG4CXX_OBJECT(AsyncAppender) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(AsyncAppender) LOG4CXX_CAST_ENTRY_CHAIN(AppenderSkeleton) LOG4CXX_CAST_ENTRY(spi::AppenderAttachable) END_LOG4CXX_CAST_MAP() /** * Create new instance. */ AsyncAppender(); /** * Destructor. */ virtual ~AsyncAppender(); /** * Add appender. * * @param newAppender appender to add, may not be null. */ void addAppender(const AppenderPtr newAppender) override; void doAppend(const spi::LoggingEventPtr& event, helpers::Pool& pool1) override; void append(const spi::LoggingEventPtr& event, helpers::Pool& p) override; /** Close this AsyncAppender by interrupting the dispatcher thread which will process all pending events before exiting. */ void close() override; /** * Get iterator over attached appenders. * @return list of all attached appenders. */ AppenderList getAllAppenders() const override; /** * Get appender by name. * * @param name name, may not be null. * @return matching appender or null. */ AppenderPtr getAppender(const LogString& name) const override; /** * Gets whether the location of the logging request call * should be captured. * * @return the current value of the LocationInfo option. */ bool getLocationInfo() const; /** * Determines if specified appender is attached. * @param appender appender. * @return true if attached. */ bool isAttached(const AppenderPtr appender) const override; bool requiresLayout() const override; /** * Removes and closes all attached appenders. */ void removeAllAppenders() override; /** * Removes an appender. * @param appender appender to remove. */ void removeAppender(const AppenderPtr appender) override; /** * Remove appender by name. * @param name name. */ void removeAppender(const LogString& name) override; /** * The LocationInfo attribute is provided for compatibility * with log4j and has no effect on the log output. * @param flag new value. */ void setLocationInfo(bool flag); /** * The BufferSize option takes a non-negative integer value. * This integer value determines the maximum size of the bounded * buffer. * */ void setBufferSize(int size); /** * Gets the current buffer size. * @return the current value of the BufferSize option. */ int getBufferSize() const; /** * Sets whether appender should wait if there is no * space available in the event buffer or immediately return. * * @param value true if appender should wait until available space in buffer. */ void setBlocking(bool value); /** * Gets whether appender should block calling thread when buffer is full. * If false, messages will be counted by logger and a summary * message appended after the contents of the buffer have been appended. * * @return true if calling thread will be blocked when buffer is full. */ bool getBlocking() const; /** \copybrief AppenderSkeleton::setOption() Supported options | Supported values | Default value -------------- | ---------------- | --------------- LocationInfo | True,False | False BufferSize | int | 128 Blocking | True,False | True \sa AppenderSkeleton::setOption() */ void setOption(const LogString& option, const LogString& value) override; private: AsyncAppender(const AsyncAppender&); AsyncAppender& operator=(const AsyncAppender&); /** * Dispatch routine. */ void dispatch(); }; // class AsyncAppender LOG4CXX_PTR_DEF(AsyncAppender); } // namespace log4cxx #endif// _LOG4CXX_ASYNC_APPENDER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/provisionnode.h0000644000175100001770000000217114721727031023472 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_PROVISION_NODE_H #define _LOG4CXX_PROVISION_NODE_H #include #include #include namespace LOG4CXX_NS { class Logger; typedef std::shared_ptr LoggerPtr; typedef std::vector ProvisionNode; } // namespace log4cxx #endif //_LOG4CXX_PROVISION_NODE_H apache-log4cxx-1.3.1/src/main/include/log4cxx/propertyconfigurator.h0000644000175100001770000003246714721727031025116 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_PROPERTY_CONFIGURATOR_H #define _LOG4CXX_PROPERTY_CONFIGURATOR_H #include #include #include #include #include namespace LOG4CXX_NS { class Logger; typedef std::shared_ptr LoggerPtr; class Appender; typedef std::shared_ptr AppenderPtr; namespace helpers { class Properties; } namespace spi { class LoggerFactory; typedef std::shared_ptr LoggerFactoryPtr; } class PropertyWatchdog; /** Allows the configuration of log4cxx from an external file. \anchor PropertyConfigurator_details The configuration file consists of statements in the format key=value. A line beginning with a # or ! character is ignored by %log4cxx (use for a comment). The syntax of different configuration elements are discussed below. The PropertyConfigurator does not handle the advanced configuration features supported by the {@link xml::DOMConfigurator DOMConfigurator} such as support for {@link spi::Filter Filters}, custom {@link spi::ErrorHandler ErrorHandlers}, nested appenders such as the {@link AsyncAppender AsyncAppender}, etc.

Appender configuration

Appender configuration syntax is:
# For appender named appenderName, set its class.
# Note: The appender name can contain dots.
log4j.appender.appenderName=fully.qualified.name.of.appender.class

# Set appender specific options.
log4j.appender.appenderName.option1=value1
...
log4j.appender.appenderName.optionN=valueN
For each named appender you can configure its {@link Layout Layout}. The syntax for configuring an appender's layout is:
log4j.appender.appenderName.layout=fully.qualified.name.of.layout.class
log4j.appender.appenderName.layout.option1=value1
....
log4j.appender.appenderName.layout.optionN=valueN
Refer to the Appender::setOption override of each implemented appender and Layout::setOption override of each implemented layout for class specific options.

Configuring loggers

The syntax for configuring the root logger is:
log4j.rootLogger=[level], appenderName, appenderName, ...
This syntax means that an optional level can be supplied followed by appender names separated by commas. The level value can consist of the string values OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL or a custom level value. A custom level value can be specified in the form level#classname. If a level value is specified, then the root level is set to the corresponding level. If no level value is specified, then the root level remains untouched. The root logger can be assigned multiple appenders. Each appenderName (separated by commas) will be added to the root logger. The named appender is defined using the appender syntax defined above. For non-root categories the syntax is almost the same:
log4j.logger.logger_name=[level|INHERITED|NULL], appenderName, appenderName,
...
The meaning of the optional level value is discussed above in relation to the root logger. In addition however, the value INHERITED can be specified meaning that the named logger should inherit its level from the logger hierarchy. If no level value is supplied, then the level of the named logger remains untouched. By default categories inherit their level from the hierarchy. However, if you set the level of a logger and later decide that that logger should inherit its level, then you should specify INHERITED as the value for the level value. NULL is a synonym for INHERITED. Similar to the root logger syntax, each appenderName (separated by commas) will be attached to the named logger. See the appender additivity rule in the usage guide for the meaning of the additivity flag.

Example

An example configuration is given below.
# Set options for appender named "A1".
# Appender "A1" will be a SyslogAppender
log4j.appender.A1=SyslogAppender

# The syslog daemon resides on www.abc.net
log4j.appender.A1.SyslogHost=www.abc.net

# A1's layout is a PatternLayout, using the conversion pattern
# "%r %-5p %c{2} %M.%L %x - %m%n". Thus, the log output will include
# the relative time since the start of the application in milliseconds, followed by
# the level of the log request, followed by
# the two rightmost components of the logger name, followed by
# the callers method name, followed by the line number,
# the nested disgnostic context and finally the message itself.
# Refer to the documentation of PatternLayout for further information
# on the syntax of the ConversionPattern key.
log4j.appender.A1.layout=PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r %-5p %%c{2} %%M.%%L %%x - %%m%%n

# Set options for appender named "A2"
# A2 should be a RollingFileAppender,
# with maximum file size of 10 MB using at most one backup file.
# A2's layout is: date and time (using the ISO8061 date format),
# thread, level, logger name, nested diagnostic context
# and finally the message itself.
log4j.appender.A2=RollingFileAppender
log4j.appender.A2.MaxFileSize=10MB
log4j.appender.A2.MaxBackupIndex=1
log4j.appender.A2.layout=PatternLayout
log4j.appender.A2.layout.ConversionPattern=%%d [%%t] %%p %%c %%x - %%m%%n

# Root logger set to DEBUG using the A2 appender defined above.
log4j.rootLogger=DEBUG, A2

# Logger definitions:
# The SECURITY logger inherits is level from root. However, it's output
# will go to A1 appender defined above. It's additivity is non-cumulative.
log4j.logger.SECURITY=INHERIT, A1
log4j.additivity.SECURITY=false

# Only warnings or above will be logged for the logger "SECURITY.access".
# Output will go to A1.
log4j.logger.SECURITY.access=WARN

# The logger "class.of.the.day" inherits its level from the
# logger hierarchy.  Output will go to the appender's of the root
# logger, A2 in this case.
log4j.logger.class.of.the.day=INHERIT

Dynamic option values

All option values admit variable substitution. The syntax of variable substitution is similar to that of Unix shells. The string between an opening "${" and closing "}" is interpreted as a key. The value of the substituted variable can be defined as a system property or in the configuration file itself. The value of the key is first searched in the system properties, and if not found there, it is then searched in the configuration file being parsed. The corresponding value replaces the ${variableName} sequence. For example, if home system property is set to /home/xyz, then every occurrence of the sequence ${home} will be interpreted as /home/xyz.

Repository-wide threshold

The repository-wide threshold filters logging requests by level regardless of logger. The syntax is:
log4j.threshold=[level]
The level value can consist of the string values OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL or a custom level value. A custom level value can be specified in the form level#classname. By default the repository-wide threshold is set to the lowest possible value, namely the level ALL.

Debugging

It is sometimes useful to see how %log4cxx is reading configuration files. You can enable %log4cxx internal logging by defining the log4j.debug variable in the property file.
# Enable internal logging
log4j.debug=true

Logger Factories

The usage of custom logger factories is discouraged and no longer documented. */ class LOG4CXX_EXPORT PropertyConfigurator : virtual public spi::Configurator, virtual public helpers::Object { protected: /** Used internally to keep track of configured appenders. */ std::map* registry; /** Used to create new instances of logger */ LOG4CXX_DECLARE_PRIVATE_MEMBER(spi::LoggerFactoryPtr, loggerFactory) public: DECLARE_LOG4CXX_OBJECT(PropertyConfigurator) BEGIN_LOG4CXX_CAST_MAP() #if 15 < LOG4CXX_ABI_VERSION LOG4CXX_CAST_ENTRY(PropertyConfigurator) LOG4CXX_CAST_ENTRY_CHAIN(spi::Configurator) #else LOG4CXX_CAST_ENTRY(spi::Configurator) #endif END_LOG4CXX_CAST_MAP() PropertyConfigurator(); virtual ~PropertyConfigurator(); /** Read configuration from \c configFileName. If \c repository is not provided, the spi::LoggerRepository held by LogManager is used. The existing configuration is not cleared nor reset. If you require a different behavior, call {@link spi::LoggerRepository::resetConfiguration resetConfiguration} before calling doConfigure. @param configFileName The file to parse. @param repository Where the Logger instances reside. */ spi::ConfigurationStatus doConfigure ( const File& configFileName #if LOG4CXX_ABI_VERSION <= 15 , spi::LoggerRepositoryPtr repository #else , const spi::LoggerRepositoryPtr& repository = spi::LoggerRepositoryPtr() #endif ) override; /** Read configuration options from file configFilename. Stores Logger instances in the spi::LoggerRepository held by LogManager. */ static spi::ConfigurationStatus configure(const File& configFilename); #if LOG4CXX_ABI_VERSION <= 15 /** Like {@link #configureAndWatch(const File& configFilename, long delay)} except that the default delay as defined by helpers::FileWatchdog#DEFAULT_DELAY is used. @param configFilename A file in key=value format. */ static spi::ConfigurationStatus configureAndWatch(const File& configFilename); #endif /** Read configuration options from \c configFilename (if it exists). Stores Logger instances in the spi::LoggerRepository held by LogManager. A thread will be created that periodically checks whether \c configFilename has been created or modified. A period of log4cxx::helpers::FileWatchdog#DEFAULT_DELAY is used if \c delay is not a positive number. If a change or file creation is detected, then \c configFilename is read to configure Log4cxx. The thread will be stopped by a LogManager::shutdown call. @param configFilename A file in key=value format. @param delay The delay in milliseconds to wait between each check. */ static spi::ConfigurationStatus configureAndWatch(const File& configFilename, long delay = 0); /** Read configuration options from properties. Stores Logger instances in the spi::LoggerRepository held by LogManager. See the \ref PropertyConfigurator_details "detailed description" for the expected format. */ static spi::ConfigurationStatus configure(helpers::Properties& properties); /** Read configuration options from properties. See the \ref PropertyConfigurator_details "detailed description" for the expected format. */ spi::ConfigurationStatus doConfigure(helpers::Properties& properties, spi::LoggerRepositoryPtr hierarchy); // -------------------------------------------------------------------------- // Internal stuff // -------------------------------------------------------------------------- protected: /** Check the provided Properties object for a LoggerFactory entry specified by *log4j.loggerFactory*. If such an entry exists, an attempt is made to create an instance using the default constructor. This instance is used for subsequent Logger creations within this configurator. @see #parseCatsAndRenderers */ void configureLoggerFactory(helpers::Properties& props); void configureRootLogger(helpers::Properties& props, spi::LoggerRepositoryPtr& hierarchy); /** Parse non-root elements, such non-root categories and renderers. */ void parseCatsAndRenderers(helpers::Properties& props, spi::LoggerRepositoryPtr& hierarchy); /** Parse the additivity option for a non-root logger. */ bool parseAdditivityForLogger(helpers::Properties& props, LoggerPtr& cat, const LogString& loggerName); /** This method must work for the root logger as well. */ void parseLogger( helpers::Properties& props, LoggerPtr& logger, const LogString& optionKey, const LogString& loggerName, const LogString& value, bool additivity); AppenderPtr parseAppender( helpers::Properties& props, const LogString& appenderName); void registryPut(const AppenderPtr& appender); AppenderPtr registryGet(const LogString& name); private: PropertyConfigurator(const PropertyConfigurator&); PropertyConfigurator& operator=(const PropertyConfigurator&); static PropertyWatchdog* pdog; }; // class PropertyConfigurator } // namespace log4cxx #endif //_LOG4CXX_PROPERTY_CONFIGURATOR_H apache-log4cxx-1.3.1/src/main/include/log4cxx/loggerinstance.h0000644000175100001770000000660614721727031023607 0ustar runnerdocker/* * 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. */ #ifndef LOG4CXX_LOGGER_INSTANCE_HDR_ #define LOG4CXX_LOGGER_INSTANCE_HDR_ #include #include namespace LOG4CXX_NS { /** * A smart pointer (implicity convertable to LoggerPtr) * that conditionally removes a Logger from the spi::LoggerRepository * at the end of the instance variable's lifetime. * If the configuration process loaded settings for the logger, * or the logger is referenced elsewhere, * the LoggerInstancePtr destructor will not remove it from the spi::LoggerRepository. * Use a LoggerInstancePtr to prevent unbounded growth * of data in the spi::LoggerRepository * when using runtime generated logger names. * A runtime generated logger name is a technique for marking logging messages * that allows control of the logger level at a class instance level (i.e. a per object logger). * A per object logger is useful when the object instance has a identifiable name * (e.g. when it is instantiated from configuration data). */ class LoggerInstancePtr { bool m_hadConfiguration; //!< Did the logger repository hold a \c m_logger before creation of this instance? LoggerPtr m_logger; public: // ...structors /// A null LoggerPtr LoggerInstancePtr() : m_hadConfiguration(false) {} /// A separately configurable logger named \c instanceName template LoggerInstancePtr(const StringType& instanceName) : m_hadConfiguration(LogManager::exists(instanceName)) , m_logger(LogManager::getLogger(instanceName)) { } /// Conditionally remove the logger from the the spi::LoggerRepository ~LoggerInstancePtr() { reset(); } const LoggerPtr& operator->() const noexcept { return m_logger; } explicit operator bool() const noexcept { return !!m_logger; } operator LoggerPtr&() noexcept { return m_logger; } operator const LoggerPtr&() const noexcept { return m_logger; } Logger* get() noexcept { return m_logger.get(); } const Logger* get() const noexcept { return m_logger.get(); } /// Conditionally remove the Logger from the spi::LoggerRepository void reset() { if (m_logger && !m_hadConfiguration) { auto name = m_logger->getName(); m_logger.reset(); // Decrease reference count LogManager::removeLogger(name); } else { m_hadConfiguration = false; m_logger.reset(); } } /// Change this to a logger named \c instanceName template void reset(const StringType& instanceName) { reset(); m_hadConfiguration = !!LogManager::exists(instanceName); m_logger = LogManager::getLogger(instanceName); } }; } // namespace LOG4CXX_NS #endif // LOG4CXX_LOGGER_INSTANCE_HDR_ apache-log4cxx-1.3.1/src/main/include/log4cxx/appenderskeleton.h0000644000175100001770000001201014721727031024130 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_APPENDER_SKELETON_H #define _LOG4CXX_APPENDER_SKELETON_H #include #include #include #include #include #include #include namespace LOG4CXX_NS { /** * Implementation base class for all appenders. * * This class provides the code for common functionality, such as * support for threshold filtering and support for general filters. * */ class LOG4CXX_EXPORT AppenderSkeleton : public virtual Appender, public virtual helpers::Object { protected: LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(AppenderSkeletonPrivate, m_priv) AppenderSkeleton(LOG4CXX_PRIVATE_PTR(AppenderSkeletonPrivate) priv); /** Subclasses of AppenderSkeleton should implement this method to perform actual logging. See also AppenderSkeleton::doAppend method. */ virtual void append(const spi::LoggingEventPtr& event, LOG4CXX_NS::helpers::Pool& p) = 0; void doAppendImpl(const spi::LoggingEventPtr& event, LOG4CXX_NS::helpers::Pool& pool); public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(AppenderSkeleton) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(AppenderSkeleton) LOG4CXX_CAST_ENTRY(Appender) LOG4CXX_CAST_ENTRY(spi::OptionHandler) END_LOG4CXX_CAST_MAP() AppenderSkeleton(); AppenderSkeleton(const LayoutPtr& layout); virtual ~AppenderSkeleton(); /** Finalize this appender by calling the derived class' close method. */ void finalize(); /** \copybrief spi::OptionHandler::activateOptions() No action is performed in this implementation. */ void activateOptions(helpers::Pool& /* pool */) override {} /** \copybrief spi::OptionHandler::setOption() Supported options | Supported values | Default value -------------- | ---------------- | --------------- Threshold | Trace,Debug,Info,Warn,Error,Fatal,Off,All | All */ void setOption(const LogString& option, const LogString& value) override; /** Add a filter to end of the filter list. */ void addFilter(const spi::FilterPtr newFilter) override; public: /** Clear the filters chain. */ void clearFilters() override; /** Return the currently set spi::ErrorHandler for this Appender. */ const spi::ErrorHandlerPtr getErrorHandler() const; /** Returns the head Filter. */ spi::FilterPtr getFilter() const override; /** Return the first filter in the filter chain for this Appender. The return value may be nullptr if no is filter is set. */ const spi::FilterPtr getFirstFilter() const; /** Returns the layout of this appender. The value may be nullptr. */ LayoutPtr getLayout() const override; /** Returns the name of this Appender. */ LogString getName() const override; /** Returns this appenders threshold level. See the #setThreshold method for the meaning of this option. */ const LevelPtr getThreshold() const; /** Check whether the message level is below the appender's threshold. If there is no threshold set, then the return value is always true. */ bool isAsSevereAsThreshold(const LevelPtr& level) const; /** * This method performs threshold checks and invokes filters before * delegating actual logging to the subclasses specific * AppenderSkeleton#append method. * */ void doAppend(const spi::LoggingEventPtr& event, helpers::Pool& pool) override; /** Set the {@link spi::ErrorHandler ErrorHandler} for this Appender. */ void setErrorHandler(const spi::ErrorHandlerPtr eh); /** Set the layout for this appender. Note that some appenders have their own (fixed) layouts or do not use one. */ void setLayout(const LayoutPtr layout1) override; /** Set the name of this Appender. */ void setName(const LogString& name1) override; /** Set the threshold level. All log events with lower level than the threshold level are ignored by the appender.

In configuration files this option is specified by setting the value of the Threshold option to a level string, such as "DEBUG", "INFO" and so on. */ void setThreshold(const LevelPtr& threshold); }; // class AppenderSkeleton } // namespace log4cxx #endif //_LOG4CXX_APPENDER_SKELETON_H apache-log4cxx-1.3.1/src/main/include/log4cxx/basicconfigurator.h0000644000175100001770000000425714721727031024307 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_BASIC_CONFIGURATOR_H #define _LOG4CXX_BASIC_CONFIGURATOR_H #include #include #include #include namespace LOG4CXX_NS { class Appender; typedef std::shared_ptr AppenderPtr; /** Use BasicConfigurator (static) methods to configure Log4cxx when not using a configuration file. For key=value format configuration see PropertyConfigurator. For XML format configuration see xml::DOMConfigurator. */ class LOG4CXX_EXPORT BasicConfigurator { protected: BasicConfigurator() {} public: /** Add a ConsoleAppender to the root logger that formats output using \c layout. If \c layout is not provided, use a PatternLayout with %%r [%%t] %%p %%c %%x - %%m%%n as the conversion pattern. */ static void configure(const LayoutPtr& layout = LayoutPtr()); /** Add appender to the root logger. @param appender The appender to add to the root logger. */ static void configure(const AppenderPtr& appender); /** Reset the default hierarchy to its defaut. It is equivalent to calling Logger::getDefaultHierarchy()->resetConfiguration(). See Hierarchy#resetConfiguration() for more details. */ static void resetConfiguration(); }; // class BasicConfigurator } // namespace log4cxx #endif //_LOG4CXX_BASIC_CONFIGURATOR_H apache-log4cxx-1.3.1/src/main/include/log4cxx/appender.h0000644000175100001770000000740614721727031022400 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_APPENDER_H #define _LOG4CXX_APPENDER_H #include #include #include namespace LOG4CXX_NS { // Forward declarations namespace spi { class LoggingEvent; typedef std::shared_ptr LoggingEventPtr; class Filter; typedef std::shared_ptr FilterPtr; class ErrorHandler; typedef std::shared_ptr ErrorHandlerPtr; } class Layout; typedef std::shared_ptr LayoutPtr; /** Implement this interface for your own strategies for outputting log statements. */ class LOG4CXX_EXPORT Appender : public virtual spi::OptionHandler { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(Appender) virtual ~Appender() {} /** Add a filter to the end of the filter list. */ virtual void addFilter(const spi::FilterPtr newFilter) = 0; /** Returns the head Filter. The Filters are organized in a linked list and so all Filters on this Appender are available through the result. @return the head Filter or null, if no Filters are present */ virtual spi::FilterPtr getFilter() const = 0; /** Clear the list of filters by removing all the filters in it. */ virtual void clearFilters() = 0; /** Release any resources allocated within the appender such as file handles, network connections, etc.

It is a programming error to append to a closed appender. */ virtual void close() = 0; /** Log in Appender specific way. When appropriate, Loggers will call the doAppend method of appender implementations in order to log. */ virtual void doAppend(const spi::LoggingEventPtr& event, LOG4CXX_NS::helpers::Pool& pool) = 0; /** Get the name of this appender. The name uniquely identifies the appender. */ virtual LogString getName() const = 0; /** Set the Layout for this appender. */ virtual void setLayout(const LayoutPtr layout) = 0; /** Returns this appenders layout. */ virtual LayoutPtr getLayout() const = 0; /** Set the name of this appender. The name is used by other components to identify this appender. */ virtual void setName(const LogString& name) = 0; /** Configurators call this method to determine if the appender requires a layout. If this method returns true, meaning that layout is required, then the configurator will configure an layout using the configuration information at its disposal. If this method returns false, meaning that a layout is not required, then layout configuration will be skipped even if there is available layout configuration information at the disposal of the configurator..

In the rather exceptional case, where the appender implementation admits a layout but can also work without it, then the appender should return true. */ virtual bool requiresLayout() const = 0; }; LOG4CXX_PTR_DEF(Appender); LOG4CXX_LIST_DEF(AppenderList, AppenderPtr); } #endif //_LOG4CXX_APPENDER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/log4cxx.h.in0000644000175100001770000001144114721727031022571 0ustar runnerdocker/* 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. */ #ifndef LOG4CXX_LOG4CXX_H #define LOG4CXX_LOG4CXX_H /* GENERATED FILE WARNING! DO NOT EDIT log4cxx.h * * Edit log4cxx.h.in instead * */ #define LOG4CXX_ABI_VERSION @log4cxx_ABI_VER@ #define LOG4CXX_VERSION_MAJOR @log4cxx_VERSION_MAJOR@ #define LOG4CXX_VERSION_MINOR @log4cxx_VERSION_MINOR@ #define LOG4CXX_VERSION_PATCH @log4cxx_VERSION_PATCH@ #define LOG4CXX_VERSION_TWEAK @log4cxx_VERSION_TWEAK@ #define LOG4CXX_MAKE_VERSION(major, minor, patch, tweak) (((major) << 24) |\ ((minor) << 16) |\ ((patch) << 8) |\ (tweak) ) #define LOG4CXX_VERSION_GET_MAJOR(version) (((version) >> 24) & 0xFF) #define LOG4CXX_VERSION_GET_MINOR(version) (((version) >> 16) & 0xFF) #define LOG4CXX_VERSION_GET_PATCH(version) (((version) >> 8) & 0xFF) #define LOG4CXX_VERSION_GET_TWEAK(version) ((version) & 0xFF) #define LOG4CXX_VERSION \ LOG4CXX_MAKE_VERSION(LOG4CXX_VERSION_MAJOR, LOG4CXX_VERSION_MINOR, LOG4CXX_VERSION_PATCH, LOG4CXX_VERSION_TWEAK) #define LOG4CXX_LOGCHAR_IS_UNICHAR @LOGCHAR_IS_UNICHAR@ #define LOG4CXX_LOGCHAR_IS_UTF8 @LOGCHAR_IS_UTF8@ #define LOG4CXX_LOGCHAR_IS_WCHAR @LOGCHAR_IS_WCHAR@ #define LOG4CXX_CHAR_API @CHAR_API@ #define LOG4CXX_WCHAR_T_API @WCHAR_T_API@ #define LOG4CXX_UNICHAR_API @UNICHAR_API@ #define LOG4CXX_CFSTRING_API @CFSTRING_API@ #define LOG4CXX_HAS_NETWORKING @NETWORKING_SUPPORT@ #define LOG4CXX_HAS_MULTIPROCESS_ROLLING_FILE_APPENDER @MULTIPROCESS_RFA@ #define LOG4CXX_EVENTS_AT_EXIT @EVENTS_AT_EXIT@ #define LOG4CXX_HAS_DOMCONFIGURATOR @DOMCONFIGURATOR_SUPPORT@ #define LOG4CXX_HAS_FMT_LAYOUT @FMT_LAYOUT_SUPPORT@ #define LOG4CXX_USE_GLOBAL_SCOPE_TEMPLATE 0 #define LOG4CXX_LOGSTREAM_ADD_NOP 0 #include #include #define LOG4CXX_PTR_DEF(T) typedef std::shared_ptr T##Ptr;\ typedef std::weak_ptr T##WeakPtr #define LOG4CXX_UNIQUE_PTR_DEF(T) typedef std::unique_ptr T##UniquePtr; #define LOG4CXX_LIST_DEF(N, T) typedef std::vector N #define LOG4CXX_PRIVATE_PTR(T) std::unique_ptr #if defined(_MSC_VER) #define LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(T, V) \ __pragma( warning( push ) ) \ __pragma( warning( disable : 4251 ) ) \ struct T; LOG4CXX_PRIVATE_PTR(T) V; \ __pragma( warning( pop ) ) #define LOG4CXX_DECLARE_PRIVATE_MEMBER(T, V) \ __pragma( warning( push ) ) \ __pragma( warning( disable : 4251 ) ) \ T V; \ __pragma( warning( pop ) ) #define LOG4CXX_INSTANTIATE_EXPORTED_PTR(T) template class LOG4CXX_EXPORT std::shared_ptr #else // !defined(_MSC_VER) #define LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(T, V) struct T; LOG4CXX_PRIVATE_PTR(T) V; #define LOG4CXX_DECLARE_PRIVATE_MEMBER(T, V) T V; #define LOG4CXX_INSTANTIATE_EXPORTED_PTR(T) #endif // defined(_MSC_VER) #if defined(_WIN32) && defined(_MSC_VER) #if defined(LOG4CXX_STATIC) // Linking a static library? #define LOG4CXX_EXPORT #elif defined(LOG4CXX) // Building a DLL? #define LOG4CXX_EXPORT __declspec(dllexport) #else // Linking against a DLL? #define LOG4CXX_EXPORT __declspec(dllimport) #endif // !LOG4CXX_STATIC #elif defined(__GNUC__) && 4 <= __GNUC__ && 15 < LOG4CXX_ABI_VERSION #define LOG4CXX_EXPORT __attribute__ ((visibility ("default"))) #else // !(defined(_WIN32) && defined(_MSC_VER)) || LOG4CXX_ABI_VERSION <= 15 || __GNUC__ < 4 #define LOG4CXX_EXPORT #endif #define LOG4CXX_NS @LOG4CXX_NS@ namespace LOG4CXX_NS { /** * log4cxx_time_t - holds the number of microseconds since 1970-01-01 */ typedef int64_t log4cxx_time_t; typedef int log4cxx_status_t; /** * Query the compiled version of the library. Ideally, this should * be the same as the LOG4CXX_VERSION macro defined above. * * The LOG4CXX_VERSION_GET_ series of macros let you extract the * specific bytes of the version if required. */ LOG4CXX_EXPORT uint32_t libraryVersion(); } #if @LOG4CXX_DECLARE_DEFAULT_NS_ALIAS@ namespace log4cxx = LOG4CXX_NS; #endif #define LOG4CXX_USING_STD_FORMAT @LOG4CXX_USE_STANDARD_FORMAT@ #if !defined(LOG4CXX_FORMAT_NS) && LOG4CXX_USING_STD_FORMAT #define LOG4CXX_FORMAT_NS std #elif !defined(LOG4CXX_FORMAT_NS) #define LOG4CXX_FORMAT_NS fmt #endif #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/net/0000755000175100001770000000000014721727031021210 5ustar runnerdockerapache-log4cxx-1.3.1/src/main/include/log4cxx/net/smtpappender.h0000644000175100001770000002220714721727031024066 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_NET_SMTP_H #define _LOG4CXX_NET_SMTP_H #include #include #include namespace LOG4CXX_NS { namespace net { /** Send an e-mail when a specific logging event occurs, typically when an ERROR level logging event is sent to the appender. A value must be provided for the following param elements : - smtpHost - The URL or IP address of the SMTP server. - from - The email address in the from field of the message. - one of to, cc, bcc - An email address in the message. The following param elements are optional: - smtpPort - The TCP/IP port number on the SMTP server. By default port 25 is assumed. - subject - Content for the the subject field of the message. - smtpUsername - Provided when the SMTP server requests authentication. - smtpPassword - Provided when the SMTP server requests authentication. - BufferSize - The number of logging events delivered in an e-mail. The SMTPAppender keeps only the last BufferSize logging events in its cyclic buffer. This keeps memory requirements at a reasonable level while still delivering useful application context. By default 512 logging events are kept in its cyclic buffer. - evaluatorClass - The registered spi::TriggeringEventEvaluator sub-class that provides the isTriggeringEvent implementation. This attribute can also be set using the triggeringPolicy element. By default an email is sent when the level of the logging event is greater or equal to ERROR. An example configuration is: \include async-example.xml */ class LOG4CXX_EXPORT SMTPAppender : public AppenderSkeleton { private: struct SMTPPriv; SMTPAppender(const SMTPAppender&); SMTPAppender& operator=(const SMTPAppender&); static bool asciiCheck(const LogString& value, const LogString& label); /** This method determines if there is a sense in attempting to append.

It checks whether there is a set output target and also if there is a set layout. If these checks fail, then the boolean value false is returned. */ bool checkEntryConditions(); public: DECLARE_LOG4CXX_OBJECT(SMTPAppender) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(SMTPAppender) LOG4CXX_CAST_ENTRY_CHAIN(AppenderSkeleton) END_LOG4CXX_CAST_MAP() SMTPAppender(); /** The default constructor will instantiate the appender with a spi::TriggeringEventEvaluator that will trigger on events with level ERROR or higher.*/ SMTPAppender(LOG4CXX_NS::helpers::Pool& p); /** Use evaluator passed as parameter as the spi::TriggeringEventEvaluator for this net::SMTPAppender. */ SMTPAppender(spi::TriggeringEventEvaluatorPtr evaluator); ~SMTPAppender(); /** \copybrief AppenderSkeleton::setOption() Supported options | Supported values | Default value -------------- | ---------------- | --------------- smtpHost | {any} | - smtpPort | {int} | 25 smtpUserName | {any} | - smtpPassword | {any} | - from | (\ref asciiCheck "1") | - to | (\ref asciiCheck "1") | - cc | (\ref asciiCheck "1") | - bcc | (\ref asciiCheck "1") | - subject | {any} | - subject | {any} | - buffersize | {int} | 512 evaluatorClass | (\ref AppenderSkeleton "2") | - \anchor asciiCheck (1) Only ASCII charaters \anchor TriggeringEventEvaluator (2) A registered class deriving from TriggeringEventEvaluator \sa AppenderSkeleton::setOption() */ void setOption(const LogString& option, const LogString& value) override; /** \copybrief AppenderSkeleton::activateOptions() Will not activate and will log an error message if:

  • no layout is provided
  • no TriggeringEventEvaluator is provided
  • any required field is missing
  • a non-ascii character is detected where not permitted
. */ void activateOptions(helpers::Pool& p) override; /** Perform SMTPAppender specific appending actions, mainly adding the event to a cyclic buffer and checking if the event triggers an e-mail to be sent. */ void append(const spi::LoggingEventPtr& event, helpers::Pool& p) override; void close() override; /** Returns value of the To option. */ LogString getTo() const; /** Returns value of the cc option. */ LogString getCc() const; /** Returns value of the bcc option. */ LogString getBcc() const; /** The SMTPAppender requires a Layout. */ bool requiresLayout() const override; /** Send the contents of the cyclic buffer as an e-mail message. */ void sendBuffer(LOG4CXX_NS::helpers::Pool& p); /** Returns value of the EvaluatorClass option. */ LogString getEvaluatorClass(); /** Returns value of the From option. */ LogString getFrom() const; /** Returns value of the Subject option. */ LogString getSubject() const; /** The From option takes a string value which should be a e-mail address of the sender. */ void setFrom(const LogString& from); /** The Subject option takes a string value which should be a the subject of the e-mail message. */ void setSubject(const LogString& subject); /** The BufferSize option takes a positive integer representing the maximum number of logging events to collect in a cyclic buffer. When the BufferSize is reached, oldest events are deleted as new events are added to the buffer. By default the size of the cyclic buffer is 512 events. */ void setBufferSize(int bufferSize); /** The SMTPHost option takes a string value which should be a the host name of the SMTP server that will send the e-mail message. */ void setSMTPHost(const LogString& smtpHost); /** Returns value of the SMTPHost option. */ LogString getSMTPHost() const; /** The SMTPPort option takes a string value which should be a the port of the SMTP server that will send the e-mail message. */ void setSMTPPort(int port); /** Returns value of the SMTPHost option. */ int getSMTPPort() const; /** The To option takes a string value which should be a comma separated list of e-mail address of the recipients. */ void setTo(const LogString& to); /** The Cc option takes a string value which should be a comma separated list of e-mail address of the cc'd recipients. */ void setCc(const LogString& to); /** The Bcc option takes a string value which should be a comma separated list of e-mail address of the bcc'd recipients. */ void setBcc(const LogString& to); /** The SMTPUsername option takes a string value which should be a the user name for the SMTP server. */ void setSMTPUsername(const LogString& newVal); /** Returns value of the SMTPUsername option. */ LogString getSMTPUsername() const; /** The SMTPPassword option takes a string value which should be a the password for the SMTP server. */ void setSMTPPassword(const LogString& newVal); /** Returns value of the SMTPPassword option. */ LogString getSMTPPassword() const; /** Returns value of the BufferSize option. */ int getBufferSize() const; /** * Gets the current triggering evaluator. * @return triggering evaluator. */ LOG4CXX_NS::spi::TriggeringEventEvaluatorPtr getEvaluator() const; /** * Sets the triggering evaluator. * @param trigger triggering evaluator. */ void setEvaluator(LOG4CXX_NS::spi::TriggeringEventEvaluatorPtr& trigger); /** The EvaluatorClass option takes a string value representing the name of the class implementing the spi::TriggeringEventEvaluator interface. A corresponding object will be instantiated and assigned as the triggering event evaluator for the SMTPAppender. */ void setEvaluatorClass(const LogString& value); /** The LocationInfo option is provided for compatibility with log4j and has no effect in log4cxx. */ void setLocationInfo(bool locationInfo); /** Returns value of the LocationInfo option. */ bool getLocationInfo() const; }; // class SMTPAppender LOG4CXX_PTR_DEF(SMTPAppender); } // namespace net } // namespace log4cxx #endif // _LOG4CXX_NET_SMTP_H apache-log4cxx-1.3.1/src/main/include/log4cxx/net/syslogappender.h0000644000175100001770000001230314721727031024417 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_NET_SYSLOG_APPENDER_H #define _LOG4CXX_NET_SYSLOG_APPENDER_H #include #include namespace LOG4CXX_NS { namespace net { /** * Use SyslogAppender to send log messages to a remote syslog daemon. * * Note that by default, this appender will split up messages that are * more than 1024 bytes long, for compatability with BSD syslog(see * RFC 3164). Modern syslog implementations(e.g. syslog-ng) can accept * messages much larger, and may have a default of 8k. You may modify * the default size of the messages by setting the MaxMessageLength option. * * When the message is too large for the current MaxMessageLength, * the packet number and total # will be appended to the end of the * message like this: (5/10) */ class LOG4CXX_EXPORT SyslogAppender : public AppenderSkeleton { public: DECLARE_LOG4CXX_OBJECT(SyslogAppender) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(SyslogAppender) LOG4CXX_CAST_ENTRY_CHAIN(AppenderSkeleton) END_LOG4CXX_CAST_MAP() SyslogAppender(); SyslogAppender(const LayoutPtr& layout, int syslogFacility); SyslogAppender(const LayoutPtr& layout, const LogString& syslogHost, int syslogFacility); ~SyslogAppender(); /** Release any resources held by this SyslogAppender.*/ void close() override; /** Returns the specified syslog facility as a lower-case String, e.g. "kern", "user", etc. */ static LogString getFacilityString(int syslogFacility); /** Returns the integer value corresponding to the named syslog facility, or -1 if it couldn't be recognized. @param facilityName one of the strings KERN, USER, MAIL, DAEMON, AUTH, SYSLOG, LPR, NEWS, UUCP, CRON, AUTHPRIV, FTP, LOCAL0, LOCAL1, LOCAL2, LOCAL3, LOCAL4, LOCAL5, LOCAL6, LOCAL7. The matching is case-insensitive. */ static int getFacility(const LogString& facilityName); void append(const spi::LoggingEventPtr& event, helpers::Pool& p) override; /** \copybrief AppenderSkeleton::activateOptions() No action is performed in this implementation. */ void activateOptions(helpers::Pool& p) override; /** \copybrief AppenderSkeleton::setOption() Supported options | Supported values | Default value -------------- | ---------------- | --------------- SysLogHost | (\ref sysLogAddress "1") | - Facility | (\ref facility "2") | - MaxMessageLength | {int} | 1024 \anchor sysLogAddress (1) A valid internet address, optionally with the port number as a suffix after a ':'. \anchor facility (2) One of kern,user,mail,daemon,auth,syslog,lpr,news,uucp,cron,ftp,local0,local1,local2,local3,local4,local5,local6,local7 \sa AppenderSkeleton::setOption() */ void setOption(const LogString& option, const LogString& value) override; /** The SyslogAppender requires a layout. Hence, this method returns true. */ bool requiresLayout() const override { return true; } /** The SyslogHost option is the name of the the syslog host where log output should go. WARNING If the SyslogHost is not set, then this appender will fail. */ void setSyslogHost(const LogString& syslogHost); /** Returns the value of the SyslogHost option. */ const LogString& getSyslogHost() const; /** Set the syslog facility. This is the Facility option.

The facilityName parameter must be one of the strings KERN, USER, MAIL, DAEMON, AUTH, SYSLOG, LPR, NEWS, UUCP, CRON, AUTHPRIV, FTP, LOCAL0, LOCAL1, LOCAL2, LOCAL3, LOCAL4, LOCAL5, LOCAL6, LOCAL7. Case is unimportant. */ void setFacility(const LogString& facilityName); /** Returns the value of the Facility option. */ LogString getFacility() const; /** If the FacilityPrinting option is set to true, the printed message will include the facility name of the application. It is false by default. */ void setFacilityPrinting(bool facilityPrinting1); /** Returns the value of the FacilityPrinting option. */ bool getFacilityPrinting() const; void setMaxMessageLength(int maxMessageLength1); int getMaxMessageLength() const; protected: void initSyslogFacilityStr(); private: struct SyslogAppenderPriv; SyslogAppender(const SyslogAppender&); SyslogAppender& operator=(const SyslogAppender&); }; // class SyslogAppender LOG4CXX_PTR_DEF(SyslogAppender); } // namespace net } // namespace log4cxx #endif // _LOG4CXX_NET_SYSLOG_APPENDER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/net/socketappenderskeleton.h0000644000175100001770000001173414721727031026143 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_NET_SOCKET_APPENDER_SKELETON_H #define _LOG4CXX_NET_SOCKET_APPENDER_SKELETON_H #include #include #include #include namespace LOG4CXX_NS { namespace net { /** * Abstract base class for SocketAppender and XMLSocketAppender */ class LOG4CXX_EXPORT SocketAppenderSkeleton : public AppenderSkeleton { protected: struct SocketAppenderSkeletonPriv; public: SocketAppenderSkeleton(int defaultPort, int reconnectionDelay); ~SocketAppenderSkeleton(); /** Connects to remote server at address and port. */ SocketAppenderSkeleton(helpers::InetAddressPtr address, int port, int reconnectionDelay); /** Connects to remote server at host and port. */ SocketAppenderSkeleton(const LogString& host, int port, int reconnectionDelay); /** \copybrief AppenderSkeleton::activateOptions() Connects to the specified RemoteHost and Port. */ void activateOptions(helpers::Pool& p) override; void close() override; /** * This appender does not use a layout. Hence, this method * returns false. * */ bool requiresLayout() const override { return false; } /** * The RemoteHost option takes a string value which should be * the host name of the server where a * Apache Chainsaw or compatible is running. * */ void setRemoteHost(const LogString& host); /** Returns value of the RemoteHost option. */ const LogString& getRemoteHost() const; /** The Port option takes a positive integer representing the port where the server is waiting for connections. */ void setPort(int port1); /** Returns value of the Port option. */ int getPort() const; /** 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. */ void setLocationInfo(bool locationInfo1); /** Returns value of the LocationInfo option. */ bool getLocationInfo() const; /** 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. */ void setReconnectionDelay(int reconnectionDelay1); /** Returns value of the ReconnectionDelay option. */ int getReconnectionDelay() const; void fireConnector(); /** \copybrief AppenderSkeleton::setOption() Supported options | Supported values | Default value -------------- | ---------------- | --------------- RemoteHost | (\ref inetAddress "1") | - Port | {int} | (\ref defaultPort "2") LocationInfo | True,False | False \anchor inetAddress (1) A valid internet address. \anchor defaultPort (2) Provided by the derived class. \sa AppenderSkeleton::setOption() */ void setOption(const LogString& option, const LogString& value) override; protected: SocketAppenderSkeleton(std::unique_ptr priv); virtual void setSocket(LOG4CXX_NS::helpers::SocketPtr& socket, LOG4CXX_NS::helpers::Pool& p) = 0; virtual void cleanUp(LOG4CXX_NS::helpers::Pool& p) = 0; virtual int getDefaultDelay() const = 0; virtual int getDefaultPort() const = 0; private: void connect(LOG4CXX_NS::helpers::Pool& p); /** 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 previously open connection is droppped. */ void monitor(); bool is_closed(); SocketAppenderSkeleton(const SocketAppenderSkeleton&); SocketAppenderSkeleton& operator=(const SocketAppenderSkeleton&); }; // class SocketAppenderSkeleton } // namespace net } // namespace log4cxx #endif // _LOG4CXX_NET_SOCKET_APPENDER_SKELETON_H apache-log4cxx-1.3.1/src/main/include/log4cxx/net/telnetappender.h0000644000175100001770000000756314721727031024406 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_NET_TELNET_APPENDER_H #define _LOG4CXX_NET_TELNET_APPENDER_H #include #include namespace LOG4CXX_NS { namespace helpers { class ByteBuffer; } namespace net { /** The TelnetAppender writes log messages to clients that connect to the TCP port. This allows logging output to be monitored using TCP/IP. To receive log data, use telnet to connect to the configured port number. TelnetAppender is most useful as a secondary appender, especially when monitoring a servlet remotely. If no layout is provided, the log message only is sent to attached client(s). See TelnetAppender::setOption() for the available options. */ class LOG4CXX_EXPORT TelnetAppender : public AppenderSkeleton { private: static const int DEFAULT_PORT; static const int MAX_CONNECTIONS; public: DECLARE_LOG4CXX_OBJECT(TelnetAppender) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(TelnetAppender) LOG4CXX_CAST_ENTRY_CHAIN(AppenderSkeleton) END_LOG4CXX_CAST_MAP() TelnetAppender(); ~TelnetAppender(); /** If no layout is provided, sends only the log message to attached client(s). */ bool requiresLayout() const override; /** The current encoding value. \sa setOption */ LogString getEncoding() const; /** Set the encoding to \c value. \sa setOption */ void setEncoding(const LogString& value); /** \copybrief AppenderSkeleton::activateOptions() Create the socket handler and wait for connections. */ void activateOptions(helpers::Pool& p) override; /** \copybrief AppenderSkeleton::setOption() Supported options | Supported values | Default value -------------- | ---------------- | --------------- Port | {int} | 23 MaxConnections | {int} | 20 Encoding | C,UTF-8,UTF-16,UTF-16BE,UTF-16LE,646,US-ASCII,ISO646-US,ANSI_X3.4-1968,ISO-8859-1,ISO-LATIN-1 | UTF-8 \sa AppenderSkeleton::setOption() */ void setOption(const LogString& option, const LogString& value) override; /** The TCP Port number on which to accept connections. */ int getPort() const; /** Use \c newValue as the TCP port number on which to accept connections. */ void setPort(int newValue); /** The number of allowed concurrent connections. \sa setOption */ int getMaxConnections() const; /** Set the number of allowed concurrent connections to \c newValue. \sa setOption */ void setMaxConnections(int newValue); /** Shutdown this appender. */ void close() override; protected: /** Send \c event to each connected client. */ void append(const spi::LoggingEventPtr& event, helpers::Pool& p) override; private: // prevent copy and assignment statements TelnetAppender(const TelnetAppender&); TelnetAppender& operator=(const TelnetAppender&); void write(helpers::ByteBuffer&); void writeStatus(const helpers::SocketPtr& socket, const LogString& msg, helpers::Pool& p); void acceptConnections(); struct TelnetAppenderPriv; }; // class TelnetAppender LOG4CXX_PTR_DEF(TelnetAppender); } // namespace net } // namespace log4cxx #endif // _LOG4CXX_NET_TELNET_APPENDER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/net/xmlsocketappender.h0000644000175100001770000001253614721727031025120 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_NET_XML_SOCKET_APPENDER_H #define _LOG4CXX_NET_XML_SOCKET_APPENDER_H #include #include namespace LOG4CXX_NS { namespace net { /** Sends spi::LoggingEvent elements to a remote a log server, usually in XML format. Here is an example configuration that writes JSON to the TCP input plugin of a fluent-bit log server running on the same system as the application: ~~~{.xml} ~~~

XMLSocketAppender has the following properties: - The event will be logged with the same time stamp, NDC, location info as if it were logged locally by the client. - Remote logging uses the TCP protocol. Consequently, if the server is reachable, then log events will eventually arrive at the server. - If the remote server is down, the logging requests are simply dropped. However, if and when the server comes back up, then event transmission is resumed transparently. This transparent reconneciton is performed by a connector thread which periodically attempts to connect to the server. - Logging events are automatically buffered by the native TCP implementation. This means that if the link to server is slow but still faster than the rate of (log) event production by the client, the client will not be affected by the slow network connection. However, if the network connection is slower then the rate of event production, then the client can only progress at the network rate. In particular, if the network link to the the server is down, the client will be blocked. @n @n On the other hand, if the network link is up, but the server is down, the client will not be blocked when making log requests but the log events will be lost due to server unavailability. - Even if an XMLSocketAppender is no longer attached to any logger, it will not be destroyed in the presence of a connector thread. A connector thread exists only if the connection to the server is down. To avoid this destruction problem, you should #close the the XMLSocketAppender explicitly. See also next item. @n @n Long lived applications which create/destroy many XMLSocketAppender instances should be aware of this destruction problem. Most other applications can safely ignore it. - If the application hosting the XMLSocketAppender exits before the XMLSocketAppender is closed either explicitly or subsequent to destruction, then there might be untransmitted data in the pipe which might be lost. @n @n To avoid lost data, it is usually sufficient to #close the XMLSocketAppender either explicitly or by calling the LogManager#shutdown method before exiting the application. */ class LOG4CXX_EXPORT XMLSocketAppender : public SocketAppenderSkeleton { public: /** The default port number of remote logging server (4560). */ static int DEFAULT_PORT; /** The default reconnection delay (30000 milliseconds or 30 seconds). */ static int DEFAULT_RECONNECTION_DELAY; /** Unused */ static const int MAX_EVENT_LEN; DECLARE_LOG4CXX_OBJECT(XMLSocketAppender) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(XMLSocketAppender) LOG4CXX_CAST_ENTRY_CHAIN(AppenderSkeleton) END_LOG4CXX_CAST_MAP() XMLSocketAppender(); ~XMLSocketAppender(); /** Connects to remote server at address and port. */ XMLSocketAppender(helpers::InetAddressPtr address, int port); /** Connects to remote server at host and port. */ XMLSocketAppender(const LogString& host, int port); protected: void setSocket(LOG4CXX_NS::helpers::SocketPtr& socket, helpers::Pool& p) override; void cleanUp(helpers::Pool& p) override; int getDefaultDelay() const override; int getDefaultPort() const override; void append(const spi::LoggingEventPtr& event, helpers::Pool& pool) override; private: // prevent copy and assignment statements XMLSocketAppender(const XMLSocketAppender&); XMLSocketAppender& operator=(const XMLSocketAppender&); struct XMLSocketAppenderPriv; }; // class XMLSocketAppender LOG4CXX_PTR_DEF(XMLSocketAppender); } // namespace net } // namespace log4cxx #endif // _LOG4CXX_NET_XML_SOCKET_APPENDER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/consoleappender.h0000644000175100001770000000664614721727031023770 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_CONSOLE_APPENDER_H #define _LOG4CXX_CONSOLE_APPENDER_H #include namespace LOG4CXX_NS { /** * ConsoleAppender appends log events to stdout or * stderr using a layout specified by the user. * * The default target is stdout. * * You can use fwide(stdout, 1) in your configuration code * or use the cmake directive `LOG4CXX_FORCE_WIDE_CONSOLE=ON` when building Log4cxx * to force Log4cxx to use fputws. * If doing this ensure the cmake directive `LOG4CXX_WCHAR_T` is also enabled. */ class LOG4CXX_EXPORT ConsoleAppender : public WriterAppender { private: struct ConsoleAppenderPriv; public: DECLARE_LOG4CXX_OBJECT(ConsoleAppender) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(ConsoleAppender) LOG4CXX_CAST_ENTRY_CHAIN(AppenderSkeleton) END_LOG4CXX_CAST_MAP() /** * A stdout log event appender. * * See also #setLayout and #setTarget. */ ConsoleAppender(); /** * A stdout log event appender formatted using \c layout. * * @param layout formats a log event */ ConsoleAppender(const LayoutPtr& layout); /** * A \c target log event appender formatted using \c layout. * * @param layout formats a log event * @param target the value provided by #getSystemOut or #getSystemErr */ ConsoleAppender(const LayoutPtr& layout, const LogString& target); ~ConsoleAppender(); /** * Use \c newValue for the target property. * * @param newValue the value provided by #getSystemOut or #getSystemErr * */ void setTarget(const LogString& newValue); /** * @returns the current value of the target property. */ LogString getTarget() const; /** \copybrief WriterAppender::activateOptions() No action is performed in this implementation. */ void activateOptions(helpers::Pool& p) override; /** \copybrief WriterAppender::setOption() Supported options | Supported values | Default value -------------- | ---------------- | --------------- Target | System.err,System.out | System.out \sa WriterAppender::setOption() */ void setOption(const LogString& option, const LogString& value) override; /** * @returns the name recognised as stdout. */ static const LogString& getSystemOut(); /** * @returns the name recognised as stderr. */ static const LogString& getSystemErr(); private: void targetWarn(const LogString& val); }; LOG4CXX_PTR_DEF(ConsoleAppender); } //namespace log4cxx #endif //_LOG4CXX_CONSOLE_APPENDER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/defaultconfigurator.h0000644000175100001770000001062714721727031024650 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_DEFAULT_CONFIGURATOR_H #define _LOG4CXX_DEFAULT_CONFIGURATOR_H #include #include #include namespace LOG4CXX_NS { /** * Configures the repository from environmental settings and files. * */ class LOG4CXX_EXPORT DefaultConfigurator { private: DefaultConfigurator() {} public: /** Configure \c repository. If the configuration file name has not been provided by a call to setConfigurationFileName(), the environment variables "LOG4CXX_CONFIGURATION" and "log4j.configuration" are examined. Unless a custom configurator is specified using the "LOG4CXX_CONFIGURATOR_CLASS" or "log4j.configuratorClass" environment variable, the PropertyConfigurator will be used to configure log4cxx unless the file name ends with the ".xml" extension, in which case the DOMConfigurator will be used. If a custom configurator is specified, the environment variable should contain a fully qualified class name of a class that implements the Configurator interface. If the configuration file name is not found using any of the previous approaches, the current directory is examined for a file with extension ".xml" or ".properties" with a base name "log4cxx" or "log4j". If a positive number has been provided by a call to setConfigurationWatchSeconds() or the environment variables "LOG4CXX_CONFIGURATION_WATCH_SECONDS" contains a positive number a background thread is started that will periodically check for a change to the configuration file and apply any configuration changes found. */ static void configure(spi::LoggerRepositoryPtr repository); /** Make \c path the configuration file used by configure(). */ static void setConfigurationFileName(const LogString& path); /** Make \c seconds the time a background thread will delay before checking for a change to the configuration file used by configure(). */ static void setConfigurationWatchSeconds(int seconds); /** * Configure Log4cxx from a file. This method will attempt to load the configuration files in the * directories given. * * For example, if we want a configuration file named 'myapp-logging.xml' with the default location * for this file in /etc/myapp, but to have this overriden by a file in /usr/local/etc/myapp, we would * call this function as follows: * * configureFromFile( { "/usr/local/etc/myapp", "/etc/myapp" }, { "myapp-logging.xml" ); * * This will then search for files in the following order: * *

		 * /usr/local/etc/myapp/myapp-logging.xml
		 * /etc/myapp/myapp-logging.xml
		 * 
* * The status of configuring Log4cxx as well as the eventual filename used is returned. If a file exists * but it is not able to be used to configure Log4cxx, the next file in the list will be tried until * a valid configuration file is found or the end of the list is reached. * * @param directories The directories to look in. * @param filenames The names of the files to look for * @return The status of the configuration, and the filename loaded(if a file was found). */ static std::tuple configureFromFile(const std::vector& directories, const std::vector& filenames); private: static const LogString getConfigurationFileName(); static const LogString getConfiguratorClass(); static int getConfigurationWatchDelay(); static LOG4CXX_NS::spi::ConfigurationStatus tryLoadFile(const LogString& filename); }; // class DefaultConfigurator } // namespace log4cxx #endif //_LOG4CXX_DEFAULT_CONFIGURATOR_H apache-log4cxx-1.3.1/src/main/include/log4cxx/filter/0000755000175100001770000000000014721727031021707 5ustar runnerdockerapache-log4cxx-1.3.1/src/main/include/log4cxx/filter/loggermatchfilter.h0000644000175100001770000000632614721727031025571 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_FILTER_LOGGER_MATCH_FILTER_H #define _LOG4CXX_FILTER_LOGGER_MATCH_FILTER_H #include #include namespace LOG4CXX_NS { class Level; namespace filter { /** 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 spi::LoggingEvent LoggingEvent}, then the #decide method returns {@link spi::Filter#ACCEPT ACCEPT} in case the acceptOnMatch option value is set to true, if it is false then {@link spi::Filter#DENY} is returned. If there is no match, {@link spi::Filter#NEUTRAL} is returned. A loggerToMatch of "root" matches both the root logger and a logger named "root". */ class LOG4CXX_EXPORT LoggerMatchFilter : public spi::Filter { private: struct LoggerMatchFilterPrivate; public: typedef spi::Filter BASE_CLASS; DECLARE_LOG4CXX_OBJECT(LoggerMatchFilter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(LoggerMatchFilter) LOG4CXX_CAST_ENTRY_CHAIN(BASE_CLASS) END_LOG4CXX_CAST_MAP() LoggerMatchFilter(); ~LoggerMatchFilter(); /** \copybrief spi::OptionHandler::setOption() Supported options | Supported values | Default value -------------- | ---------------- | --------------- LoggerToMatch | {any} | root AcceptOnMatch | True,False | True */ void setOption(const LogString& option, const LogString& value) override; void setLoggerToMatch(const LogString& levelToMatch); LogString getLoggerToMatch() const; void setAcceptOnMatch(bool acceptOnMatch1); bool getAcceptOnMatch() const; /** Return the decision of this filter. Returns {@link spi::Filter#NEUTRAL NEUTRAL} if the loggerToMatch option is not set or if there is not match. Otherwise, if there is a match, then the returned decision is {@link spi::Filter#ACCEPT ACCEPT} if the acceptOnMatch property is set to true. The returned decision is {@link spi::Filter#DENY DENY} if the acceptOnMatch property is set to false. */ FilterDecision decide(const spi::LoggingEventPtr& event) const override; }; // class LoggerMatchFilter LOG4CXX_PTR_DEF(LoggerMatchFilter); } // namespace filter } // namespace log4cxx #endif // _LOG4CXX_FILTER_LOGGER_MATCH_FILTER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/filter/propertyfilter.h0000644000175100001770000000415414721727031025156 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_FILTER_PROPERTYFILTER_H #define _LOG4CXX_FILTER_PROPERTYFILTER_H #include #include namespace LOG4CXX_NS { namespace filter { /** * NOTE: This filter modifies logging events by adding properties to the event. * * The 'properties' param is converted to event properties, which are * set on every event processed by the filter. * * Individual properties are only set if they do not already exist on the * logging event (will not override existing properties). * * This class relies on the convention that property name/value pairs are * equals-symbol delimited, and each name/value pair is comma-delimited * * Example properties param: * somename=somevalue,anothername=anothervalue,thirdname=third value * * */ class LOG4CXX_EXPORT PropertyFilter : public LOG4CXX_NS::spi::Filter { typedef std::map < LogString, LogString > PropertyMap; PropertyMap* properties; PropertyFilter(const PropertyFilter&); PropertyFilter& operator=(const PropertyFilter&); public: DECLARE_LOG4CXX_OBJECT(PropertyFilter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(LOG4CXX_NS::spi::Filter) END_LOG4CXX_CAST_MAP() PropertyFilter(); ~PropertyFilter(); void setProperties(const LogString& props); FilterDecision decide(const spi::LoggingEventPtr& event) const override; }; } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/filter/stringmatchfilter.h0000644000175100001770000000600714721727031025614 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_FILTER_STRING_MATCH_FILTER_H #define _LOG4CXX_FILTER_STRING_MATCH_FILTER_H #include namespace LOG4CXX_NS { namespace filter { /** 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 spi::LoggingEvent LoggingEvent}, then the #decide method returns {@link log4cxx::spi::Filter#ACCEPT ACCEPT} if the AcceptOnMatch option value is true, if it is false then {@link log4cxx::spi::Filter#DENY DENY} is returned. If there is no match, {@link log4cxx::spi::Filter#NEUTRAL NEUTRAL} is returned.

See configuration files test6.xml, test7.xml, test8.xml, test9.xml, and test10.xml for examples of seeting up a StringMatchFilter. */ class LOG4CXX_EXPORT StringMatchFilter : public spi::Filter { private: struct StringMatchFilterPrivate; public: typedef spi::Filter BASE_CLASS; DECLARE_LOG4CXX_OBJECT(StringMatchFilter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(StringMatchFilter) LOG4CXX_CAST_ENTRY_CHAIN(BASE_CLASS) END_LOG4CXX_CAST_MAP() StringMatchFilter(); ~StringMatchFilter(); /** \copybrief spi::OptionHandler::setOption() Supported options | Supported values | Default value -------------- | ---------------- | --------------- StringToMatch | {any} | - AcceptOnMatch | True,False | True */ void setOption(const LogString& option, const LogString& value) override; void setStringToMatch(const LogString& stringToMatch1); const LogString& getStringToMatch() const; void setAcceptOnMatch(bool acceptOnMatch1); bool getAcceptOnMatch() const; /** Returns {@link log4cxx::spi::Filter#NEUTRAL NEUTRAL} is there is no string match. */ FilterDecision decide(const spi::LoggingEventPtr& event) const override; }; // class StringMatchFilter LOG4CXX_PTR_DEF(StringMatchFilter); } // namespace filter } // namespace log4cxx #endif // _LOG4CXX_FILTER_STRING_MATCH_FILTER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/filter/expressionfilter.h0000644000175100001770000000754714721727031025502 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_FILTER_EXPRESSIONFILTER_H #define _LOG4CXX_FILTER_EXPRESSIONFILTER_H #include namespace LOG4CXX_NS { namespace rule { class Rule; typedef helpers::ObjectPtrT < Rule > RulePtr; } namespace filter { /** *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 ORO-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 log4cxx::spi::LoggingEvent} and AcceptOnMatch is true, * the {@link #decide} method returns {@link log4cxx::spi::Filter#ACCEPT}. * * If there is a match between the value of the * Expression option and the {@link log4cxx::spi::LoggingEvent} and AcceptOnMatch is false, * {@link log4cxx::spi::Filter#DENY} is returned. * * If there is no match, {@link log4cxx::spi::Filter#NEUTRAL} is returned. * * */ class LOG4CXX_EXPORT ExpressionFilter: public LOG4CXX_NS::spi::Filter { private: bool acceptOnMatch; bool convertInFixToPostFix; LOG4CXX_DECLARE_PRIVATE_MEMBER(LogString, expression) LOG4CXX_DECLARE_PRIVATE_MEMBER(rule::RulePtr, expressionRule) ExpressionFilter(const ExpressionFilter&); ExpressionFilter& operator=(const ExpressionFilter&); public: DECLARE_LOG4CXX_OBJECT(ExpressionFilter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(LOG4CXX_NS::spi::Filter) END_LOG4CXX_CAST_MAP() ExpressionFilter(); void activateOptions(helpers::Pool& p) override; void setExpression(const LogString& expression); LogString getExpression() const; void setConvertInFixToPostFix(bool convertInFixToPostFix); bool getConvertInFixToPostFix() const; void setAcceptOnMatch(bool acceptOnMatch); bool getAcceptOnMatch() const; /** Returns {@link log4cxx::spi::Filter#NEUTRAL} is there is no string match. */ FilterDecision decide(const spi::LoggingEventPtr& event) const override; }; } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/filter/mapfilter.h0000644000175100001770000000557114721727031024053 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_FILTER_MAPFILTER_H #define _LOG4CXX_FILTER_MAPFILTER_H #include namespace LOG4CXX_NS { namespace filter { /** * A Filter that operates on the current thread's MDC map. For example, to exclude entries from the log where the context has "user.name" set to "test2" and "user.ip" is "127.0.0.1": *

 * <filter class="MapFilter">
 *     <param name="user.ip"       value="127.0.0.1" />
 *     <param name="user.name"     value="test2"     />
 *     <param name="Operator"      value="AND"       />
 *     <param name="AcceptOnMatch" value="false"     />
 * </filter>
 * 
*/ class LOG4CXX_EXPORT MapFilter: public LOG4CXX_NS::spi::Filter { typedef std::map < LogString, LogString > KeyVals; private: struct MapFilterPrivate; public: DECLARE_LOG4CXX_OBJECT(MapFilter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(MapFilter) LOG4CXX_CAST_ENTRY_CHAIN(LOG4CXX_NS::spi::Filter) END_LOG4CXX_CAST_MAP() MapFilter(); ~MapFilter(); /** \copybrief spi::OptionHandler::setOption() Supported options | Supported values | Default value -------------- | ---------------- | --------------- Operator | (\ref andOrOne "1") | Or AcceptOnMatch | True,False | True {anyKey} | {anyValue} | - \anchor andOrOne (1) If "And", the MDC must contain all configured key-value pairs, otherwise only one configured key-value pair needs to match. */ void setOption(const LogString& option, const LogString& value) override; void setKeyValue(const LogString& strKey, const LogString& strValue); const LogString& getValue(const LogString& strKey) const; void setAcceptOnMatch(bool acceptOnMatch1); bool getAcceptOnMatch() const; bool getMustMatchAll() const; void setMustMatchAll(bool mustMatchAll1); /** Returns {@link log4cxx::spi::Filter#NEUTRAL NEUTRAL} is there is no string match. */ FilterDecision decide(const spi::LoggingEventPtr& event) const override; }; // class MapFilter LOG4CXX_PTR_DEF(MapFilter); } // namespace filter } // namespace log4cxx #endif // _LOG4CXX_FILTER_MAPFILTER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/filter/levelmatchfilter.h0000644000175100001770000000643414721727031025421 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_FILTER_LEVEL_MATCH_FILTER_H #define _LOG4CXX_FILTER_LEVEL_MATCH_FILTER_H #include #include namespace LOG4CXX_NS { class Level; namespace filter { /** 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 spi::LoggingEvent LoggingEvent}, then the #decide method returns {@link spi::Filter::ACCEPT ACCEPT} in case the acceptOnMatch option value is set to true, if it is false then {@link spi::Filter::DENY DENY} is returned. If there is no match, {@link spi::Filter::NEUTRAL NEUTRAL} is returned. */ class LOG4CXX_EXPORT LevelMatchFilter : public spi::Filter { private: struct LevelMatchFilterPrivate; public: typedef spi::Filter BASE_CLASS; DECLARE_LOG4CXX_OBJECT(LevelMatchFilter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(LevelMatchFilter) LOG4CXX_CAST_ENTRY_CHAIN(BASE_CLASS) END_LOG4CXX_CAST_MAP() LevelMatchFilter(); ~LevelMatchFilter(); /** \copybrief spi::OptionHandler::setOption() Supported options | Supported values | Default value -------------- | ---------------- | --------------- LevelToMatch | (\ref validLevel "1") | - AcceptOnMatch | True,False | True \anchor validLevel (1) One of Trace, Debug, Info, Warn, Error, Fatal, Off, All or a custom level in which case it is of the form {levelName}#{registeredClassName}. */ void setOption(const LogString& option, const LogString& value) override; void setLevelToMatch(const LogString& levelToMatch); LogString getLevelToMatch() const; void setAcceptOnMatch(bool acceptOnMatch1); bool getAcceptOnMatch() const; /** Return the decision of this filter. Returns {@link spi::Filter#NEUTRAL 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 spi::Filter#ACCEPT ACCEPT} if the acceptOnMatch property is set to true. The returned decision is {@link spi::Filter#DENY DENY} if the acceptOnMatch property is set to false. */ FilterDecision decide(const spi::LoggingEventPtr& event) const override; }; // class LevelMatchFilter LOG4CXX_PTR_DEF(LevelMatchFilter); } // namespace filter } // namespace log4cxx #endif // _LOG4CXX_FILTER_LEVEL_MATCH_FILTER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/filter/andfilter.h0000644000175100001770000000642314721727031024035 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_FILTER_ANDFILTER_H #define _LOG4CXX_FILTER_ANDFILTER_H #include #include namespace LOG4CXX_NS { namespace filter { /** * 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: *

 * <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
 *  <filter class="org.apache.log4j.filter.AndFilter">
 *   <filter class="org.apache.log4j.filter.LevelMatchFilter">
 *        <param name="levelToMatch" value="DEBUG" />
 *        <param name="acceptOnMatch" value="true" />
 *   </filter>
 *   <filter class="org.apache.log4j.filter.StringMatchFilter">
 *        <param name="stringToMatch" value="test" />
 *        <param name="acceptOnMatch" value="true" />
 *   </filter>
 *   <param name="acceptOnMatch" value="false"/>
 *  </filter>
 *  <filter class="org.apache.log4j.filter.DenyAllFilter"/>
 * <layout class="org.apache.log4j.SimpleLayout"/>
 * </appender>
 * 
* * 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' ) * * */ class LOG4CXX_EXPORT AndFilter: public LOG4CXX_NS::spi::Filter { private: struct AndFilterPrivate; AndFilter(const AndFilter&); AndFilter& operator=(const AndFilter&); public: DECLARE_LOG4CXX_OBJECT(AndFilter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(LOG4CXX_NS::spi::Filter) END_LOG4CXX_CAST_MAP() AndFilter(); ~AndFilter(); void addFilter(const spi::FilterPtr& filter); void setAcceptOnMatch(bool acceptOnMatch); FilterDecision decide(const spi::LoggingEventPtr& event) const override; }; LOG4CXX_PTR_DEF(AndFilter); } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/filter/locationinfofilter.h0000644000175100001770000000615414721727031025760 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_FILTER_LOCATIONINFOFILTER_H #define _LOG4CXX_FILTER_LOCATIONINFOFILTER_H #include namespace LOG4CXX_NS { namespace filter { /** * When location information is available, individual log statements can be turned on or off * depending on their source location. * * This filter allows for filtering messages based off of either the line number of the * message, or the name of the method that the log mesage is in. The 'operator' parameter * may be used to determine if both the method name and line number must match. * If 'operator' is set to 'AND', then both the line number and method name must match, * otherwise only one needs to match. By default, 'operator' is set to 'OR'. * * If location information is not available, this filter does nothing. * */ class LOG4CXX_EXPORT LocationInfoFilter: public LOG4CXX_NS::spi::Filter { struct LocationInfoFilterPrivate; public: DECLARE_LOG4CXX_OBJECT(LocationInfoFilter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(LocationInfoFilter) LOG4CXX_CAST_ENTRY_CHAIN(LOG4CXX_NS::spi::Filter) END_LOG4CXX_CAST_MAP() LocationInfoFilter(); ~LocationInfoFilter(); /** \copybrief spi::OptionHandler::setOption() Supported options | Supported values | Default value -------------- | ---------------- | --------------- Method | {any} | - LineNumber | {int} | - Operator | (\ref andOrAny "1") | Or AcceptOnMatch | True,False | True \anchor andOrAny (1) If "And", both method name and line number must match, otherwise either method name or line number match. */ void setOption(const LogString& option, const LogString& value) override; void setLineNumber(int lineNum); void setMethodName(const LogString& methodName); void setAcceptOnMatch(bool acceptOnMatch1); bool getAcceptOnMatch() const; bool getMustMatchAll() const; void setMustMatchAll(bool mustMatchAll1); /** * 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 log4cxx::spi::Filter#NEUTRAL} */ FilterDecision decide(const spi::LoggingEventPtr& event) const override; }; LOG4CXX_PTR_DEF(LocationInfoFilter); } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/filter/denyallfilter.h0000644000175100001770000000376114721727031024725 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_FILTER_DENY_ALL_FILTER_H #define _LOG4CXX_FILTER_DENY_ALL_FILTER_H #include namespace LOG4CXX_NS { namespace filter { /** 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. */ class LOG4CXX_EXPORT DenyAllFilter : public spi::Filter { public: DenyAllFilter() : spi::Filter() { } typedef spi::Filter BASE_CLASS; DECLARE_LOG4CXX_OBJECT(DenyAllFilter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(DenyAllFilter) LOG4CXX_CAST_ENTRY_CHAIN(BASE_CLASS) END_LOG4CXX_CAST_MAP() /** Always returns the integer constant {@link spi::Filter#DENY DENY} regardless of the {@link spi::LoggingEventPtr LoggingEvent} parameter. @param event The LoggingEvent to filter. @return Always returns {@link spi::Filter#DENY DENY}. */ FilterDecision decide(const spi::LoggingEventPtr& event) const override { return spi::Filter::DENY; } }; // class DenyAllFilter LOG4CXX_PTR_DEF(DenyAllFilter); } // namespace filter } // namespace log4cxx #endif // _LOG4CXX_FILTER_DENY_ALL_FILTER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/filter/levelrangefilter.h0000644000175100001770000001045014721727031025412 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_FILTER_LEVEL_RANGE_FILTER_H #define _LOG4CXX_FILTER_LEVEL_RANGE_FILTER_H #include #include namespace LOG4CXX_NS { namespace filter { /** 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 spi::LoggingEvent LoggingEvent} is not between Min and Max (inclusive), then {@link spi::Filter#DENY DENY} is returned.

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

If levelMinw 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 AppenderSkeleton#setThreshold setThreshold} method available to all appenders extending AppenderSkeleton for a more convenient way to filter out events by level. */ class LOG4CXX_EXPORT LevelRangeFilter : public spi::Filter { private: struct LevelRangeFilterPrivate; public: typedef spi::Filter BASE_CLASS; DECLARE_LOG4CXX_OBJECT(LevelRangeFilter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(LevelRangeFilter) LOG4CXX_CAST_ENTRY_CHAIN(BASE_CLASS) END_LOG4CXX_CAST_MAP() LevelRangeFilter(); ~LevelRangeFilter(); /** \copybrief spi::OptionHandler::setOption() Supported options | Supported values | Default value -------------- | ---------------- | --------------- LevelMin | (\ref validLevels "1") | ALL LevelMax | (\ref validLevels "1") | OFF AcceptOnMatch | True,False | True \anchor validLevels (1). One of "Trace", "Debug", "Info", "Warn", "Error", "Fatal", "Off", "All" or a custom level in which case it is of the form {levelName}#{registeredClassName}. */ void setOption(const LogString& option, const LogString& value) override; /** Set the levelMin option. */ void setLevelMin(const LevelPtr& levelMin1); /** Get the value of the levelMin option. */ const LevelPtr& getLevelMin() const; /** Set the levelMax option. */ void setLevelMax(const LevelPtr& levelMax1); /** Get the value of the levelMax option. */ const LevelPtr& getLevelMax() const; /** Set the acceptOnMatch option. */ void setAcceptOnMatch(bool acceptOnMatch1); /** Get the value of the acceptOnMatch option. */ bool getAcceptOnMatch() const; /** Return the decision of this filter. Returns {@link spi::Filter#NEUTRAL 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 spi::Filter#ACCEPT ACCEPT} if the acceptOnMatch property is set to true. The returned decision is {@link spi::Filter#DENY DENY} if the acceptOnMatch property is set to false. */ FilterDecision decide(const spi::LoggingEventPtr& event) const override; }; // class LevelRangeFilter LOG4CXX_PTR_DEF(LevelRangeFilter); } // namespace filter } // namespace log4cxx #endif // _LOG4CXX_FILTER_LEVEL_RANGE_FILTER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/stream.h0000644000175100001770000003566114721727031022101 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_STREAM_H #define _LOG4CXX_STREAM_H #include #include #include namespace LOG4CXX_NS { /** * Base class for the basic_logstream template which attempts * to emulate std::basic_ostream but attempts to short-circuit * unnecessary operations. * * The logstream has a logger and level that are used for logging * requests. The level of the stream is compared against the * current level of the logger to determine if the request should be processed. */ class LOG4CXX_EXPORT logstream_base { public: /** * Create new instance. * @param logger logger logger used in log requests. * @param level indicates level that will be used in log requests. Can * be modified later by inserting a level or calling setLevel. */ logstream_base(const LOG4CXX_NS::LoggerPtr& logger, const LOG4CXX_NS::LevelPtr& level); /** * Destructor. */ virtual ~logstream_base(); /** * Insertion operator for std::fixed and similar manipulators. */ void insert(std::ios_base & (*manip)(std::ios_base&)); /** * get precision. */ int precision(); /** * get width. */ int width(); /** * set precision. This should be used in preference to inserting an std::setprecision(n) * since the other requires construction of an STL stream which may be expensive. */ int precision(int newval); /** * set width. This should be used in preference to inserting an std::setw(n) * since the other requires construction of an STL stream which may be expensive. */ int width(int newval); /** * Get fill character. */ int fill(); /** * Set fill character. */ int fill(int newval); /** * Set flags. see std::ios_base. */ std::ios_base::fmtflags flags(std::ios_base::fmtflags newflags); /** * Set flags. see std::ios_base. */ std::ios_base::fmtflags setf(std::ios_base::fmtflags newflags, std::ios_base::fmtflags mask); /** * Set flags. see std::ios_base. */ std::ios_base::fmtflags setf(std::ios_base::fmtflags newflags); /** * end of message manipulator, triggers logging. */ static logstream_base& endmsg(logstream_base&); /** * no-operation manipulator, Used to avoid ambiguity with VC6. */ static logstream_base& nop(logstream_base&); /** * end of message action. */ void end_message(); /** * Set the level. * @param level level */ void setLevel(const LevelPtr& level); /** * Returns true if the current level is the same or high as the * level of logger at time of construction or last setLevel. */ inline bool isEnabled() const { return enabled; } /** * Returns if logger is currently enabled for the specified level. */ bool isEnabledFor(const LevelPtr& level) const; /** * Sets the location for subsequent log requests. */ void setLocation(const LOG4CXX_NS::spi::LocationInfo& location); /** * Sets the state of the embedded stream (if any) * to the state of the formatting info. * @param os stream to receive formatting info. * @param fillchar receives fill charater. * @return true if fill character was specified. */ bool set_stream_state(std::ios_base& os, int& fillchar); protected: /** * Dispatches the pending log request. */ virtual void log(LoggerPtr& logger, const LevelPtr& level, const LOG4CXX_NS::spi::LocationInfo& location) = 0; /** * Erase any content in the message construction buffer. */ virtual void erase() = 0; /** * Copy state of embedded stream (if any) * to value and mask instances of std::ios_base * and return fill character value. */ virtual void get_stream_state(std::ios_base& base, std::ios_base& mask, int& fill, bool& fillSet) const = 0; virtual void refresh_stream_state() = 0; private: /** * prevent copy constructor. */ logstream_base(logstream_base&); /** * prevent copy operatpr. */ logstream_base& operator=(logstream_base&); /** * Minimal extension of std::ios_base to allow creation * of embedded IO states. */ class LOG4CXX_EXPORT logstream_ios_base : public std::ios_base { public: logstream_ios_base(std::ios_base::fmtflags initval, int initsize); } initset, initclear; /** * fill character. */ int fillchar; /** * true if fill character is set. */ bool fillset; /** * true if assigned level was same or higher than level of associated logger. */ bool enabled; /** * associated logger. */ LOG4CXX_NS::LoggerPtr logger; /** * associated level. */ LOG4CXX_NS::LevelPtr level; /** * associated level. */ LOG4CXX_NS::spi::LocationInfo location; }; typedef logstream_base& (*logstream_manipulator)(logstream_base&); /** * An STL-like stream API for log4cxx using char as the character type. *. Instances of log4cxx::logstream * are not designedfor use by multiple threads and in general should be short-lived * function scoped objects. Using log4cxx::basic_logstream as a class member or * static instance should be avoided in the same manner as you would avoid placing a std::ostringstream * in those locations. Insertion operations are generally short-circuited if the * level for the stream is not the same of higher that the level of the associated logger. */ class LOG4CXX_EXPORT logstream : public logstream_base { typedef char Ch; public: /** * Constructor. */ logstream(const LOG4CXX_NS::LoggerPtr& logger, const LOG4CXX_NS::LevelPtr& level); /** * Constructor. */ logstream(const Ch* loggerName, const LOG4CXX_NS::LevelPtr& level); /** * Constructor. */ logstream(const std::basic_string& loggerName, const LOG4CXX_NS::LevelPtr& level); ~logstream(); /** * Insertion operator for std::fixed and similar manipulators. */ logstream& operator<<(std::ios_base & (*manip)(std::ios_base&)); /** * Insertion operator for logstream_base::endmsg. */ logstream& operator<<(logstream_manipulator manip); /** * Insertion operator for level. */ logstream& operator<<(const LOG4CXX_NS::LevelPtr& level); /** * Insertion operator for location. */ logstream& operator<<(const LOG4CXX_NS::spi::LocationInfo& location); /** * Alias for insertion operator for location. Kludge to avoid * inappropriate compiler ambiguity. */ logstream& operator>>(const LOG4CXX_NS::spi::LocationInfo& location); /** * Cast operator to provide access to embedded std::basic_ostream. */ operator std::basic_ostream& (); #if !(LOG4CXX_USE_GLOBAL_SCOPE_TEMPLATE) /** * Template to allow any class with an std::basic_ostream inserter * to be applied to this class. */ template inline LOG4CXX_NS::logstream& operator<<(const V& val) { if (LOG4CXX_UNLIKELY(isEnabled())) { ((std::basic_ostream&) *this) << val; } return *this; } #endif protected: virtual void log(LoggerPtr& logger, const LevelPtr& level, const LOG4CXX_NS::spi::LocationInfo& location); virtual void erase(); virtual void get_stream_state(std::ios_base& base, std::ios_base& mask, int& fill, bool& fillSet) const; virtual void refresh_stream_state(); private: logstream(const logstream&); logstream& operator=(const logstream&); std::basic_stringstream* stream; }; #if LOG4CXX_WCHAR_T_API /** * An STL-like stream API for log4cxx using wchar_t as the character type. *. Instances of log4cxx::logstream * are not designedfor use by multiple threads and in general should be short-lived * function scoped objects. Using log4cxx::basic_logstream as a class member or * static instance should be avoided in the same manner as you would avoid placing a std::ostringstream * in those locations. Insertion operations are generally short-circuited if the * level for the stream is not the same of higher that the level of the associated logger. */ class LOG4CXX_EXPORT wlogstream : public logstream_base { typedef wchar_t Ch; public: /** * Constructor. */ wlogstream(const LOG4CXX_NS::LoggerPtr& logger, const LOG4CXX_NS::LevelPtr& level); /** * Constructor. */ wlogstream(const Ch* loggerName, const LOG4CXX_NS::LevelPtr& level); /** * Constructor. */ wlogstream(const std::basic_string& loggerName, const LOG4CXX_NS::LevelPtr& level); ~wlogstream(); /** * Insertion operator for std::fixed and similar manipulators. */ wlogstream& operator<<(std::ios_base & (*manip)(std::ios_base&)); /** * Insertion operator for logstream_base::endmsg. */ wlogstream& operator<<(logstream_manipulator manip); /** * Insertion operator for level. */ wlogstream& operator<<(const LOG4CXX_NS::LevelPtr& level); /** * Insertion operator for location. */ wlogstream& operator<<(const LOG4CXX_NS::spi::LocationInfo& location); /** * Alias for insertion operator for location. Kludge to avoid * inappropriate compiler ambiguity. */ wlogstream& operator>>(const LOG4CXX_NS::spi::LocationInfo& location); /** * Cast operator to provide access to embedded std::basic_ostream. */ operator std::basic_ostream& (); #if !(LOG4CXX_USE_GLOBAL_SCOPE_TEMPLATE) /** * Template to allow any class with an std::basic_ostream inserter * to be applied to this class. */ template inline LOG4CXX_NS::wlogstream& operator<<(const V& val) { if (LOG4CXX_UNLIKELY(isEnabled())) { ((std::basic_ostream&) *this) << val; } return *this; } #endif protected: virtual void log(LoggerPtr& logger, const LevelPtr& level, const LOG4CXX_NS::spi::LocationInfo& location); virtual void erase(); virtual void get_stream_state(std::ios_base& base, std::ios_base& mask, int& fill, bool& fillSet) const; virtual void refresh_stream_state(); private: wlogstream(const wlogstream&); wlogstream& operator=(const wlogstream&); std::basic_stringstream* stream; }; #endif #if LOG4CXX_UNICHAR_API /** * An STL-like stream API for log4cxx using UniChar as the character type. *. Instances of log4cxx::logstream * are not designedfor use by multiple threads and in general should be short-lived * function scoped objects. Using log4cxx::basic_logstream as a class member or * static instance should be avoided in the same manner as you would avoid placing a std::ostringstream * in those locations. Insertion operations are generally short-circuited if the * level for the stream is not the same of higher that the level of the associated logger. */ class LOG4CXX_EXPORT ulogstream : public logstream_base { typedef UniChar Ch; public: /** * Constructor. */ ulogstream(const LOG4CXX_NS::LoggerPtr& logger, const LOG4CXX_NS::LevelPtr& level); #if LOG4CXX_UNICHAR_API /** * Constructor. */ ulogstream(const Ch* loggerName, const LOG4CXX_NS::LevelPtr& level); /** * Constructor. */ ulogstream(const std::basic_string& loggerName, const LOG4CXX_NS::LevelPtr& level); #endif #if LOG4CXX_CFSTRING_API ulogstream(const CFStringRef& loggerName, const LOG4CXX_NS::LevelPtr& level); #endif ~ulogstream(); /** * Insertion operator for std::fixed and similar manipulators. */ ulogstream& operator<<(std::ios_base & (*manip)(std::ios_base&)); /** * Insertion operator for logstream_base::endmsg. */ ulogstream& operator<<(logstream_manipulator manip); /** * Insertion operator for level. */ ulogstream& operator<<(const LOG4CXX_NS::LevelPtr& level); /** * Insertion operator for location. */ ulogstream& operator<<(const LOG4CXX_NS::spi::LocationInfo& location); /** * Alias for insertion operator for location. Kludge to avoid * inappropriate compiler ambiguity. */ ulogstream& operator>>(const LOG4CXX_NS::spi::LocationInfo& location); /** * Cast operator to provide access to embedded std::basic_ostream. */ operator std::basic_ostream& (); #if !(LOG4CXX_USE_GLOBAL_SCOPE_TEMPLATE) /** * Template to allow any class with an std::basic_ostream inserter * to be applied to this class. */ template inline ulogstream& operator<<(const V& val) { if (LOG4CXX_UNLIKELY(isEnabled())) { ((std::basic_ostream&) *this) << val; } return *this; } #endif protected: virtual void log(LoggerPtr& logger, const LevelPtr& level, const LOG4CXX_NS::spi::LocationInfo& location); virtual void erase(); virtual void get_stream_state(std::ios_base& base, std::ios_base& mask, int& fill, bool& fillSet) const; virtual void refresh_stream_state(); private: ulogstream(const ulogstream&); ulogstream& operator=(const ulogstream&); std::basic_stringstream* stream; }; #endif } // namespace log4cxx #if LOG4CXX_USE_GLOBAL_SCOPE_TEMPLATE // // VC6 will fail to compile if class-scope templates // are used to handle arbitrary insertion operations. // However, using global namespace insertion operations // run into LOGCXX-150. /** * Template to allow any class with an std::basic_ostream inserter * to be applied to this class. */ template inline LOG4CXX_NS::logstream& operator<<(LOG4CXX_NS::logstream& os, const V& val) { if (LOG4CXX_UNLIKELY(os.isEnabled())) { ((std::basic_ostream&) os) << val; } return os; } #if LOG4CXX_WCHAR_T_API /** * Template to allow any class with an std::basic_ostream inserter * to be applied to this class. */ template inline LOG4CXX_NS::wlogstream& operator<<(LOG4CXX_NS::wlogstream& os, const V& val) { if (LOG4CXX_UNLIKELY(os.isEnabled())) { ((std::basic_ostream&) os) << val; } return os; } #endif #endif #if !defined(LOG4CXX_ENDMSG) #if LOG4CXX_LOGSTREAM_ADD_NOP #define LOG4CXX_ENDMSG (LOG4CXX_NS::logstream_manipulator) LOG4CXX_NS::logstream_base::nop >> LOG4CXX_LOCATION << (LOG4CXX_NS::logstream_manipulator) LOG4CXX_NS::logstream_base::endmsg #else #define LOG4CXX_ENDMSG LOG4CXX_LOCATION << (LOG4CXX_NS::logstream_manipulator) LOG4CXX_NS::logstream_base::endmsg #endif #endif #endif //_LOG4CXX_STREAM_H apache-log4cxx-1.3.1/src/main/include/log4cxx/spi/0000755000175100001770000000000014721727031021215 5ustar runnerdockerapache-log4cxx-1.3.1/src/main/include/log4cxx/spi/loggerfactory.h0000644000175100001770000000337114721727031024241 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_SPI_LOGGERFACTORY_H #define _LOG4CXX_SPI_LOGGERFACTORY_H #include namespace LOG4CXX_NS { namespace spi { /** Implement this interface to create new instances of Logger or a sub-class of Logger. */ class LOG4CXX_EXPORT LoggerFactory : public virtual helpers::Object { public: #if LOG4CXX_ABI_VERSION <= 15 DECLARE_ABSTRACT_LOG4CXX_OBJECT(LoggerFactory) #else DECLARE_LOG4CXX_OBJECT(LoggerFactory) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(LoggerFactory) END_LOG4CXX_CAST_MAP() #endif virtual ~LoggerFactory() {} #if LOG4CXX_ABI_VERSION <= 15 [[ deprecated( "Pool is no longer required" ) ]] virtual LoggerPtr makeNewLoggerInstance(helpers::Pool& pool, const LogString& name) const = 0; LoggerPtr makeNewLoggerInstance(const LogString& name) const; #else virtual LoggerPtr makeNewLoggerInstance(const LogString& name) const; #endif }; } // namespace spi } // namesapce log4cxx #endif //_LOG4CXX_SPI_LOGGERFACTORY_H apache-log4cxx-1.3.1/src/main/include/log4cxx/spi/hierarchyeventlistener.h0000644000175100001770000000312414721727031026154 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_SPI_HIERARCHY_EVENT_LISTENER_H #define _LOG4CXX_SPI_HIERARCHY_EVENT_LISTENER_H #include #include namespace LOG4CXX_NS { class Logger; class Appender; namespace spi { /** Listen to events occuring within a Hierarchy.*/ class LOG4CXX_EXPORT HierarchyEventListener : public virtual LOG4CXX_NS::helpers::Object { public: virtual ~HierarchyEventListener() {} virtual void addAppenderEvent( const Logger* logger, const Appender* appender) = 0; virtual void removeAppenderEvent( const Logger* logger, const Appender* appender) = 0; }; LOG4CXX_PTR_DEF(HierarchyEventListener); LOG4CXX_LIST_DEF(HierarchyEventListenerList, HierarchyEventListenerPtr); } // namespace spi } // namespace log4cxx #endif //_LOG4CXX_SPI_HIERARCHY_EVENT_LISTENER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/spi/location/0000755000175100001770000000000014721727031023025 5ustar runnerdockerapache-log4cxx-1.3.1/src/main/include/log4cxx/spi/location/locationinfo.h0000644000175100001770000001110714721727031025662 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_SPI_LOCATION_LOCATIONINFO_H #define _LOG4CXX_SPI_LOCATION_LOCATIONINFO_H #include #include #include #if defined(_MSC_VER) #define LOG4CXX_SHORT_FILENAME_SPLIT_CHAR '\\' #else #define LOG4CXX_SHORT_FILENAME_SPLIT_CHAR '/' #endif namespace LOG4CXX_NS { namespace spi { /** * This class represents the location of a logging statement. * */ class LOG4CXX_EXPORT LocationInfo { public: /** * When location information is not available the constant * NA is returned. Current value of this string constant is ?. */ static const char* const NA; static const char* const NA_METHOD; static const LocationInfo& getLocationUnavailable(); /** * The part of \c fileName after the path. * * Implemented to allow compile-time evaluation when called with a literal string */ #if 201304L <= __cpp_constexpr static constexpr const char* calcShortFileName(const char* fileName){ #else static const char* calcShortFileName(const char* fileName){ #endif if (fileName == nullptr) return nullptr; #if defined(_MSC_VER) // As at 2024, the MSVC optimizer does not inline a function that calls another function const char* location = nullptr; for (auto p = fileName; *p; ++p) if (*p == LOG4CXX_SHORT_FILENAME_SPLIT_CHAR) location = p; #else const char* location = strrchr(fileName, LOG4CXX_SHORT_FILENAME_SPLIT_CHAR); #endif return location == nullptr ? fileName : location + 1; } /** * Constructor. * @remarks Used by LOG4CXX_LOCATION to generate * location info for current code site */ LocationInfo( const char* const fileName, const char* const shortFileName, const char* const functionName, int lineNumber); /** * Default constructor. */ LocationInfo(); /** * Copy constructor. * @param src source location */ LocationInfo( const LocationInfo& src ); /** * Assignment operator. * @param src source location */ LocationInfo& operator = ( const LocationInfo& src ); /** * Resets location info to default state. */ void clear(); /** Return the class name of the call site. */ const std::string getClassName() const; /** * Return the file name of the caller. * @returns file name, may be null. */ const char* getFileName() const; /** * Return the short file name of the caller. * @returns file name. Note that this will fallback to the full filename when using * calcShortFileName to calculate the filename at compile-time. */ const char* getShortFileName() const; /** * Returns the line number of the caller. * @returns line number, -1 if not available. */ int getLineNumber() const; /** Returns the method name of the caller. */ const std::string getMethodName() const; private: /** Caller's line number. */ int lineNumber; /** Caller's file name. */ const char* fileName; /** Caller's short file name. */ const char* shortFileName; /** Caller's method name. */ const char* methodName; }; } } #if !defined(LOG4CXX_LOCATION) && !LOG4CXX_DISABLE_LOCATION_INFO #if defined(_MSC_VER) #if _MSC_VER >= 1300 #define __LOG4CXX_FUNC__ __FUNCSIG__ #endif #else #if defined(__GNUC__) #define __LOG4CXX_FUNC__ __PRETTY_FUNCTION__ #else #if defined(__BORLANDC__) #define __LOG4CXX_FUNC__ __FUNC__ #endif #endif #endif #if !defined(__LOG4CXX_FUNC__) #define __LOG4CXX_FUNC__ nullptr #endif #define LOG4CXX_LOCATION ::LOG4CXX_NS::spi::LocationInfo(__FILE__, \ ::LOG4CXX_NS::spi::LocationInfo::calcShortFileName(__FILE__), \ __LOG4CXX_FUNC__, \ __LINE__) #else #define LOG4CXX_LOCATION ::LOG4CXX_NS::spi::LocationInfo::getLocationUnavailable() #endif // LOG4CXX_LOCATION #endif //_LOG4CXX_SPI_LOCATION_LOCATIONINFO_H apache-log4cxx-1.3.1/src/main/include/log4cxx/spi/loggerrepository.h0000644000175100001770000001155614721727031025015 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_SPI_LOG_REPOSITORY_H #define _LOG4CXX_SPI_LOG_REPOSITORY_H #include #include #include #include #include namespace LOG4CXX_NS { namespace spi { /** 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. */ class LOG4CXX_EXPORT LoggerRepository : public virtual helpers::Object { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(LoggerRepository) #if 15 < LOG4CXX_ABI_VERSION BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(LoggerRepository) END_LOG4CXX_CAST_MAP() #endif virtual ~LoggerRepository() {} /** Add a {@link spi::HierarchyEventListener HierarchyEventListener} event to the repository. */ virtual void addHierarchyEventListener(const HierarchyEventListenerPtr& listener) = 0; #if 15 < LOG4CXX_ABI_VERSION /** * Remove a previously added HierarchyEventListener from the repository. * */ virtual void removeHierarchyEventListener(const spi::HierarchyEventListenerPtr& listener) = 0; #endif /** * Call \c configurator if not yet configured. */ virtual void ensureIsConfigured(std::function configurator) = 0; /** Is the repository disabled for a given level? The answer depends on the repository threshold and the level parameter. See also #setThreshold method. */ virtual bool isDisabled(int level) const = 0; /** Set the repository-wide threshold. All logging requests below the threshold are immediately dropped. By default, the threshold is set to Level::getAll() which has the lowest possible rank. */ virtual void setThreshold(const LevelPtr& level) = 0; /** Another form of {@link #setThreshold(const LevelPtr&) setThreshold} accepting a string parameter instead of a Level. */ virtual void setThreshold(const LogString& val) = 0; virtual void emitNoAppenderWarning(const Logger* logger) = 0; /** Get the repository-wide threshold. See setThreshold for an explanation. */ virtual LevelPtr getThreshold() const = 0; /** Retrieve the \c name Logger instance */ virtual LoggerPtr getLogger(const LogString& name) = 0; /** Retrieve the \c name Logger instance If a logger of that name already exists, then it will be returned. Otherwise, a new logger will be instantiated by the provided factory. @param name The name of the logger to retrieve. @param factory The factory that will make the new logger instance. */ virtual LoggerPtr getLogger(const LogString& name, const spi::LoggerFactoryPtr& factory) = 0; #if 15 < LOG4CXX_ABI_VERSION /** Remove the \c name Logger from the repository. Note: The \c name Logger must be retrieved from the repository \b after any subsequent configuration file change for the newly loaded settings to be used. @param name The logger to remove. @param ifNotUsed If true and use_count() indicates there are other references, do not remove the Logger and return false. @returns true if \c name Logger was removed from the repository. */ virtual bool removeLogger(const LogString& name, bool ifNotUsed = true) = 0; #endif virtual LoggerPtr getRootLogger() const = 0; virtual LoggerPtr exists(const LogString& name) = 0; virtual void shutdown() = 0; virtual LoggerList getCurrentLoggers() const = 0; virtual void fireAddAppenderEvent(const Logger* logger, const Appender* appender) {}; virtual void fireRemoveAppenderEvent(const Logger* logger, const Appender* appender) {}; virtual void resetConfiguration() = 0; virtual bool isConfigured() = 0; virtual void setConfigured(bool configured) = 0; }; // class LoggerRepository } // namespace spi } // namespace log4cxx #endif //_LOG4CXX_SPI_LOG_REPOSITORY_H apache-log4cxx-1.3.1/src/main/include/log4cxx/spi/rootlogger.h0000644000175100001770000000401214721727031023546 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_SPI_ROOT_LOGGER_H #define _LOG4CXX_SPI_ROOT_LOGGER_H #include namespace LOG4CXX_NS { namespace spi { /** RootLogger sits at the top of the logger hierachy. It is a regular logger except that it provides several guarantees.

First, it cannot be assigned a null level. Second, since root logger cannot have a parent, the #getEffectiveLevel method always returns the value of the level field without walking the hierarchy. */ class LOG4CXX_EXPORT RootLogger : public Logger { public: /** The root logger names itself as "root". However, the root logger cannot be retrieved by name. */ RootLogger(const LevelPtr& level); #if LOG4CXX_ABI_VERSION <= 15 [[ deprecated( "Pool is no longer required" ) ]] RootLogger(helpers::Pool& pool, const LevelPtr level); #endif ~RootLogger() {} /** Return the assigned level value without walking the logger hierarchy. */ virtual const LevelPtr& getEffectiveLevel() const; /** Setting a null value to the level of the root logger may have catastrophic results. We prevent this here. */ void setLevel(const LevelPtr level); }; } // namespace spi } // namespace log4cxx #endif //_LOG4CXX_SPI_ROOT_LOGGER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/spi/configurator.h0000644000175100001770000000406114721727031024071 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_SPI_CONFIGURATOR_H #define _LOG4CXX_SPI_CONFIGURATOR_H #include namespace LOG4CXX_NS { class File; namespace spi { enum class ConfigurationStatus{ Configured, NotConfigured, }; /** Implemented by classes capable of configuring log4j using a URL. */ class LOG4CXX_EXPORT Configurator : virtual public helpers::Object { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(Configurator) #if 15 < LOG4CXX_ABI_VERSION BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(Configurator) END_LOG4CXX_CAST_MAP() #endif /** Interpret a resource pointed by a URL and set up log4j accordingly. The configuration is done relative to the hierarchy parameter. @param configFileName The file to parse @param repository Where the Logger instances reside. */ virtual ConfigurationStatus doConfigure ( const File& configFileName #if LOG4CXX_ABI_VERSION <= 15 , spi::LoggerRepositoryPtr repository #else , const spi::LoggerRepositoryPtr& repository = spi::LoggerRepositoryPtr() #endif ) = 0; protected: Configurator(); private: Configurator(const Configurator&); Configurator& operator=(const Configurator&); }; LOG4CXX_PTR_DEF(Configurator); } } #endif // _LOG4CXX_SPI_CONFIGURATOR_H apache-log4cxx-1.3.1/src/main/include/log4cxx/spi/appenderattachable.h0000644000175100001770000000443414721727031025202 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_SPI_APPENDER_ATTACHABLE_H_ #define _LOG4CXX_SPI_APPENDER_ATTACHABLE_H_ #include #include #include namespace LOG4CXX_NS { namespace spi { /** * This Interface is for attaching Appenders to objects. */ class LOG4CXX_EXPORT AppenderAttachable : public virtual helpers::Object { public: // Methods DECLARE_ABSTRACT_LOG4CXX_OBJECT(AppenderAttachable) /** * Add an appender. */ virtual void addAppender(const AppenderPtr newAppender) = 0; /** * Get all previously added appenders as an AppenderList. */ virtual AppenderList getAllAppenders() const = 0; /** * Get an appender by name. */ virtual AppenderPtr getAppender(const LogString& name) const = 0; /** * Returns true if the specified appender is in list of * attached appenders, false otherwise. */ virtual bool isAttached(const AppenderPtr appender) const = 0; /** * Remove all previously added appenders. */ virtual void removeAllAppenders() = 0; /** * Remove the appender passed as parameter from the list of appenders. */ virtual void removeAppender(const AppenderPtr appender) = 0; /** * Remove the appender with the name passed as parameter from the * list of appenders. */ virtual void removeAppender(const LogString& name) = 0; // Dtor virtual ~AppenderAttachable() {} }; LOG4CXX_PTR_DEF(AppenderAttachable); } } #endif //_LOG4CXX_SPI_APPENDER_ATTACHABLE_H_ apache-log4cxx-1.3.1/src/main/include/log4cxx/spi/defaultrepositoryselector.h0000644000175100001770000000326114721727031026715 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_SPI_DEFAULT_REPOSITORY_SELECTOR_H #define _LOG4CXX_SPI_DEFAULT_REPOSITORY_SELECTOR_H #include #include #include #include namespace LOG4CXX_NS { namespace spi { class LOG4CXX_EXPORT DefaultRepositorySelector : public virtual RepositorySelector, public virtual helpers::Object { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(DefaultRepositorySelector) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(RepositorySelector) END_LOG4CXX_CAST_MAP() DefaultRepositorySelector(const LoggerRepositoryPtr repository1); ~DefaultRepositorySelector(); LoggerRepositoryPtr getLoggerRepository() override; private: LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(DefaultRepositorySelectorPrivate, m_priv) }; } // namespace spi } // namespace log4cxx #endif //_LOG4CXX_SPI_DEFAULT_REPOSITORY_SELECTOR_H apache-log4cxx-1.3.1/src/main/include/log4cxx/spi/optionhandler.h0000644000175100001770000000425614721727031024243 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_SPI_OPTION_HANDLER_H #define _LOG4CXX_SPI_OPTION_HANDLER_H #include #include namespace LOG4CXX_NS { namespace spi { class OptionHandler; typedef std::shared_ptr OptionHandlerPtr; /** A string based interface to configure package components. */ class LOG4CXX_EXPORT OptionHandler : public virtual helpers::Object { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(OptionHandler) virtual ~OptionHandler() {} /** Activate the options that were previously set with calls to option setters.

This allows to defer activiation of the options until all options have been set. This is required for components which have related options that remain ambigous until all are set.

For example, the FileAppender has the File and Append options both of which are ambigous until the other is also set. */ virtual void activateOptions(helpers::Pool& p) = 0; /** Set option to value.

The handling of each option depends on the OptionHandler instance. Some options may become active immediately whereas other may be activated only when #activateOptions is called. */ virtual void setOption(const LogString& option, const LogString& value) = 0; }; // class OptionConverter } // namespace spi } // namespace log4cxx #endif //_LOG4CXX_SPI_OPTION_HANDLER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/spi/repositoryselector.h0000644000175100001770000000347414721727031025356 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_SPI_REPOSITORY_SELECTOR_H #define _LOG4CXX_SPI_REPOSITORY_SELECTOR_H #include namespace LOG4CXX_NS { namespace spi { class LoggerRepository; typedef std::shared_ptr LoggerRepositoryPtr; /** The LogManager uses one (and only one) RepositorySelector implementation to select the {@link log4cxx::spi::LoggerRepository LoggerRepository} for a particular application context.

It is the responsability of the RepositorySelector implementation to track the application context. log4cxx makes no assumptions about the application context or on its management.

See also LogManager. */ class LOG4CXX_EXPORT RepositorySelector : public virtual helpers::Object { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(RepositorySelector) virtual ~RepositorySelector() {} virtual LoggerRepositoryPtr getLoggerRepository() = 0; }; LOG4CXX_PTR_DEF(RepositorySelector); } //namespace spi } //namespace log4cxx #endif //_LOG4CXX_SPI_REPOSITORY_SELECTOR_H apache-log4cxx-1.3.1/src/main/include/log4cxx/spi/triggeringeventevaluator.h0000644000175100001770000000323714721727031026521 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_SPI_TRIGGERING_EVENT_EVALUATOR_H #define _LOG4CXX_SPI_TRIGGERING_EVENT_EVALUATOR_H #include namespace LOG4CXX_NS { namespace spi { /** Implementions of this interface allow certain appenders to decide when to perform an appender specific action.

For example the {@link net::SMTPAppender SMTPAppender} sends an email when the #isTriggeringEvent method returns true and adds the event to an internal buffer when the returned result is false. */ class LOG4CXX_EXPORT TriggeringEventEvaluator : public virtual helpers::Object { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(TriggeringEventEvaluator) /** Is this the triggering event? */ virtual bool isTriggeringEvent(const spi::LoggingEventPtr& event) = 0; }; LOG4CXX_PTR_DEF(TriggeringEventEvaluator); } } #endif // _LOG4CXX_SPI_TRIGGERING_EVENT_EVALUATOR_H apache-log4cxx-1.3.1/src/main/include/log4cxx/spi/errorhandler.h0000644000175100001770000000723714721727031024066 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_SPI_ERROR_HANDLER_H #define _LOG4CXX_SPI_ERROR_HANDLER_H #include #include #include #include namespace LOG4CXX_NS { namespace spi { class ErrorCode { public: enum { GENERIC_FAILURE = 0, WRITE_FAILURE = 1, FLUSH_FAILURE = 2, CLOSE_FAILURE = 3, FILE_OPEN_FAILURE = 4, MISSING_LAYOUT = 5, ADDRESS_PARSE_FAILURE = 6 }; }; /** Appenders may delegate their error handling to ErrorHandlers.

Error handling is a particularly tedious to get right because by definition errors are hard to predict and to reproduce.

Please take the time to contact the author in case you discover that errors are not properly handled. You are most welcome to suggest new error handling policies or criticize existing policies. */ class LOG4CXX_EXPORT ErrorHandler : public virtual OptionHandler { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(ErrorHandler) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(ErrorHandler) LOG4CXX_CAST_ENTRY(OptionHandler) END_LOG4CXX_CAST_MAP() virtual ~ErrorHandler() {} /** Add a reference to a logger to which the failing appender might be attached to. The failing appender will be searched and replaced only in the loggers you add through this method. @param logger One of the loggers that will be searched for the failing appender in view of replacement. */ virtual void setLogger(const LoggerPtr& logger) = 0; /** Equivalent to the error(const String&, helpers::Exception&, int, spi::LoggingEvent&) with the the event parameteter set to null. */ virtual void error(const LogString& message, const std::exception& e, int errorCode) const = 0; /** This method is normally used to just print the error message passed as a parameter. */ virtual void error(const LogString& message) const = 0; /** This method is invoked to handle the error. @param message The message assoicated with the error. @param e The Exption that was thrown when the error occured. @param errorCode The error code associated with the error. @param event The logging event that the failing appender is asked to log. */ virtual void error(const LogString& message, const std::exception& e, int errorCode, const LoggingEventPtr& event) const = 0; /** Set the appender for which errors are handled. This method is usually called when the error handler is configured. */ virtual void setAppender(const AppenderPtr& appender) = 0; /** Set the appender to fallback upon in case of failure. */ virtual void setBackupAppender(const AppenderPtr& appender) = 0; #if 15 < LOG4CXX_ABI_VERSION /** Has an error been reported? */ virtual bool errorReported() const = 0; #endif }; LOG4CXX_PTR_DEF(ErrorHandler); } //namespace spi } //namespace log4cxx #endif //_LOG4CXX_SPI_ERROR_HANDLER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/spi/loggingevent.h0000644000175100001770000001461514721727031024065 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_SPI_LOGGING_EVENT_H #define _LOG4CXX_SPI_LOGGING_EVENT_H #include #include #include #include #include #include #include namespace LOG4CXX_NS { namespace spi { LOG4CXX_LIST_DEF(KeySet, LogString); /** The data recorded for each logging request. Each logging request instantiates a LoggingEvent instance, which Log4cxx provides to [filters](@ref log4cxx.spi.Filter), [layouts](@ref log4cxx.Layout) and [appenders](@ref log4cxx.Appender).

This class is of concern to those wishing to extend log4cxx. */ class LOG4CXX_EXPORT LoggingEvent : public virtual helpers::Object { public: DECLARE_LOG4CXX_OBJECT(LoggingEvent) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(LoggingEvent) END_LOG4CXX_CAST_MAP() typedef spi::KeySet KeySet; /** An empty event. */ LoggingEvent(); /** An event composed using the supplied parameters. @param logger The logger used to make the logging request. @param level The severity of this event. @param location The source code location of the logging request. @param message The text to add to this event. */ LoggingEvent ( const LogString& logger , const LevelPtr& level , const LocationInfo& location , LogString&& message ); /** An event composed using the supplied parameters. @param logger The logger used to make the logging request. @param level The severity of this event. @param message The text to add to this event. @param location The source code location of the logging request. */ LoggingEvent ( const LogString& logger , const LevelPtr& level , const LogString& message , const LocationInfo& location ); ~LoggingEvent(); /** The severity level of the logging request that generated this event. */ const LevelPtr& getLevel() const; /** The name of the logger used to make the logging request. */ const LogString& getLoggerName() const; /** The message provided in the logging request. */ const LogString& getMessage() const; /** The message provided in the logging request. */ const LogString& getRenderedMessage() const; /** The number of microseconds elapsed since 1970-01-01 * at the time the application started. */ static log4cxx_time_t getStartTime(); /** The identity of the thread in which this logging event was created. */ const LogString& getThreadName() const; /** * The name you gave to the thread in which this logging event was created. * You can create a named thread using log4cxx::helpers::ThreadUtility::createThread. * If Log4cxx is unable to retrieve the thread name using a platform-specific call, * the value is the same as the thread identity. */ const LogString& getThreadUserName() const; /** The number of microseconds elapsed since 1970-01-01 * at the time this logging event was created. */ log4cxx_time_t getTimeStamp() const; /** The value of the system clock at the time this logging event was created. */ std::chrono::time_point getChronoTimeStamp() const; /** The source code location where the logging request was made. */ const LocationInfo& getLocationInformation() const; /** * Add the current nested diagnostic context to the end of \c dest. * The diagnostic context must have been loaded into this LoggingEvent using LoadDC, * to obtain the correct content if the event was generated in a different thread. * * @param dest the string to be added to. * @return true if \c dest is changed. */ bool getNDC(LogString& dest) const; /** * Add the value associated with \c key to the end of \c dest. * The diagnostic context must have been loaded into this LoggingEvent using LoadDC, * to obtain the correct content if the event was generated in a different thread. * * @param key mapped diagnostic context key value. * @param dest the string to be added to. * @return true if \c dest is changed. */ bool getMDC(const LogString& key, LogString& dest) const; /** * The keys in the mapped diagnostic context for the event. * * @return the mapped diagnostic context keys. * */ KeySet getMDCKeySet() const; #if LOG4CXX_ABI_VERSION <= 15 /** Obtain a copy of the current thread's diagnostic context data. */ [[ deprecated( "Use LoadDC instead" ) ]] void getMDCCopy() const; #endif /** * Obtain a copy of the current thread's diagnostic context data. * The diagnostic context must be loaded to ensure the * correct diagnostic context data is available * when the event is stored for later use * (for example, when the appender uses a different thread to process this event). */ void LoadDC() const; /** * Append onto \c dest the value associated with the property \c key. * @param key the property name. * @param dest the string onto which to associated value is appended. * @return true if \c dest was changed. */ bool getProperty(const LogString& key, LogString& dest) const; /** * The set of of the key values in the properties * for the event. * @return the keys from properties in this event. */ KeySet getPropertyKeySet() const; /** * Associate \c value with the property \c key. */ void setProperty(const LogString& key, const LogString& value); private: LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(LoggingEventPrivate, m_priv) // // prevent copy and assignment // LoggingEvent(const LoggingEvent&); LoggingEvent& operator=(const LoggingEvent&); }; LOG4CXX_PTR_DEF(LoggingEvent); LOG4CXX_LIST_DEF(LoggingEventList, LoggingEventPtr); } } #endif //_LOG4CXX_SPI_LOGGING_EVENT_H apache-log4cxx-1.3.1/src/main/include/log4cxx/spi/filter.h0000644000175100001770000001025014721727031022651 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_SPI_FILTER_H #define _LOG4CXX_SPI_FILTER_H #include #include #include namespace LOG4CXX_NS { namespace spi { class Filter; LOG4CXX_PTR_DEF(Filter); /** Users should extend this class to implement customized logging event filtering. Note that Logger and AppenderSkeleton, the parent class of all standard appenders, have built-in filtering rules. It is suggested that you first use and understand the built-in rules before rushing to write your own custom filters.

This abstract class assumes and also imposes that filters be organized in a linear chain. The {@link #decide decide(LoggingEvent)} method of each filter is called sequentially, in the order of their addition to the chain.

The {@link #decide decide(LoggingEvent)} method must return one of the integer constants #DENY, #NEUTRAL or #ACCEPT.

If the value #DENY is returned, then the log event is dropped immediately without consulting with the remaining filters.

If the value #NEUTRAL is returned, then the next filter in the chain is consulted. If there are no more filters in the chain, then the log event is logged. Thus, in the presence of no filters, the default behaviour is to log all logging events.

If the value #ACCEPT is returned, then the log event is logged without consulting the remaining filters.

The philosophy of log4cxx filters is largely inspired from the Linux ipchains.

Note that filtering is only supported by the DOMConfigurator. */ class LOG4CXX_EXPORT Filter : public virtual OptionHandler { protected: LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(FilterPrivate, m_priv) public: Filter(); Filter(std::unique_ptr priv); virtual ~Filter(); DECLARE_ABSTRACT_LOG4CXX_OBJECT(Filter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(Filter) LOG4CXX_CAST_ENTRY(spi::OptionHandler) END_LOG4CXX_CAST_MAP() LOG4CXX_NS::spi::FilterPtr getNext() const; void setNext(const LOG4CXX_NS::spi::FilterPtr& newNext); enum FilterDecision { /** The log event must be dropped immediately without consulting with the remaining filters, if any, in the chain. */ DENY = -1, /** This filter is neutral with respect to the log event. The remaining filters, if any, should be consulted for a final decision. */ NEUTRAL = 0, /** The log event must be logged immediately without consulting with the remaining filters, if any, in the chain. */ ACCEPT = 1 }; /** \copybrief spi::OptionHandler::activateOptions() No action is performed in this implementation. */ void activateOptions(helpers::Pool& p) override; /** \copybrief spi::OptionHandler::setOption() Supported options | Supported values | Default value -------------- | ---------------- | --------------- - | - | - */ void setOption(const LogString& option, const LogString& value) override; /**

If the decision is DENY, then the event will be dropped. If the decision is NEUTRAL, then the next filter, if any, will be invoked. If the decision is ACCEPT then the event will be logged without consulting with other filters in the chain. @param event The LoggingEvent to decide upon. @return The decision of the filter. */ virtual FilterDecision decide(const LoggingEventPtr& event) const = 0; }; } } #endif //_LOG4CXX_SPI_FILTER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/simplelayout.h0000644000175100001770000000461514721727031023330 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_SIMPLE_LAYOUT_H #define _LOG4CXX_SIMPLE_LAYOUT_H #include namespace LOG4CXX_NS { /** SimpleLayout consists of the level of the log statement, followed by " - " and then the log message itself. For example,

        DEBUG - Hello world

PatternLayout offers a much more powerful alternative. */ class LOG4CXX_EXPORT SimpleLayout : public Layout { public: DECLARE_LOG4CXX_OBJECT(SimpleLayout) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(SimpleLayout) LOG4CXX_CAST_ENTRY_CHAIN(Layout) END_LOG4CXX_CAST_MAP() /** Returns the log statement in a format consisting of the level, followed by " - " and then the message. For example,

 INFO - "A message"
		
*/ void format(LogString& output, const spi::LoggingEventPtr& event, helpers::Pool& pool) const override; /** The SimpleLayout does not handle the throwable contained within {@link spi::LoggingEvent LoggingEvents}. Thus, it returns true. */ bool ignoresThrowable() const override { return true; } /** \copybrief spi::OptionHandler::activateOptions() No action is performed in this implementation. */ void activateOptions(helpers::Pool& /* p */) override {} /** \copybrief spi::OptionHandler::setOption() Supported options | Supported values | Default value -------------- | ---------------- | --------------- - | - | - */ void setOption(const LogString& /* option */, const LogString& /* value */) override {} }; LOG4CXX_PTR_DEF(SimpleLayout); } // namespace log4cxx #endif //_LOG4CXX_SIMPLE_LAYOUT_H apache-log4cxx-1.3.1/src/main/include/log4cxx/rolling/0000755000175100001770000000000014721727031022070 5ustar runnerdockerapache-log4cxx-1.3.1/src/main/include/log4cxx/rolling/rollingpolicy.h0000644000175100001770000000564614721727031025142 0ustar runnerdocker/* * 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. */ #if !defined(_LOG4CXX_ROLLING_ROLLING_POLICY_H) #define _LOG4CXX_ROLLING_ROLLING_POLICY_H #include #include #include namespace LOG4CXX_NS { namespace rolling { /** * A RollingPolicy is responsible for performing the * rolling over of the active log file. The RollingPolicy * is also responsible for providing the active log file, * that is the live file where logging output will be directed. * * * * */ class LOG4CXX_EXPORT RollingPolicy : public virtual spi::OptionHandler { DECLARE_ABSTRACT_LOG4CXX_OBJECT(RollingPolicy) public: virtual ~RollingPolicy() {} /** * Initialize the policy and return any initial actions for rolling file appender. * * @param currentActiveFile current value of RollingFileAppender.getFile(). * @param append current value of RollingFileAppender.getAppend(). * @param pool pool for memory allocations during call. * @return Description of the initialization, may be null to indicate * no initialization needed. * @throws SecurityException if denied access to log files. */ virtual RolloverDescriptionPtr initialize( const LogString& currentActiveFile, const bool append, LOG4CXX_NS::helpers::Pool& pool) = 0; /** * 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 currentActiveFile file name for current active log file. * @param append current value of the parent FileAppender.getAppend(). * @param pool pool for memory allocations during call. * @return Description of pending rollover, may be null to indicate no rollover * at this time. * @throws SecurityException if denied access to log files. */ virtual RolloverDescriptionPtr rollover( const LogString& currentActiveFile, const bool append, LOG4CXX_NS::helpers::Pool& pool) = 0; }; LOG4CXX_PTR_DEF(RollingPolicy); } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/rolling/zipcompressaction.h0000644000175100001770000000420214721727031026013 0ustar runnerdocker/* * 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. */ #if !defined(_LOG4CXX_ROLLING_ZIP_COMPRESS_ACTION_H) #define _LOG4CXX_ROLLING_ZIP_COMPRESS_ACTION_H #include #include namespace LOG4CXX_NS { namespace rolling { class ZipCompressAction : public Action { struct ZipCompressActionPrivate; public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(ZipCompressAction) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(ZipCompressAction) LOG4CXX_CAST_ENTRY_CHAIN(Action) END_LOG4CXX_CAST_MAP() /** * Constructor. */ ZipCompressAction(const File& source, const File& destination, bool deleteSource); /** * Perform action. * * @return true if successful. */ bool execute(LOG4CXX_NS::helpers::Pool& pool) const override; /** * Set to true to throw an IOException on a fork failure. By default, this * is true. When an IOException is thrown, this will automatically cause the * error handler to be called(which is the recommended way of handling this * problem). By setting this to false, the ZipCompressAction effectively * turns into a FileRenameAction if any errors are encountered. * * @param throwIO */ void setThrowIOExceptionOnForkFailure(bool throwIO); private: ZipCompressAction(const ZipCompressAction&); ZipCompressAction& operator=(const ZipCompressAction&); }; LOG4CXX_PTR_DEF(ZipCompressAction); } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/rolling/rollingpolicybase.h0000644000175100001770000000742114721727031025766 0ustar runnerdocker/* * 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. */ #if !defined(_LOG4CXX_ROLLING_ROLLING_POLICY_BASE_H) #define _LOG4CXX_ROLLING_ROLLING_POLICY_BASE_H #include #include #include #include #include #include #include namespace LOG4CXX_NS { namespace rolling { LOG4CXX_LIST_DEF(PatternConverterList, LOG4CXX_NS::pattern::PatternConverterPtr); LOG4CXX_LIST_DEF(FormattingInfoList, LOG4CXX_NS::pattern::FormattingInfoPtr); /** * Implements methods common to most, it not all, rolling * policies. * * * */ class LOG4CXX_EXPORT RollingPolicyBase : public virtual RollingPolicy, public virtual helpers::Object { protected: DECLARE_ABSTRACT_LOG4CXX_OBJECT(RollingPolicyBase) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(RollingPolicy) LOG4CXX_CAST_ENTRY(spi::OptionHandler) END_LOG4CXX_CAST_MAP() LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(RollingPolicyBasePrivate, m_priv) public: RollingPolicyBase(); virtual ~RollingPolicyBase(); /** \copybrief RollingPolicy::activateOptions() Logs a warning if FileNamePattern is not set. \sa RollingPolicy::activateOptions() */ void activateOptions(helpers::Pool& p) override; /** A map from a name to the object implementing the (date or index) formatting. */ virtual pattern::PatternMap getFormatSpecifiers() const = 0; /** \copybrief spi::OptionHandler::setOption() Supported options | Supported values | Default value :-------------- | :----------------: | :---------------: FileNamePattern | (\ref legalChars "^") | - CreateIntermediateDirectories | True,False | False \anchor legalChars (^) Legal file name characters plus any conversion specifier supported by the concrete class. \sa getFormatSpecifiers() */ void setOption(const LogString& option, const LogString& value) override; /** * Set file name pattern. * @param fnp file name pattern. */ void setFileNamePattern(const LogString& fnp); /** * Get file name pattern. * @return file name pattern. */ LogString getFileNamePattern() const; bool getCreateIntermediateDirectories() const; void setCreateIntermediateDirectories(bool createIntermediate); PatternConverterList getPatternConverterList() const; protected: RollingPolicyBase(LOG4CXX_PRIVATE_PTR(RollingPolicyBasePrivate) priv); /** * Parse file name pattern. */ void parseFileNamePattern(); /** * 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. * @param p memory pool. */ void formatFileName(const helpers::ObjectPtr& obj, LogString& buf, helpers::Pool& p) const; LOG4CXX_NS::pattern::PatternConverterPtr getIntegerPatternConverter() const; LOG4CXX_NS::pattern::PatternConverterPtr getDatePatternConverter() const; }; LOG4CXX_PTR_DEF(RollingPolicyBase); } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/rolling/action.h0000644000175100001770000000354714721727031023527 0ustar runnerdocker/* * 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. */ #if !defined(_LOG4CXX_ROLLING_ACTION_H) #define _LOG4CXX_ROLLING_ACTION_H #include #include #include #include namespace LOG4CXX_NS { namespace rolling { /** * A file system action performed as part of a rollover event. */ class Action : public virtual LOG4CXX_NS::helpers::Object { DECLARE_ABSTRACT_LOG4CXX_OBJECT(Action) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(Action) END_LOG4CXX_CAST_MAP() LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(ActionPrivate, m_priv) protected: /** * Constructor. */ Action(); Action(LOG4CXX_PRIVATE_PTR(ActionPrivate) priv); virtual ~Action(); public: /** * Perform action. * * @return true if successful. */ virtual bool execute(LOG4CXX_NS::helpers::Pool& pool) const = 0; void run(LOG4CXX_NS::helpers::Pool& pool); void close(); /** * Tests if the action is complete. * @return true if action is complete. */ bool isComplete() const; void reportException(const std::exception&); }; LOG4CXX_PTR_DEF(Action); } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/rolling/rolloverdescription.h0000644000175100001770000000500314721727031026347 0ustar runnerdocker/* * 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. */ #if !defined(_LOG4CXX_ROLLING_ROLLOVER_DESCRIPTION_H) #define _LOG4CXX_ROLLING_ROLLOVER_DESCRIPTION_H #include namespace LOG4CXX_NS { namespace rolling { class RolloverDescription : public LOG4CXX_NS::helpers::Object { DECLARE_LOG4CXX_OBJECT(RolloverDescription) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(RolloverDescription) END_LOG4CXX_CAST_MAP() LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(RolloverDescriptionPrivate, m_priv) public: RolloverDescription(); /** * 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. */ RolloverDescription( const LogString& activeFileName, const bool append, const ActionPtr& synchronous, const ActionPtr& asynchronous); ~RolloverDescription(); /** * Active log file name after rollover. * @return active log file name after rollover. */ LogString getActiveFileName() const; bool getAppend() const; /** * Action to be completed after close of current active log file * before returning control to caller. * * @return action, may be null. */ ActionPtr getSynchronous() const; /** * 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. */ ActionPtr getAsynchronous() const; }; LOG4CXX_PTR_DEF(RolloverDescription); } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/rolling/filterbasedtriggeringpolicy.h0000644000175100001770000000644114721727031030034 0ustar runnerdocker/* * 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. */ #if !defined(_LOG4CXX_ROLLING_FILTER_BASED_TRIGGERING_POLICY_H) #define _LOG4CXX_ROLLING_FILTER_BASED_TRIGGERING_POLICY_H #include #include // Instantiate template pointer types passed as parameters LOG4CXX_INSTANTIATE_EXPORTED_PTR(LOG4CXX_NS::spi::Filter); namespace LOG4CXX_NS { class File; namespace helpers { class Pool; } namespace rolling { /** * 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. * * * * */ class LOG4CXX_EXPORT FilterBasedTriggeringPolicy : public TriggeringPolicy { DECLARE_LOG4CXX_OBJECT(FilterBasedTriggeringPolicy) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(FilterBasedTriggeringPolicy) LOG4CXX_CAST_ENTRY_CHAIN(TriggeringPolicy) END_LOG4CXX_CAST_MAP() LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(FilterBasedTriggeringPolicyPrivate, m_priv) public: /** * Creates a new FilterBasedTriggeringPolicy. */ FilterBasedTriggeringPolicy(); virtual ~FilterBasedTriggeringPolicy(); /** * 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. */ bool isTriggeringEvent( Appender* appender, const spi::LoggingEventPtr& event, const LogString& filename, size_t fileLength) override; /** * Add a filter to end of the filter list. * @param newFilter filter to add to end of list. */ void addFilter(const spi::FilterPtr& newFilter); /** * Clear the filters chain. * */ void clearFilters(); /** * Returns the head Filter. * */ spi::FilterPtr& getFilter(); /** \copybrief spi::OptionHandler::activateOptions() Activates all attached filters. */ void activateOptions(helpers::Pool&) override; /** \copybrief spi::OptionHandler::setOption() Supported options | Supported values | Default value -------------- | ---------------- | --------------- - | - | - */ void setOption(const LogString& option, const LogString& value) override; }; LOG4CXX_PTR_DEF(FilterBasedTriggeringPolicy); } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/rolling/multiprocessrollingfileappender.h0000644000175100001770000001101414721727031030735 0ustar runnerdocker/* * 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. */ #if !defined(LOG4CXX_ROLLING_MULTIPROCESS_ROLLING_FILE_APPENDER_H) #define LOG4CXX_ROLLING_MULTIPROCESS_ROLLING_FILE_APPENDER_H #include #include #include #include #include #include namespace LOG4CXX_NS { namespace rolling { /** * A special version of the RollingFileAppender that acts properly with multiple processes */ class LOG4CXX_EXPORT MultiprocessRollingFileAppender : public FileAppender { DECLARE_LOG4CXX_OBJECT(MultiprocessRollingFileAppender) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(MultiprocessRollingFileAppender) LOG4CXX_CAST_ENTRY_CHAIN(FileAppender) END_LOG4CXX_CAST_MAP() protected: struct MultiprocessRollingFileAppenderPriv; public: MultiprocessRollingFileAppender(); /** \copybrief FileAppender::activateOptions() Activate the attached TriggeringPolicy and RollingPolicy. \sa FileAppender::activateOptions() */ void activateOptions(helpers::Pool&) override; /** 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. */ bool rollover(helpers::Pool& p); protected: /** Actual writing occurs here. */ void subAppend(const spi::LoggingEventPtr& event, helpers::Pool& p) override; bool rolloverInternal(LOG4CXX_NS::helpers::Pool& p); public: RollingPolicyPtr getRollingPolicy() const; TriggeringPolicyPtr getTriggeringPolicy() const; /** * Sets the rolling policy. In case the 'policy' argument also implements * {@link TriggeringPolicy}, then the triggering policy for this appender * is automatically set to be the policy argument. * @param policy */ void setRollingPolicy(const RollingPolicyPtr& policy); void setTriggeringPolicy(const TriggeringPolicyPtr& policy); public: /** * Close appender. Waits for any asynchronous file compression actions to be completed. */ void close() override; protected: /** 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. */ helpers::WriterPtr createWriter(helpers::OutputStreamPtr& os) override; public: /** * Get byte length of current active log file. * @return byte length of current active log file. */ size_t getFileLength() const; /** * Increments estimated byte length of current active log file. * @param increment additional bytes written to log file. */ void incrementFileLength(size_t increment); private: /** * Set byte length of current active log file. * @return void */ void setFileLength(size_t length); /** * Release the file lock * @return void */ void releaseFileLock(apr_file_t* lock_file); /** * re-open the latest file when its own handler has been renamed * @return void */ void reopenLatestFile(LOG4CXX_NS::helpers::Pool& p); friend class CountingOutputStream; }; LOG4CXX_PTR_DEF(MultiprocessRollingFileAppender); } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/rolling/fixedwindowrollingpolicy.h0000644000175100001770000001110114721727031027371 0ustar runnerdocker/* * 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. */ #if !defined(_LOG4CXX_ROLLING_FIXED_WINDOW_ROLLING_POLICY_H) #define _LOG4CXX_ROLLING_FIXED_WINDOW_ROLLING_POLICY_H #include namespace LOG4CXX_NS { namespace helpers { class Pool; } namespace rolling { /** * 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" somwhere * 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. * * * * * */ class LOG4CXX_EXPORT FixedWindowRollingPolicy : public RollingPolicyBase { DECLARE_LOG4CXX_OBJECT(FixedWindowRollingPolicy) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(FixedWindowRollingPolicy) LOG4CXX_CAST_ENTRY_CHAIN(RollingPolicyBase) END_LOG4CXX_CAST_MAP() struct FixedWindowRollingPolicyPrivate; /** * It's almost always a bad idea to have a large window size, say over 12. */ enum { MAX_WINDOW_SIZE = 12 }; bool purge(int purgeStart, int maxIndex, LOG4CXX_NS::helpers::Pool& p) const; public: FixedWindowRollingPolicy(); ~FixedWindowRollingPolicy(); /** \copybrief RollingPolicyBase::activateOptions() Logs a warning if an option is not valid. \sa RollingPolicyBase::activateOptions() */ void activateOptions(helpers::Pool& p) override; /** \copybrief RollingPolicyBase::setOption() Supported options | Supported values | Default value :-------------- | :----------------: | :---------------: MinIndex | 1-12 | 1 MaxIndex | 1-12 | 7 ThrowIOExceptionOnForkFailure | True,False | True \sa RollingPolicyBase::setOption() */ void setOption(const LogString& option, const LogString& value) override; void rollover(); int getMaxIndex() const; int getMinIndex() const; void setMaxIndex(int newVal); void setMinIndex(int newVal); /** * {@inheritDoc} */ RolloverDescriptionPtr initialize( const LogString& currentActiveFile, const bool append, helpers::Pool& pool) override; /** * {@inheritDoc} */ RolloverDescriptionPtr rollover( const LogString& currentActiveFile, const bool append, helpers::Pool& pool) override; protected: /** * A map from "i" and "index" to a integer conversion formatter. * * \sa IntegerPatternConverter */ LOG4CXX_NS::pattern::PatternMap getFormatSpecifiers() const override; }; LOG4CXX_PTR_DEF(FixedWindowRollingPolicy); } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/rolling/filerenameaction.h0000644000175100001770000000306014721727031025545 0ustar runnerdocker/* * 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. */ #if !defined(_LOG4CXX_ROLLING_FILE_RENAME_ACTION_H) #define _LOG4CXX_ROLLING_FILE_RENAME_ACTION_H #include #include namespace LOG4CXX_NS { namespace rolling { class FileRenameAction : public Action { struct FileRenameActionPrivate; public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(FileRenameAction) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(FileRenameAction) LOG4CXX_CAST_ENTRY_CHAIN(Action) END_LOG4CXX_CAST_MAP() /** * Constructor. */ FileRenameAction(const File& toRename, const File& renameTo, bool renameEmptyFile); /** * Perform action. * * @return true if successful. */ bool execute(LOG4CXX_NS::helpers::Pool& pool) const override; }; LOG4CXX_PTR_DEF(FileRenameAction); } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/rolling/manualtriggeringpolicy.h0000644000175100001770000000474114721727031027026 0ustar runnerdocker/* * 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. */ #if !defined(_LOG4CXX_ROLLING_MANUAL_TRIGGERING_POLICY_H) #define _LOG4CXX_ROLLING_MANUAL_TRIGGERING_POLICY_H #include namespace LOG4CXX_NS { class File; namespace helpers { class Pool; } namespace rolling { /** * ManualTriggeringPolicy only rolls over on explicit calls to * RollingFileAppender.rollover(). * * * */ class LOG4CXX_EXPORT ManualTriggeringPolicy : public TriggeringPolicy { DECLARE_LOG4CXX_OBJECT(ManualTriggeringPolicy) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(ManualTriggeringPolicy) LOG4CXX_CAST_ENTRY_CHAIN(TriggeringPolicy) END_LOG4CXX_CAST_MAP() public: ManualTriggeringPolicy(); /** * 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. */ bool isTriggeringEvent( Appender* appender, const spi::LoggingEventPtr& event, const LogString& filename, size_t fileLength) override; /** \copybrief spi::OptionHandler::activateOptions() No action is performed in this implementation. */ void activateOptions(helpers::Pool&) override; /** \copybrief spi::OptionHandler::setOption() Supported options | Supported values | Default value -------------- | ---------------- | --------------- - | - | - */ void setOption(const LogString& option, const LogString& value) override; }; } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/rolling/rollingfileappender.h0000644000175100001770000002021014721727031026261 0ustar runnerdocker/* * 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. */ #if !defined(_LOG4CXX_ROLLING_ROLLING_FILE_APPENDER_H) #define _LOG4CXX_ROLLING_ROLLING_FILE_APPENDER_H #include #include #include #include #include #include namespace LOG4CXX_NS { namespace rolling { /** * RollingFileAppender extends {@link log4cxx::FileAppender} to backup the log files * depending on {@link log4cxx::rolling::RollingPolicy RollingPolicy} and {@link log4cxx::rolling::TriggeringPolicy 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 log4cxx::rolling::TimeBasedRollingPolicy TimeBasedRollingPolicy} acts both as a * RollingPolicy and a TriggeringPolicy. * *

RollingFileAppender can be configured programattically or * using {@link log4cxx::xml::DOMConfigurator}. 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. * * * * * */ class LOG4CXX_EXPORT RollingFileAppender : public FileAppender { DECLARE_LOG4CXX_OBJECT(RollingFileAppender) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(RollingFileAppender) LOG4CXX_CAST_ENTRY_CHAIN(FileAppender) END_LOG4CXX_CAST_MAP() protected: struct RollingFileAppenderPriv; public: RollingFileAppender(); /** Returns the value of the MaxBackupIndex option. */ int getMaxBackupIndex() const; /** Get the maximum size that the output file is allowed to reach before being rolled over to backup files. */ size_t getMaximumFileSize() const; /** Set the maximum number of backup files to keep around.

The MaxBackupIndex option determines how many backup files are kept before the oldest is erased. This option takes a positive integer value. If set to zero, then there will be no backup files and the log file will be truncated when it reaches MaxFileSize. */ void setMaxBackupIndex( int maxBackupIndex ); /** Set the maximum size that the output file is allowed to reach before being rolled over to backup files.

In configuration files, the MaxFileSize option takes an long integer in the range 0 - 2^63. You can specify the value with the suffixes "KB", "MB" or "GB" so that the integer is interpreted being expressed respectively in kilobytes, megabytes or gigabytes. For example, the value "10KB" will be interpreted as 10240. */ void setMaxFileSize( const LogString& value ); void setMaximumFileSize( size_t value ); /** The DatePattern takes a string in the same format as expected by {@link log4cxx::helpers::SimpleDateFormat SimpleDateFormat}. This options determines the rollover schedule. */ void setDatePattern(const LogString& pattern); LogString makeFileNamePattern(const LogString& datePattern); /** \copybrief FileAppender::setOption() Supported options | Supported values | Default value :-------------- | :----------------: | :---------------: FileDatePattern | (\ref dateChars "1") | - MaxBackupIndex | 1-12 | 0 MaxFileSize | (\ref fileSz "2") | 10 MB \anchor dateChars (1) A pattern compatible with java.text.SimpleDateFormat, "ABSOLUTE", "DATE" or "ISO8601". For example, "HH:mm:ss,SSS", "dd MMM yyyy HH:mm:ss,SSS" or "DATE". \anchor fileSz (2) An integer in the range 0 - 2^63. You can specify the value with the suffixes "KB", "MB" or "GB" so that the integer is interpreted being expressed respectively in kilobytes, megabytes or gigabytes. For example, the value "10KB" will be interpreted as 10240. \sa FileAppender::setOption() */ void setOption( const LogString& option, const LogString& value ) override; /** \copybrief FileAppender::activateOptions() \sa FileAppender::activateOptions() */ void activateOptions(helpers::Pool& pool ) override; /** Implements the configured 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. */ bool rollover(LOG4CXX_NS::helpers::Pool& p); protected: /** Actual writing occurs here. */ void subAppend(const spi::LoggingEventPtr& event, helpers::Pool& p) override; bool rolloverInternal(LOG4CXX_NS::helpers::Pool& p); public: /** * The policy that implements the scheme for rolling over a log file. */ RollingPolicyPtr getRollingPolicy() const; /** * The policy that determine when to trigger a log file rollover. */ TriggeringPolicyPtr getTriggeringPolicy() const; /** * Use \c policy as the scheme for rolling over log files. * * Where the \c policy also implements * {@link TriggeringPolicy}, then \c policy * will be used to determine when to trigger a log file rollover. */ void setRollingPolicy(const RollingPolicyPtr& policy); /** * Use \c policy to determine when to trigger a log file rollover. */ void setTriggeringPolicy(const TriggeringPolicyPtr& policy); public: /** * Close appender. Waits for any asynchronous file compression actions to be completed. */ void close() override; protected: /** 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. */ helpers::WriterPtr createWriter(helpers::OutputStreamPtr& os) override; public: /** * Get byte length of current active log file. * @return byte length of current active log file. */ size_t getFileLength() const; /** * Increments estimated byte length of current active log file. * @param increment additional bytes written to log file. */ void incrementFileLength(size_t increment); }; LOG4CXX_PTR_DEF(RollingFileAppender); } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/rolling/sizebasedtriggeringpolicy.h0000644000175100001770000000567414721727031027530 0ustar runnerdocker/* * 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. */ #if !defined(_LOG4CXX_ROLLING_SIZE_BASED_TRIGGERING_POLICY_H) #define _LOG4CXX_ROLLING_SIZE_BASED_TRIGGERING_POLICY_H #include namespace LOG4CXX_NS { class File; namespace helpers { class Pool; } namespace rolling { /** * SizeBasedTriggeringPolicy looks at size of the file being * currently written to. * * * */ class LOG4CXX_EXPORT SizeBasedTriggeringPolicy : public TriggeringPolicy { DECLARE_LOG4CXX_OBJECT(SizeBasedTriggeringPolicy) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(SizeBasedTriggeringPolicy) LOG4CXX_CAST_ENTRY_CHAIN(TriggeringPolicy) END_LOG4CXX_CAST_MAP() protected: size_t maxFileSize; public: SizeBasedTriggeringPolicy(); /** * 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. */ bool isTriggeringEvent( Appender* appender, const spi::LoggingEventPtr& event, const LogString& filename, size_t fileLength) override; size_t getMaxFileSize(); void setMaxFileSize(size_t l); /** \copybrief spi::OptionHandler::activateOptions() No action is performed in this implementation. */ void activateOptions(helpers::Pool&) override; /** \copybrief spi::OptionHandler::setOption() Supported options | Supported values | Default value -------------- | ---------------- | --------------- MaxFileSize | (\ref fileSize "1") | 10 MB \anchor fileSize (1) An integer in the range 0 - 2^63. You can specify the value with the suffixes "KB", "MB" or "GB" so that the integer is interpreted being expressed respectively in kilobytes, megabytes or gigabytes. For example, the value "10KB" will be interpreted as 10240. */ void setOption(const LogString& option, const LogString& value) override; }; LOG4CXX_PTR_DEF(SizeBasedTriggeringPolicy); } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/rolling/gzcompressaction.h0000644000175100001770000000421414721727031025634 0ustar runnerdocker/* * 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. */ #if !defined(_LOG4CXX_ROLLING_GZ_COMPRESS_ACTION_H) #define _LOG4CXX_ROLLING_GZ_COMPRESS_ACTION_H #include #include namespace LOG4CXX_NS { namespace rolling { class GZCompressAction : public Action { struct GZCompressActionPrivate; public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(GZCompressAction) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(GZCompressAction) LOG4CXX_CAST_ENTRY_CHAIN(Action) END_LOG4CXX_CAST_MAP() /** * Constructor. */ GZCompressAction(const File& source, const File& destination, bool deleteSource); ~GZCompressAction(); /** * Perform action. * * @return true if successful. */ bool execute(LOG4CXX_NS::helpers::Pool& pool) const override; /** * Set to true to throw an IOException on a fork failure. By default, this * is true. When an IOException is thrown, this will automatically cause the * error handler to be called(which is the recommended way of handling this * problem). By setting this to false, the GZCompressAction effectively * turns into a FileRenameAction if any errors are encountered. * * @param throwIO */ void setThrowIOExceptionOnForkFailure(bool throwIO); private: GZCompressAction(const GZCompressAction&); GZCompressAction& operator=(const GZCompressAction&); }; LOG4CXX_PTR_DEF(GZCompressAction); } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/rolling/triggeringpolicy.h0000644000175100001770000000442214721727031025624 0ustar runnerdocker/* * 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. */ #if !defined(_LOG4CXX_ROLLING_TRIGGER_POLICY_H) #define _LOG4CXX_ROLLING_TRIGGER_POLICY_H #include #include #include #include namespace LOG4CXX_NS { class File; namespace rolling { /** * A TriggeringPolicy controls the conditions under which rollover * occurs. Such conditions include time of day, file size, an * external event or a combination thereof. * * * * */ class LOG4CXX_EXPORT TriggeringPolicy : public virtual spi::OptionHandler, public virtual helpers::Object { DECLARE_ABSTRACT_LOG4CXX_OBJECT(TriggeringPolicy) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(TriggeringPolicy) LOG4CXX_CAST_ENTRY(spi::OptionHandler) END_LOG4CXX_CAST_MAP() public: virtual ~TriggeringPolicy(); /** * 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. */ virtual bool isTriggeringEvent( Appender* appender, const spi::LoggingEventPtr& event, const LogString& filename, size_t fileLength) = 0; }; LOG4CXX_PTR_DEF(TriggeringPolicy); } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/rolling/timebasedrollingpolicy.h0000755000175100001770000002112214721727031027006 0ustar runnerdocker/* * 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. */ #if !defined(_LOG4CXX_ROLLING_TIME_BASED_ROLLING_POLICY_H) #define _LOG4CXX_ROLLING_TIME_BASED_ROLLING_POLICY_H #include #include #include #include #include namespace LOG4CXX_NS { namespace rolling { /** * 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 log4cxx::helpers::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 * arcived 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 thos 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. */ class LOG4CXX_EXPORT TimeBasedRollingPolicy : public virtual RollingPolicyBase, public virtual TriggeringPolicy { DECLARE_LOG4CXX_OBJECT(TimeBasedRollingPolicy) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(TimeBasedRollingPolicy) LOG4CXX_CAST_ENTRY_CHAIN(RollingPolicyBase) LOG4CXX_CAST_ENTRY_CHAIN(TriggeringPolicy) END_LOG4CXX_CAST_MAP() private: LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(TimeBasedRollingPolicyPrivate, m_priv) public: TimeBasedRollingPolicy(); virtual ~TimeBasedRollingPolicy(); /** \copybrief RollingPolicyBase::activateOptions() Logs a warning if an option is not valid. \sa RollingPolicyBase::activateOptions() */ void activateOptions(helpers::Pool& ) override; void setMultiprocess(bool multiprocess); /** * {@inheritDoc} */ RolloverDescriptionPtr initialize( const LogString& currentActiveFile, const bool append, helpers::Pool& pool) override; /** * {@inheritDoc} */ RolloverDescriptionPtr rollover( const LogString& currentActiveFile, const bool append, helpers::Pool& pool) override; /** * 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. */ bool isTriggeringEvent( Appender* appender, const spi::LoggingEventPtr& event, const LogString& filename, size_t fileLength) override; /** \copybrief RollingPolicyBase::setOption() Supported options | Supported values | Default value :-------------- | :----------------: | :---------------: ThrowIOExceptionOnForkFailure | True,False | True \sa RollingPolicyBase::setOption() */ void setOption(const LogString& option, const LogString& value) override; protected: /** * A map from "d" and "date" to a date conversion formatter. * * \sa FileDatePatternConverter */ LOG4CXX_NS::pattern::PatternMap getFormatSpecifiers() const override; private: /** * Generate mmap file */ int createMMapFile(const std::string& lastfilename, LOG4CXX_NS::helpers::Pool& pool); /** * Detect if the mmap file is empty */ bool isMapFileEmpty(LOG4CXX_NS::helpers::Pool& pool); /** * init MMapFile */ void initMMapFile(const LogString& lastFileName, LOG4CXX_NS::helpers::Pool& pool); /** * lock MMapFile */ int lockMMapFile(int type); /** * unlock MMapFile */ int unLockMMapFile(); /** * create MMapFile/lockFile */ const std::string createFile(const std::string& filename, const std::string& suffix, LOG4CXX_NS::helpers::Pool& pool); }; LOG4CXX_PTR_DEF(TimeBasedRollingPolicy); } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/mdc.h0000644000175100001770000002005014721727031021333 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_MDC_H #define _LOG4CXX_MDC_H #include #include #include namespace LOG4CXX_NS { /** A Mapped Diagnostic Context, or MDC in short, is an instrument for distinguishing interleaved log output from different sources. Log output is typically interleaved when a server handles multiple clients near-simultaneously. #MDC provides a constructor and destructor which simply call the #put and #remove methods, allowing for automatic cleanup when the current scope ends. #MDC operations such as #put, #remove and #clear affect only logging events emitted in the calling thread. The contexts of other threads are not changed. That is, contexts are managed on a per thread basis. The MDC class is similar to the {@link log4cxx::NDC NDC} class except that it is based on a map instead of a stack. */ class LOG4CXX_EXPORT MDC { public: /** String to string stl map. */ typedef std::map Map; /** * Places a key/value pair in the MDC for the current thread * which will be removed during the corresponding destructor. Both * construction and destruction are expected to be on the same thread. * @param key context identifier * @param value a string that distinguishes this context. */ MDC(const std::string& key, const std::string& value); ~MDC(); /** * Set the key context in the current thread's context map to value. * *

If the current thread does not have a context map it is * created as a side effect. * @param key context identifier * @param value a string that distinguishes this context. */ static void put(const std::string& key, const std::string& value); /** * Set the key context in the current thread's context map to value. * *

If the current thread does not have a context map it is * created as a side effect. * */ static void putLS(const LogString& key, const LogString& value); /** * Get the context identified by the key parameter. * *

This method has no side effects. * @param key context identifier. * @return value for key, empty if not set. * */ static std::string get(const std::string& key); /** * Gets the context identified by the key parameter. * @param key context key. * @param dest destination to which value is appended. * @return true if key has associated value. */ static bool get(const LogString& key, LogString& dest); /** * Remove the the context identified by the key * parameter. * @param key context identifier. * @return value if key had been set, empty if not. */ static std::string remove(const std::string& key); #if LOG4CXX_WCHAR_T_API /** * Places a key/value pair in the MDC for the current thread * which will be removed during the corresponding destructor. Both * construction and destruction are expected to be on the same thread. * @param key context identifier * @param value a string that distinguishes this context. */ MDC(const std::wstring& key, const std::wstring& value); /** * Set the key context in the current thread's context map to value. * *

If the current thread does not have a context map it is * created as a side effect. * @param key context identifier * @param value a string that distinguishes this context. */ static void put(const std::wstring& key, const std::wstring& value); /** * Get the context identified by the key parameter. * *

This method has no side effects. * @param key context identifier. * @return value for key, empty if not set. * */ static std::wstring get(const std::wstring& key); /** * Remove the the context identified by the key * parameter. * @param key context identifier. * @return value if key had been set, empty if not. */ static std::wstring remove(const std::wstring& key); #endif #if LOG4CXX_UNICHAR_API /** * Places a key/value pair in the MDC for the current thread * which will be removed during the corresponding destructor. Both * construction and destruction are expected to be on the same thread. * @param key context identifier * @param value a string that distinguishes this context. */ MDC(const std::basic_string& key, const std::basic_string& value); /** * Set the key context in the current thread's context map to value. * *

If the current thread does not have a context map it is * created as a side effect. * @param key context identifier * @param value the value. */ static void put(const std::basic_string& key, const std::basic_string& value); /** * Get the context identified by the key parameter. * *

This method has no side effects. * @param key context identifier. * @return value for key, empty if not set. * */ static std::basic_string get(const std::basic_string& key); /** * Remove the the context identified by the key * parameter. * @param key context identifier. * @return value if key had been set, empty if not. */ static std::basic_string remove(const std::basic_string& key); #endif #if LOG4CXX_CFSTRING_API /** * Places a key/value pair in the MDC for the current thread * which will be removed during the corresponding destructor. Both * construction and destruction are expected to be on the same thread. * @param key context identifier * @param value a string that distinguishes this context. */ MDC(const CFStringRef& key, const CFStringRef& value); /** * Set the key context in the current thread's context map to value. * *

If the current thread does not have a context map it is * created as a side effect. * @param key context identifier * @param value a string that distinguishes this context. */ static void put(const CFStringRef& key, const CFStringRef& value); /** * Get the context identified by the key parameter. * *

This method has no side effects. * @param key context identifier. * @return value for key, empty if not set. * */ static CFStringRef get(const CFStringRef& key); /** * Remove the the context identified by the key * parameter. * @param key context identifier. * @return value if key had been set, empty if not. */ static CFStringRef remove(const CFStringRef& key); #endif /** * Remove the the context identified by the key * parameter. * @param key context identifier. * @param prevValue buffer to which previous value is appended. * @return true if key existed in MDC. */ static bool remove(const LogString& key, LogString& prevValue); /** * Clear all entries in the MDC. *

A thread that adds to the diagnostic context by calling * #put should call this method before exiting * to prevent unbounded memory usage. */ static void clear(); private: MDC(const MDC&); MDC& operator=(const MDC&); LOG4CXX_DECLARE_PRIVATE_MEMBER(LogString, key) }; // class MDC; } // namespace log4cxx #endif // _LOG4CXX_MDC_H apache-log4cxx-1.3.1/src/main/include/log4cxx/hexdump.h0000644000175100001770000000355514721727031022255 0ustar runnerdocker/* * 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. */ #ifndef LOG4CXX_HEXDUMP_H #define LOG4CXX_HEXDUMP_H #include #include namespace LOG4CXX_NS { enum class HexdumpFlags : uint32_t{ None, AddStartingNewline = (0x01 << 0), AddEndingNewline = (0x01 << 1), AddNewline = AddStartingNewline | AddEndingNewline, }; inline bool operator&(HexdumpFlags a, HexdumpFlags b){ return !!(static_cast(a) & static_cast(b)); } inline HexdumpFlags operator|(HexdumpFlags a, HexdumpFlags b){ return static_cast(static_cast(a) | static_cast(b)); } /** * Hexdump the given bytes and return a LogString with the dumped bytes. * * Sample output: * 00000000 0a 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 |. | * * @param bytes A pointer to the bytes to dump * @param len How many bytes to dump * @param flags Flags to control the output format of the hexdump * @return A LogString with the hexdump output */ LOG4CXX_EXPORT LogString hexdump(const void* bytes, uint32_t len, HexdumpFlags flags = HexdumpFlags::None); } #endif // LOG4CXX_HEXDUMP_H apache-log4cxx-1.3.1/src/main/include/log4cxx/config/0000755000175100001770000000000014721727031021667 5ustar runnerdockerapache-log4cxx-1.3.1/src/main/include/log4cxx/config/propertysetter.h0000644000175100001770000000665714721727031025171 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_CONFIG_PROPERTYSETTER_H #define _LOG4CXX_CONFIG_PROPERTYSETTER_H #include #include namespace LOG4CXX_NS { namespace helpers { class Object; LOG4CXX_PTR_DEF(Object); } } // Instantiate template pointer type passed as parameter LOG4CXX_INSTANTIATE_EXPORTED_PTR(LOG4CXX_NS::helpers::Object); namespace LOG4CXX_NS { namespace helpers { class Properties; class Pool; } namespace config { /** General purpose Object property setter. Clients repeatedly invokes {@link #setProperty setProperty(name,value)} in order to invoke setters on the Object specified in the constructor.

Usage:

PropertySetter ps(anObject);
ps.set("name", "Joe");
ps.set("age", "32");
ps.set("isMale", "true");
will cause the invocations anObject->setOption("name", "Joe"), anObject->setOption("age", "32") and anObject->setOption("isMale", "true") if the spi::OptionHandler interface is supported by anObject. */ class LOG4CXX_EXPORT PropertySetter { protected: helpers::ObjectPtr obj; public: /** Create a new PropertySetter for the specified Object. This is done in prepartion for invoking #setProperty one or more times. @param obj the object for which to set properties */ PropertySetter(const helpers::ObjectPtr& obj); /** Set the properties of an object passed as a parameter in one go. The properties are parsed relative to a prefix. @param obj The object to configure. @param properties A java.util.Properties containing keys and values. @param prefix Only keys having the specified prefix will be set. @param p pool to use for any allocations required during call. */ static void setProperties(const helpers::ObjectPtr& obj, helpers::Properties& properties, const LogString& prefix, LOG4CXX_NS::helpers::Pool& p); /** Set the properites for the object that match the prefix passed as parameter. */ void setProperties(helpers::Properties& properties, const LogString& prefix, LOG4CXX_NS::helpers::Pool& p); /** Set a property on this PropertySetter's Object. If the underlying Object supports the spi::OptionHandler interface, the {@link spi::OptionHandler#setOption setOption} method is called. @param option name of the property @param value String value of the property @param p pool to use for any allocations required during call. */ void setProperty(const LogString& option, const LogString& value, LOG4CXX_NS::helpers::Pool& p); void activate(LOG4CXX_NS::helpers::Pool& p); }; // class PropertySetter } // namespace config; } // namespace log4cxx #endif //_LOG4CXX_CONFIG_PROPERTYSETTER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/patternlayout.h0000644000175100001770000004770114721727031023517 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_PATTERN_LAYOUT_H #define _LOG4CXX_PATTERN_LAYOUT_H #include #include #include #include namespace LOG4CXX_NS { LOG4CXX_LIST_DEF(LoggingEventPatternConverterList, LOG4CXX_NS::pattern::LoggingEventPatternConverterPtr); LOG4CXX_LIST_DEF(FormattingInfoList, LOG4CXX_NS::pattern::FormattingInfoPtr); /** * A flexible layout configurable with pattern string. * *

* The goal of this class is to format a {@link spi::LoggingEvent LoggingEvent} and * return the results as a string. The results depend on the conversion pattern. *

* *

* The conversion pattern is closely related to the conversion pattern of the printf * function in C. A conversion pattern is composed of literal text and format control * expressions called conversion specifiers. *

* *

* You are free to insert any literal text within the conversion pattern. *

* *

* Each conversion specifier starts with a percent sign (%) and is followed by optional * format modifiers and a conversion character. The conversion character * specifies the type of data, e.g. logger, level, date, thread name. The format modifiers * control such things as field width, padding, left and right justification. The * following is a simple example. *

* *

* Let the conversion pattern be "%-5p [%t]: %m%n" and assume that the log4cxx * environment was set to use a PatternLayout. Then the statements * * ~~~{.cpp} * auto root = Logger::getRootLogger(); * root->debug("Message 1"); * root->warn("Message 2"); * ~~~ * * would yield the output *

 *      DEBUG [main]: Message 1
 *      WARN  [main]: Message 2
*

* *

* Note that there is no explicit separator between text and conversion specifiers. The * pattern parser knows when it has reached the end of a conversion specifier when it * reads a conversion character. In the example above the conversion specifier %-5p * means the level of the logging event should be left justified to a width of five * characters. *

* *

The recognized conversion characters are:

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Conversion CharacterEffect
c * Used to output the name of the logger generating the logging event. The c conversion specifier * can be optionally followed by precision specifier, that is a decimal * constant in brackets. *

* If a precision specifier is given, then only the corresponding number of * right most components of the logger name will be printed. By default the * logger name is printed in full. *

*

* For example, for the logger name "a.b.c" the pattern %c{2} will * output "b.c". *

*
*

C

*

class

*
* Used to output the class of the issuer of the logging event if the compiler * used supports a macro to retrieve the method of the currently compiled line and * if the LOG4CXX_TRACE-like macros are used to issue a logging request. In this * case the macro LOG4CXX_* is expanded at compile time to generate location info * of the logging event and adds the method name, besides file and line, if * available. In most cases the provided method contains the classname and can * therefore be retrieved form the location info as needed. *

* Currently supported compilers are those from Microsoft, GNU-C and Borland. *

*
d * Used to output the date of the logging event. The date conversion specifier may * be followed by a set of braces containing a date and time pattern string * compatible with java.text.SimpleDateFormat, ABSOLUTE, DATE or * ISO8601. For example, %d{HH:mm:ss,SSS}, * %d{dd MMM yyyy HH:mm:ss,SSS} or %d{DATE}. If no * date format specifier is given then ISO8601 format is assumed. *
f * Used to output the short file name where the logging request was issued. *
F * Used to output the file name where the logging request was issued. *
l * Used to output location information of the caller which generated the logging * event. *
L * Used to output the line number from where the logging request was issued. *
m * Used to output the application supplied message associated with the logging event. * To output in a quoted context, add set of braces containing the quote character. * Any quote character in the message is augmented with a second quote character. * For example, use %m{'} in an SQL insert statement. *
* M *

method

*
* Used to output the method of the issuer of the logging event if the compiler * used supports a macro to retrieve the method of the currently compiled line * and if the LOG4CXX_TRACE-like macros are used to issue a logging request. In * this case the macro LOG4CXX_* is expanded at compile time to generate location * info of the logging event and adds the method name, besides file and line, if * available. In most cases the provided method contains the classname which is * ignored in every attempt to retrieve the method from the location info. *

* Currently supported compilers are those from Microsoft, GNU-C and Borland. *

*
n * Outputs the platform dependent line separator character or characters. *

* This conversion character offers practically the same performance as using * non-portable line separator strings such as "\n", or "\r\n". Thus, it is the * preferred way of specifying a line separator. *

*
pUsed to output the level of the logging event.
r * Used to output the number of milliseconds elapsed since the start of the * application until the creation of the logging event. *
t

thread

Used to output the ID of the thread that generated the logging event.
T

threadname

Used to output the name of the thread that generated the logging event. May not be available on all platforms.
x * Used to output the NDC (nested diagnostic context) associated with the thread that * generated the logging event. *
X * Used to output the MDC (mapped diagnostic context) associated with the thread that * generated the logging event. All key/value pairs are output, each inside {} unless * the X is followed by a key placed between braces, as in %X{clientNumber} * where clientNumber is the key. In this case the value in the MDC corresponding to * the key will be output. *

See MDC class for more details.

*
J * Used to output JSON key/value pairs of all MDC (mapped diagnostic context) * entries associated with the thread that generated the logging event. * To output in a quoted context, add set of braces containing the quote character. * Any quote character in the message is augmented with a second quote character. * For example, use %J{'} in an SQL insert statement. *

See MDC class for more details.

*
y * Used to wrap log with color. The y is the end of a color block.
*
Y * Used to wrap log with color. The Y is the start of a color block. * Color will be taken from the log level. The default colors are: * - `TRACE` - blue * - `DEBUG` - cyan * - `INFO` - green * - `WARN` - yellow * - `ERROR` - red * - `FATAL` - magenta * * These colors are all customizable. *
%The sequence %% outputs a single percent sign.
* *

* By default the relevant information is output as is. However, with the aid of format * modifiers it is possible to change the minimum field width, the maximum field width * and justification. *

* *

* The optional format modifier is placed between the percent sign and the conversion * character. *

* *

* The first optional format modifier is the left justification flag which is * just the minus (-) character. Then comes the optional minimum field width * modifier. This is a decimal constant that represents the minimum number of characters * to output. If the data item requires fewer characters, it is padded on either the left * or the right until the minimum width is reached. The default is to pad on the left * (right justify) but you can specify right padding with the left justification flag. The * padding character is space. If the data item is larger than the minimum field width, * the field is expanded to accommodate the data. The value is never truncated. *

* *

* This behavior can be changed using the maximum field width modifier which is * designated by a period followed by a decimal constant. If the data item is longer than * the maximum field, then the extra characters are removed from the beginning of * the data item and not from the end. For example, it the maximum field width is eight * and the data item is ten characters long, then the first two characters of the data * item are dropped. This behavior deviates from the printf function in C where truncation * is done from the end. *

* *

Below are various format modifier examples for the logger conversion specifier.

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Format modifierleft justifyminimum widthmaximum widthcomment
%20cfalse20noneLeft pad with spaces if the logger name is less than 20 characters long.
%-20ctrue20noneRight pad with spaces if the logger name is less than 20 characters long.
%.30cNAnone30Truncate from the beginning if the logger name is longer than 30 characters.
%20.30cfalse2030 * Left pad with spaces if the logger name is shorter than 20 characters. However, if * logger name is longer than 30 characters, then truncate from the beginning. *
%-20.30ctrue2030 * Right pad with spaces if the logger name is shorter than 20 characters. However, if * logger name is longer than 30 characters, then truncate from the beginning. *
* *

Below are some examples of conversion patterns.

* *

%%r [%%t] %-5p %%c %%x - %%m\n

*

This is essentially the TTCC layout.

* *

%-6r [%15.15t] %-5p %30.30c %%x - %%m\n

* *

* Similar to the TTCC layout except that the relative time is right padded if less than 6 * digits, thread name is right padded if less than 15 characters and truncated if longer * and the logger name is left padded if shorter than 30 characters and truncated if * longer. *

* *

* The above text is largely inspired from Peter A. Darnell and Philip E. Margolis' highly * recommended book "C -- a Software Engineering Approach", ISBN 0-387-97389-3. *

* *

Colorizing log output

* * In order to customize the colors for the %Y specifier, options have been added to the * PatternLayout in order to let users define their own colors. Foreground/background colors * can be set, as well as other text effects. A user can also set the ANSI escape pattern * directly if they want. * * Each level can be set individually. The configuration options for the levels are as follows: *
    *
  • FatalColor
  • *
  • ErrorColor
  • *
  • WarnColor
  • *
  • InfoColor
  • *
  • DebugColor
  • *
  • ErrorColor
  • *
* * Foreground colors may be set by using fg(), background colors may be set by using bg(), and * other options(such as bold) may be set as well. * * Available colors: *
    *
  • Black
  • *
  • Red
  • *
  • Green
  • *
  • Yellow
  • *
  • Blue
  • *
  • Magenta
  • *
  • Cyan
  • *
  • White
  • *
* * Available graphics modes: *
    *
  • Bold
  • *
  • Dim
  • *
  • Italic
  • *
  • Underline
  • *
  • Blinking
  • *
  • Inverse
  • *
  • Strikethrough
  • *
* * Combining these together, we can configure our colors as we want, shown here in XML: * * Set the background color to red, make text blinking and bold: *
 * <param name="FatalColor" value="bg(red)|blinking|bold"/>
 * 
* * Set the foreground color to blue: *
 * <param name="FatalColor" value="fg(blue)"/>
 * 
* * Set the foreground color to white and the background color to black: *
 * <param name="FatalColor" value="fg(white)|bg(black)"/>
 * 
* * Clear the formatting for the specified level(no formatting will be applied): *
 * <param name="FatalColor" value="none"/>
 * 
* * Set a color based off on an ANSI escape sequence(equivalent to setting fg(red)): *
 * <param name="FatalColor" value="\x1b[31m"/>
 * 
*/ class LOG4CXX_EXPORT PatternLayout : public Layout { LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(PatternLayoutPrivate, m_priv) public: DECLARE_LOG4CXX_OBJECT(PatternLayout) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(PatternLayout) LOG4CXX_CAST_ENTRY_CHAIN(Layout) END_LOG4CXX_CAST_MAP() /** * Does nothing */ PatternLayout(); /** * Constructs a PatternLayout using the supplied conversion pattern. */ PatternLayout(const LogString& pattern); ~PatternLayout(); /** * Use \c conversionPattern as to control formatting. * * The pattern can be a mix of literal content and * conversion specifiers. */ void setConversionPattern(const LogString& conversionPattern); /** * Returns the value of the ConversionPattern option. */ LogString getConversionPattern() const; /** \copybrief spi::OptionHandler::activateOptions() Calls createPatternParser */ void activateOptions(helpers::Pool& p) override; /** \copybrief spi::OptionHandler::setOption() Supported options | Supported values | Default value -------------- | ---------------- | --------------- ConversionPattern | {any} | \%m\%n FatalColor | (\ref validColors "1") | magenta ErrorColor | (\ref validColors "1") | red WarnColor | (\ref validColors "1") | yellow InfoColor | (\ref validColors "1") | green DebugColor | (\ref validColors "1") | cyan TraceColor | (\ref validColors "1") | blue \anchor validColors (1) The word None or valid ANSI escape sequence. A prefix of \\x1b will be replaced with the ESC character. The character prefix ESC and suffix m will be added to the value if it does not begin with \\x1b. Color names can be combined with graphic modes using a | separator. Enclose the color name in bg() to set the background. Enclose the color name in fg() to set the foreground. \sa setConversionPattern */ void setOption(const LogString& option, const LogString& value) override; /** * The PatternLayout does not handle the throwable contained within * {@link spi::LoggingEvent LoggingEvents}. Thus, it returns * true. */ bool ignoresThrowable() const override { return true; } /** * Produces a formatted string as specified by the conversion pattern. */ void format( LogString& output, const spi::LoggingEventPtr& event, helpers::Pool& pool) const override; protected: virtual LOG4CXX_NS::pattern::PatternMap getFormatSpecifiers(); private: pattern::PatternConverterPtr createColorStartPatternConverter(const std::vector& options); }; LOG4CXX_PTR_DEF(PatternLayout); } // namespace log4cxx #endif //_LOG4CXX_PATTERN_LAYOUT_H apache-log4cxx-1.3.1/src/main/include/log4cxx/level.h0000644000175100001770000002103414721727031021702 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_LEVEL_H #define _LOG4CXX_LEVEL_H #include #include #include #include namespace LOG4CXX_NS { /** * LOG4CXX_PTR_DEF can't be used to get a smart pointer for Level because we need to override * the comparison operator and this doesn't work if the template has alread been initialized, * which is what the macro does on some platforms. The overriding takes place underneath the * definition of Level because we need one of it's methods. * * https://issues.apache.org/jira/browse/LOGCXX-394 */ class Level; typedef std::shared_ptr LevelPtr; /** Defines the minimum set of levels recognized by the system, that is OFF, FATAL, ERROR, WARN, INFO, DEBUG and ALL.

The Level class may be subclassed to define a larger level set. */ class LOG4CXX_EXPORT Level : public helpers::Object { public: class LOG4CXX_EXPORT LevelClass : public helpers::Class { public: LevelClass() : helpers::Class() {} virtual LogString getName() const { return LOG4CXX_STR("Level"); } virtual LevelPtr toLevel(const LogString& sArg) const { return Level::toLevelLS(sArg); } virtual LevelPtr toLevel(int val) const { return Level::toLevel(val); } }; DECLARE_LOG4CXX_OBJECT_WITH_CUSTOM_CLASS(Level, LevelClass) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(Level) END_LOG4CXX_CAST_MAP() /** Instantiate a Level object. */ Level(int level, const LogString& name, int syslogEquivalent); /** Convert the string passed as argument to a level. If the conversion fails, then this method returns DEBUG. * @param sArg level name. */ static LevelPtr toLevel(const std::string& sArg); /** Convert the string passed as argument to a level. If the conversion fails, then this method returns the value of defaultLevel. * @param sArg level name. * @param defaultLevel level to return if no match. * @return */ static LevelPtr toLevel(const std::string& sArg, const LevelPtr& defaultLevel); /** * Get the name of the level in the current encoding. * @param name buffer to which name is appended. */ void toString(std::string& name) const; #if LOG4CXX_WCHAR_T_API /** Convert the string passed as argument to a level. If the conversion fails, then this method returns DEBUG. * @param sArg level name. */ static LevelPtr toLevel(const std::wstring& sArg); /** Convert the string passed as argument to a level. If the conversion fails, then this method returns the value of defaultLevel. * @param sArg level name. * @param defaultLevel level to return if no match. * @return */ static LevelPtr toLevel(const std::wstring& sArg, const LevelPtr& defaultLevel); /** * Get the name of the level. * @param name buffer to which name is appended. */ void toString(std::wstring& name) const; #endif #if LOG4CXX_UNICHAR_API || LOG4CXX_LOGCHAR_IS_UNICHAR /** Convert the string passed as argument to a level. If the conversion fails, then this method returns DEBUG. * @param sArg level name. */ static LevelPtr toLevel(const std::basic_string& sArg); /** Convert the string passed as argument to a level. If the conversion fails, then this method returns the value of defaultLevel. * @param sArg level name. * @param defaultLevel level to return if no match. * @return */ static LevelPtr toLevel(const std::basic_string& sArg, const LevelPtr& defaultLevel); /** * Get the name of the level. * @param name buffer to which name is appended. */ void toString(std::basic_string& name) const; #endif #if LOG4CXX_CFSTRING_API /** Convert the string passed as argument to a level. If the conversion fails, then this method returns DEBUG. * @param sArg level name. */ static LevelPtr toLevel(const CFStringRef& sArg); /** Convert the string passed as argument to a level. If the conversion fails, then this method returns the value of defaultLevel. * @param sArg level name. * @param defaultLevel level to return if no match. * @return */ static LevelPtr toLevel(const CFStringRef& sArg, const LevelPtr& defaultLevel); /** * Get the name of the level. * @param name buffer to which name is appended. */ void toString(CFStringRef& name) const; #endif /** Convert the string passed as argument to a level. If the conversion fails, then this method returns DEBUG. * @param sArg level name. */ static LevelPtr toLevelLS(const LogString& sArg); /** Convert the string passed as argument to a level. If the conversion fails, then this method returns the value of defaultLevel. * @param sArg level name. * @param defaultLevel level to return if no match. * @return */ static LevelPtr toLevelLS(const LogString& sArg, const LevelPtr& defaultLevel); /** Returns the string representation of this level. * @return level name. */ LogString toString() const; /** Convert an integer passed as argument to a level. If the conversion fails, then this method returns DEBUG. */ static LevelPtr toLevel(int val); /** Convert an integer passed as argument to a level. If the conversion fails, then this method returns the specified default. */ static LevelPtr toLevel(int val, const LevelPtr& defaultLevel); enum { OFF_INT = INT_MAX, FATAL_INT = 50000, ERROR_INT = 40000, WARN_INT = 30000, INFO_INT = 20000, DEBUG_INT = 10000, TRACE_INT = 5000, ALL_INT = INT_MIN }; struct Data { LevelPtr Off; LevelPtr Fatal; LevelPtr Error; LevelPtr Warn; LevelPtr Info; LevelPtr Debug; LevelPtr Trace; LevelPtr All; }; using DataPtr = std::shared_ptr; static const DataPtr& getData(); static LevelPtr getAll(); static LevelPtr getFatal(); static LevelPtr getError(); static LevelPtr getWarn(); static LevelPtr getInfo(); static LevelPtr getDebug(); static LevelPtr getTrace(); static LevelPtr getOff(); /** Two levels are equal if their level fields are equal. */ virtual bool equals(const LevelPtr& level) const; inline bool operator==(const Level& level1) const { return (this->level == level1.level); } inline bool operator!=(const Level& level1) const { return (this->level != level1.level); } /** Return the syslog equivalent of this level as an integer. */ inline int getSyslogEquivalent() const { return syslogEquivalent; } /** Returns true if this level has a higher or equal level than the level passed as argument, false otherwise.

You should think twice before overriding the default implementation of isGreaterOrEqual method. */ virtual bool isGreaterOrEqual(const LevelPtr& level) const; /** Returns the integer representation of this level. */ inline int toInt() const { return level; } private: LOG4CXX_DECLARE_PRIVATE_MEMBER(LogString, name) int level; int syslogEquivalent; Level(const Level&); Level& operator=(const Level&); }; } #define DECLARE_LOG4CXX_LEVEL(level)\ public:\ class Class##level : public Level::LevelClass\ {\ public:\ Class##level() : Level::LevelClass() {}\ virtual LogString getName() const { return LOG4CXX_STR(#level); } \ virtual LevelPtr toLevel(const LogString& sArg) const\ { return level::toLevelLS(sArg); }\ virtual LevelPtr toLevel(int val) const\ { return level::toLevel(val); }\ };\ DECLARE_LOG4CXX_OBJECT_WITH_CUSTOM_CLASS(level, Class##level) #define IMPLEMENT_LOG4CXX_LEVEL(level) \ IMPLEMENT_LOG4CXX_OBJECT_WITH_CUSTOM_CLASS(level, Class##level) #endif //_LOG4CXX_LEVEL_H apache-log4cxx-1.3.1/src/main/include/log4cxx/pattern/0000755000175100001770000000000014721727031022077 5ustar runnerdockerapache-log4cxx-1.3.1/src/main/include/log4cxx/pattern/literalpatternconverter.h0000644000175100001770000000342614721727031027237 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_PATTERN_LITERAL_PATTERN_CONVERTER_H #define _LOG4CXX_PATTERN_LITERAL_PATTERN_CONVERTER_H #include namespace LOG4CXX_NS { namespace pattern { /** * Formats a string literal. * * * * */ class LOG4CXX_EXPORT LiteralPatternConverter : public LoggingEventPatternConverter { struct LiteralPatternConverterPrivate; public: DECLARE_LOG4CXX_PATTERN(LiteralPatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(LiteralPatternConverter) LOG4CXX_CAST_ENTRY_CHAIN(LoggingEventPatternConverter) END_LOG4CXX_CAST_MAP() LiteralPatternConverter(const LogString& literal); static PatternConverterPtr newInstance(const LogString& literal); using LoggingEventPatternConverter::format; void format(const spi::LoggingEventPtr& event, LogString& toAppendTo, helpers::Pool& p) const override; void format(const helpers::ObjectPtr& obj, LogString& toAppendTo, helpers::Pool& p) const override; }; } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/pattern/loggerpatternconverter.h0000644000175100001770000000340614721727031027060 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_PATTERN_LOGGER_PATTERN_CONVERTER_H #define _LOG4CXX_PATTERN_LOGGER_PATTERN_CONVERTER_H #include namespace LOG4CXX_NS { namespace pattern { /** * Formats a logger name. * * * * */ class LOG4CXX_EXPORT LoggerPatternConverter : public NamePatternConverter { public: DECLARE_LOG4CXX_PATTERN(LoggerPatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(LoggerPatternConverter) LOG4CXX_CAST_ENTRY_CHAIN(NamePatternConverter) END_LOG4CXX_CAST_MAP() LoggerPatternConverter(const std::vector& options); /** * Obtains an instance of pattern converter. * @param options options, may be null. * @return instance of pattern converter. */ static PatternConverterPtr newInstance( const std::vector& options); using NamePatternConverter::format; void format(const spi::LoggingEventPtr& event, LogString& toAppendTo, helpers::Pool& p) const override; }; } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/pattern/relativetimepatternconverter.h0000644000175100001770000000361414721727031030274 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_PATTERN_RELATIVE_TIME_PATTERN_CONVERTER #define _LOG4CXX_PATTERN_RELATIVE_TIME_PATTERN_CONVERTER #include namespace LOG4CXX_NS { namespace pattern { /** * Format the relative time in milliseconds. * * * */ class LOG4CXX_EXPORT RelativeTimePatternConverter : public LoggingEventPatternConverter { public: DECLARE_LOG4CXX_PATTERN(RelativeTimePatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(RelativeTimePatternConverter) LOG4CXX_CAST_ENTRY_CHAIN(LoggingEventPatternConverter) END_LOG4CXX_CAST_MAP() /** * Private constructor. */ RelativeTimePatternConverter(); /** * Obtains an instance of RelativeTimePatternConverter. * @param options options, currently ignored, may be null. * @return instance of RelativeTimePatternConverter. */ static PatternConverterPtr newInstance( const std::vector& options); using LoggingEventPatternConverter::format; void format(const spi::LoggingEventPtr& event, LogString& toAppendTo, LOG4CXX_NS::helpers::Pool& p) const override; }; } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/pattern/lineseparatorpatternconverter.h0000644000175100001770000000362614721727031030455 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_PATTERN_LINE_SEPARATOR_PATTERN_CONVERTER #define _LOG4CXX_PATTERN_LINE_SEPARATOR_PATTERN_CONVERTER #include namespace LOG4CXX_NS { namespace pattern { /** * Formats a line separator. * * * */ class LOG4CXX_EXPORT LineSeparatorPatternConverter : public LoggingEventPatternConverter { public: DECLARE_LOG4CXX_PATTERN(LineSeparatorPatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(LineSeparatorPatternConverter) LOG4CXX_CAST_ENTRY_CHAIN(LoggingEventPatternConverter) END_LOG4CXX_CAST_MAP() LineSeparatorPatternConverter(); /** * Obtains an instance of pattern converter. * @param options options, may be null. * @return instance of pattern converter. */ static PatternConverterPtr newInstance( const std::vector& options); using LoggingEventPatternConverter::format; void format(const spi::LoggingEventPtr& event, LogString& toAppendTo, helpers::Pool& p) const override; void format(const helpers::ObjectPtr& obj, LogString& toAppendTo, helpers::Pool& p) const override; }; } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/pattern/levelpatternconverter.h0000644000175100001770000000352014721727031026705 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_PATTERN_LEVEL_PATTERN_CONVERTER #define _LOG4CXX_PATTERN_LEVEL_PATTERN_CONVERTER #include namespace LOG4CXX_NS { namespace pattern { /** * Return the event's level in a StringBuffer. * * * */ class LOG4CXX_EXPORT LevelPatternConverter : public LoggingEventPatternConverter { public: DECLARE_LOG4CXX_PATTERN(LevelPatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(LevelPatternConverter) LOG4CXX_CAST_ENTRY_CHAIN(LoggingEventPatternConverter) END_LOG4CXX_CAST_MAP() LevelPatternConverter(); /** * Obtains an instance of pattern converter. * @param options options, may be null. * @return instance of pattern converter. */ static PatternConverterPtr newInstance( const std::vector& options); using LoggingEventPatternConverter::format; void format(const spi::LoggingEventPtr& event, LogString& toAppendTo, helpers::Pool& p) const override; LogString getStyleClass(const helpers::ObjectPtr& e) const override; }; } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/pattern/colorstartpatternconverter.h0000644000175100001770000000425314721727031027776 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_PATTERN_COLOR_START_PATTERN_CONVERTER #define _LOG4CXX_PATTERN_COLOR_START_PATTERN_CONVERTER #include namespace LOG4CXX_NS { namespace pattern { /** * Format the event's color start information. * * * */ class LOG4CXX_EXPORT ColorStartPatternConverter : public LoggingEventPatternConverter { struct ColorPatternConverterPrivate; public: DECLARE_LOG4CXX_PATTERN(ColorStartPatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(ColorStartPatternConverter) LOG4CXX_CAST_ENTRY_CHAIN(LoggingEventPatternConverter) END_LOG4CXX_CAST_MAP() ColorStartPatternConverter(); /** * Obtains an instance of pattern converter. * @param options options, may be null. * @return instance of pattern converter. */ static PatternConverterPtr newInstance( const std::vector& options); using LoggingEventPatternConverter::format; void format(const spi::LoggingEventPtr& event, LogString& toAppendTo, helpers::Pool& p) const override; void setFatalColor(const LogString& color); void setErrorColor(const LogString& color); void setWarnColor(const LogString& color); void setInfoColor(const LogString& color); void setDebugColor(const LogString& color); void setTraceColor(const LogString& color); private: void parseColor(const LogString& color, LogString* result); }; } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/pattern/formattinginfo.h0000644000175100001770000000467714721727031025314 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPER_FORMATTING_INFO_H #define _LOG4CXX_HELPER_FORMATTING_INFO_H #include #include namespace LOG4CXX_NS { namespace pattern { class FormattingInfo; typedef std::shared_ptr FormattingInfoPtr; /** * Modifies the output of a pattern converter for a specified minimum * and maximum width and alignment. * * * * */ class LOG4CXX_EXPORT FormattingInfo : public virtual LOG4CXX_NS::helpers::Object { LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(FormattingInfoPrivate, m_priv) public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(FormattingInfo) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(FormattingInfo) END_LOG4CXX_CAST_MAP() /** * Creates new instance. * @param leftAlign left align if true. * @param minLength minimum length. * @param maxLength maximum length. */ FormattingInfo( const bool leftAlign, const int minLength, const int maxLength); ~FormattingInfo(); /** * Gets default instance. * @return default instance. */ static FormattingInfoPtr getDefault(); /** * Determine if left aligned. * @return true if left aligned. */ bool isLeftAligned() const; /** * Get minimum length. * @return minimum length. */ int getMinLength() const; /** * Get maximum length. * @return maximum length. */ int getMaxLength() const; /** * 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. */ void format(const int fieldStart, LogString& buffer) const; }; LOG4CXX_PTR_DEF(FormattingInfo); } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/pattern/linelocationpatternconverter.h0000644000175100001770000000346614721727031030267 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_PATTERN_LINE_LOCATION_PATTERN_CONVERTER #define _LOG4CXX_PATTERN_LINE_LOCATION_PATTERN_CONVERTER #include namespace LOG4CXX_NS { namespace pattern { /** * Format the event's line location information. * * * */ class LOG4CXX_EXPORT LineLocationPatternConverter : public LoggingEventPatternConverter { public: DECLARE_LOG4CXX_PATTERN(LineLocationPatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(LineLocationPatternConverter) LOG4CXX_CAST_ENTRY_CHAIN(LoggingEventPatternConverter) END_LOG4CXX_CAST_MAP() LineLocationPatternConverter(); /** * Obtains an instance of pattern converter. * @param options options, may be null. * @return instance of pattern converter. */ static PatternConverterPtr newInstance( const std::vector& options); using LoggingEventPatternConverter::format; void format(const spi::LoggingEventPtr& event, LogString& toAppendTo, helpers::Pool& p) const override; }; } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/pattern/namepatternconverter.h0000644000175100001770000000422614721727031026522 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_PATTERN_NAMED_PATTERN_CONVERTER_H #define _LOG4CXX_PATTERN_NAMED_PATTERN_CONVERTER_H #include #include #include namespace LOG4CXX_NS { namespace pattern { /** * * Base class for other pattern converters which can return only parts of their name. * */ class LOG4CXX_EXPORT NamePatternConverter : public LoggingEventPatternConverter { struct NamePatternConverterPrivate; public: DECLARE_LOG4CXX_PATTERN(NamePatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(NamePatternConverter) LOG4CXX_CAST_ENTRY_CHAIN(LoggingEventPatternConverter) END_LOG4CXX_CAST_MAP() protected: /** * Constructor. * @param name name of converter. * @param style style name for associated output. * @param options options, may be null, first element will be interpreted as an abbreviation pattern. */ NamePatternConverter( const LogString& name, const LogString& style, const std::vector& options); /** * Abbreviate name in string buffer. * @param nameStart starting position of name to abbreviate. * @param buf string buffer containing name. */ void abbreviate(LogString::size_type nameStart, LogString& buf) const; private: NameAbbreviatorPtr getAbbreviator(const std::vector& options); }; } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/pattern/propertiespatternconverter.h0000644000175100001770000000452314721727031027776 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_PATTERN_PROPERTIES_PATTERN_CONVERTER #define _LOG4CXX_PATTERN_PROPERTIES_PATTERN_CONVERTER #include namespace LOG4CXX_NS { namespace pattern { /** * Able to handle the contents of the LoggingEvent's Property bundle and either * output the entire contents of the properties in a similar format to the * java.util.Hashtable.toString(), or to output the value of a specific key * within the property bundle * when this pattern converter has the option set. * * * */ class LOG4CXX_EXPORT PropertiesPatternConverter : public LoggingEventPatternConverter { struct PropertiesPatternConverterPrivate; public: DECLARE_LOG4CXX_PATTERN(PropertiesPatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(PropertiesPatternConverter) LOG4CXX_CAST_ENTRY_CHAIN(LoggingEventPatternConverter) END_LOG4CXX_CAST_MAP() /** * A Property bundle converter. * * @param name of the converter. * @param option may be null. */ PropertiesPatternConverter(const LogString& name, const LogString& option); /** * Obtains an instance of PropertiesPatternConverter. * @param options options, may be null or first element contains name of property to format. * @return instance of PropertiesPatternConverter. */ static PatternConverterPtr newInstance( const std::vector& options); using LoggingEventPatternConverter::format; void format(const spi::LoggingEventPtr& event, LogString& toAppendTo, LOG4CXX_NS::helpers::Pool& p) const override; }; } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/pattern/colorendpatternconverter.h0000644000175100001770000000343214721727031027405 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_PATTERN_COLOR_END_PATTERN_CONVERTER #define _LOG4CXX_PATTERN_COLOR_END_PATTERN_CONVERTER #include namespace LOG4CXX_NS { namespace pattern { /** * Format the event's color end information. * * * */ class LOG4CXX_EXPORT ColorEndPatternConverter : public LoggingEventPatternConverter { public: DECLARE_LOG4CXX_PATTERN(ColorEndPatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(ColorEndPatternConverter) LOG4CXX_CAST_ENTRY_CHAIN(LoggingEventPatternConverter) END_LOG4CXX_CAST_MAP() ColorEndPatternConverter(); /** * Obtains an instance of pattern converter. * @param options options, may be null. * @return instance of pattern converter. */ static PatternConverterPtr newInstance( const std::vector& options); using LoggingEventPatternConverter::format; void format(const spi::LoggingEventPtr& event, LogString& toAppendTo, helpers::Pool& p) const override; }; } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/pattern/datepatternconverter.h0000644000175100001770000000653314721727031026522 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_PATTERN_DATE_PATTERN_CONVERTER #define _LOG4CXX_PATTERN_DATE_PATTERN_CONVERTER #include #include #include #include namespace LOG4CXX_NS { namespace pattern { /** * Convert and format a date or timestamp into a string. */ class LOG4CXX_EXPORT DatePatternConverter : public LoggingEventPatternConverter { struct DatePatternConverterPrivate; /** * Obtains an instance of pattern converter. * @param options options, may be null. * @return instance of pattern converter. */ static helpers::DateFormatPtr getDateFormat(const OptionsList& options); public: DECLARE_LOG4CXX_PATTERN(DatePatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(DatePatternConverter) LOG4CXX_CAST_ENTRY_CHAIN(LoggingEventPatternConverter) END_LOG4CXX_CAST_MAP() /** * An object that can convert a date or timestamp to the format * described by the conversion specifier in the first element in \c options. * * If the conversion specifier contains a \% character, * the date is formated using strftime. * * Otherwise the conversion specifier must be a pattern compatible with * java.text.SimpleDateFormat, "ABSOLUTE", "DATE" or "ISO8601". * For example, "HH:mm:ss,SSS", "dd MMM yyyy HH:mm:ss,SSS" or "DATE". * * ISO8601 format is assumed if the first element in \c options missing or empty. * * If \c options has a second element, it is assumed to be a time zone specifier, * for example, "GMT-6" */ DatePatternConverter(const OptionsList& options); ~DatePatternConverter(); /** * \copydoc #DatePatternConverter::DatePatternConverter() */ static PatternConverterPtr newInstance( const std::vector& options); /** * Append to \c output a textual version of the timestamp in \c event. */ void format(const spi::LoggingEventPtr& event, LogString& output, helpers::Pool& p) const override; /** * Append to \c output a textual version of the date or timestamp in \c obj. * * Nothing is added to \c output if \c obj does not point to a Date or spi::LoggingEvent. */ void format(const helpers::ObjectPtr& obj, LogString& output, helpers::Pool& p) const override; /** * Append to \c toAppendTo a textual version of \c date. */ void format(const helpers::DatePtr& date, LogString& toAppendTo, helpers::Pool& p) const; }; LOG4CXX_PTR_DEF(DatePatternConverter); } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/pattern/patternparser.h0000644000175100001770000001225014721727031025142 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPER_PATTERN_CONVERTER_H #define _LOG4CXX_HELPER_PATTERN_CONVERTER_H #include #include #include #include #include #include namespace LOG4CXX_NS { namespace pattern { typedef std::function& options)> PatternConstructor; typedef std::map PatternMap; // Contributors: Nelson Minar <(nelson@monkey.org> // Igor E. Poteryaev // Reinhard Deschler /** * Most of the work of the {@link log4cxx::PatternLayout PatternLayout} class * is delegated to the PatternParser class. *

It is this class that parses conversion patterns and creates * a chained list of {@link PatternConverter PatternConverters}. * * */ class LOG4CXX_EXPORT PatternParser { /** * Escape character for format specifier. */ static const logchar ESCAPE_CHAR; enum { LITERAL_STATE = 0, CONVERTER_STATE = 1, DOT_STATE = 3, MIN_STATE = 4, MAX_STATE = 5 }; /** * Private constructor. */ PatternParser(); private: /** 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. */ static size_t extractConverter( logchar lastChar, const LogString& pattern, LogString::size_type i, LogString& convBuf, LogString& currentLiteral); /** * Extract options. * @param pattern conversion pattern. * @param i start of options. * @param options array to receive extracted options * @return position in pattern after options. */ static size_t extractOptions(const LogString& pattern, LogString::size_type i, std::vector& options); public: /** * 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 rules map of stock pattern converters keyed by format specifier. */ static void parse( const LogString& pattern, std::vector& patternConverters, std::vector& formattingInfos, const PatternMap& rules); private: /** * 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 rules map of stock pattern converters keyed by format specifier. * @param options converter options. * @return converter or null. */ static PatternConverterPtr createConverter( const LogString& converterId, LogString& currentLiteral, const PatternMap& rules, std::vector& options); /** * 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 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. */ static size_t finalizeConverter( logchar c, const LogString& pattern, size_t i, LogString& currentLiteral, const FormattingInfoPtr& formattingInfo, const PatternMap& rules, std::vector& patternConverters, std::vector& formattingInfos); static bool isUnicodeIdentifierStart(logchar c); static bool isUnicodeIdentifierPart(logchar c); }; } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/pattern/filedatepatternconverter.h0000644000175100001770000000322214721727031027352 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_PATTERN_FILE_DATE_PATTERN_CONVERTER #define _LOG4CXX_PATTERN_FILE_DATE_PATTERN_CONVERTER #include namespace LOG4CXX_NS { namespace pattern { /** * Formats an date by delegating to DatePatternConverter. The default * date pattern for a %d specifier in a file name is different than * the %d pattern in pattern layout. * * * */ class LOG4CXX_EXPORT FileDatePatternConverter { /** * Private constructor. */ FileDatePatternConverter(); public: /** * An instance of pattern converter for date conversion and formatting. * * \sa DatePatternConverter::newInstance() * * @param options If empty, used the patterm "yyyy-MM-dd". * @return The date conversion and formatting instance. */ static PatternConverterPtr newInstance( const std::vector& options); }; } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/pattern/threadpatternconverter.h0000644000175100001770000000343514721727031027052 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_PATTERN_THREAD_PATTERN_CONVERTER #define _LOG4CXX_PATTERN_THREAD_PATTERN_CONVERTER #include namespace LOG4CXX_NS { namespace pattern { /** * Formats the event thread name. * * * */ class LOG4CXX_EXPORT ThreadPatternConverter : public LoggingEventPatternConverter { public: DECLARE_LOG4CXX_PATTERN(ThreadPatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(ThreadPatternConverter) LOG4CXX_CAST_ENTRY_CHAIN(LoggingEventPatternConverter) END_LOG4CXX_CAST_MAP() ThreadPatternConverter(); /** * Obtains an instance of ThreadPatternConverter. * @param options options, currently ignored, may be null. * @return instance of ThreadPatternConverter. */ static PatternConverterPtr newInstance( const std::vector& options); using LoggingEventPatternConverter::format; void format(const spi::LoggingEventPtr& event, LogString& toAppendTo, helpers::Pool& p) const override; }; } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/pattern/throwableinformationpatternconverter.h0000644000175100001770000000437614721727031032045 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_PATTERN_THROWABLE_INFORMATION_PATTERN_CONVERTER #define _LOG4CXX_PATTERN_THROWABLE_INFORMATION_PATTERN_CONVERTER #include namespace LOG4CXX_NS { namespace pattern { /** * Outputs the ThrowableInformation portion of the LoggingiEvent as a full stacktrace * unless this converter's option is 'short', where it just outputs the first line of the trace. * * * * */ class LOG4CXX_EXPORT ThrowableInformationPatternConverter : public LoggingEventPatternConverter { struct ThrowableInformationPatternConverterPrivate; public: DECLARE_LOG4CXX_PATTERN(ThrowableInformationPatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(ThrowableInformationPatternConverter) LOG4CXX_CAST_ENTRY_CHAIN(LoggingEventPatternConverter) END_LOG4CXX_CAST_MAP() ThrowableInformationPatternConverter(bool shortReport); /** * Gets an instance of the class. * @param options pattern options, may be null. If first element is "short", * only the first line of the throwable will be formatted. * @return instance of class. */ static PatternConverterPtr newInstance( const std::vector& options); using LoggingEventPatternConverter::format; void format(const spi::LoggingEventPtr& event, LogString& toAppendTo, helpers::Pool& p) const override; /** * This converter obviously handles throwables. * @return true. */ bool handlesThrowable() const override; }; } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/pattern/methodlocationpatternconverter.h0000644000175100001770000000355514721727031030617 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_PATTERN_METHOD_LOCATION_PATTERN_CONVERTER #define _LOG4CXX_PATTERN_METHOD_LOCATION_PATTERN_CONVERTER #include namespace LOG4CXX_NS { namespace pattern { /** * Return the event's line location information in a StringBuffer. * * * */ class LOG4CXX_EXPORT MethodLocationPatternConverter : public LoggingEventPatternConverter { public: DECLARE_LOG4CXX_PATTERN(MethodLocationPatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(MethodLocationPatternConverter) LOG4CXX_CAST_ENTRY_CHAIN(LoggingEventPatternConverter) END_LOG4CXX_CAST_MAP() MethodLocationPatternConverter(); /** * Obtains an instance of MethodLocationPatternConverter. * @param options options, may be null. * @return instance of MethodLocationPatternConverter. */ static PatternConverterPtr newInstance( const std::vector& options); using LoggingEventPatternConverter::format; void format(const spi::LoggingEventPtr& event, LogString& toAppendTo, helpers::Pool& p) const override; }; } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/pattern/mdcpatternconverter.h0000644000175100001770000000376314721727031026352 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_PATTERN_MDC_PATTERN_CONVERTER #define _LOG4CXX_PATTERN_MDC_PATTERN_CONVERTER #include namespace LOG4CXX_NS { namespace pattern { /** * Provides all key value pairs in JSON or a single value from an event's mapped diagnostic context */ class LOG4CXX_EXPORT MDCPatternConverter : public LoggingEventPatternConverter { public: DECLARE_LOG4CXX_PATTERN(MDCPatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(MDCPatternConverter) LOG4CXX_CAST_ENTRY_CHAIN(LoggingEventPatternConverter) END_LOG4CXX_CAST_MAP() MDCPatternConverter ( const LogString& name = LogString() , const LogString& style = LogString() , const std::vector& options = std::vector() ); /** * An instance of MDCPatternConverter. * @param options if not empty, options[0][0] is the character to duplicate */ static PatternConverterPtr newInstance(const std::vector& options); using LoggingEventPatternConverter::format; void format ( const spi::LoggingEventPtr& event , LogString& toAppendTo , helpers::Pool& p ) const override; }; } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/pattern/ndcpatternconverter.h0000644000175100001770000000337414721727031026351 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_PATTERN_NDC_PATTERN_CONVERTER #define _LOG4CXX_PATTERN_NDC_PATTERN_CONVERTER #include namespace LOG4CXX_NS { namespace pattern { /** * Return the event's NDC in a StringBuffer. * * * */ class LOG4CXX_EXPORT NDCPatternConverter : public LoggingEventPatternConverter { public: DECLARE_LOG4CXX_PATTERN(NDCPatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(NDCPatternConverter) LOG4CXX_CAST_ENTRY_CHAIN(LoggingEventPatternConverter) END_LOG4CXX_CAST_MAP() NDCPatternConverter(); /** * Obtains an instance of NDCPatternConverter. * @param options options, may be null. * @return instance of NDCPatternConverter. */ static PatternConverterPtr newInstance( const std::vector& options); using LoggingEventPatternConverter::format; void format(const spi::LoggingEventPtr& event, LogString& toAppendTo, helpers::Pool& p) const override; }; } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/pattern/nameabbreviator.h0000644000175100001770000000454414721727031025420 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_PATTERN_NAME_ABBREVIATOR #define _LOG4CXX_PATTERN_NAME_ABBREVIATOR #include #include namespace LOG4CXX_NS { namespace pattern { class NameAbbreviator; LOG4CXX_PTR_DEF(NameAbbreviator); /** * NameAbbreviator generates abbreviated logger and class names. * * * */ class LOG4CXX_EXPORT NameAbbreviator : public LOG4CXX_NS::helpers::Object { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(NameAbbreviator) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(NameAbbreviator) END_LOG4CXX_CAST_MAP() protected: NameAbbreviator(); public: virtual ~NameAbbreviator(); /** * Gets an abbreviator. * * For example, "%logger{2}" will output only 2 elements of the logger name, * "%logger{1.}" will output only the first character of the non-final elements in the name, * "%logger(1~.2~} will output the first character of the first element, two characters of * the second and subsequent elements and will use a tilde to indicate abbreviated characters. * * @param pattern abbreviation pattern. * @return abbreviator, will not be null. */ static NameAbbreviatorPtr getAbbreviator(const LogString& pattern); /** * Gets default abbreviator. * * @return default abbreviator. */ static NameAbbreviatorPtr getDefaultAbbreviator(); /** * Abbreviates a name in a StringBuffer. * * @param nameStart starting position of name in buf. * @param buf buffer, may not be null. */ virtual void abbreviate(LogString::size_type nameStart, LogString& buf) const = 0; }; } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/pattern/patternconverter.h0000644000175100001770000000663214721727031025664 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_PATTERN_PATTERN_CONVERTER_H #define _LOG4CXX_PATTERN_PATTERN_CONVERTER_H #include #include #include #define DECLARE_LOG4CXX_PATTERN(cls) DECLARE_ABSTRACT_LOG4CXX_OBJECT(cls) namespace LOG4CXX_NS { namespace pattern { typedef std::vector OptionsList; /**

PatternConverter is an abstract class that provides the formatting functionality that derived classes need.

Conversion specifiers in a conversion patterns are parsed to individual PatternConverters. Each of which is responsible for converting an object in a converter specific manner. */ class LOG4CXX_EXPORT PatternConverter : public virtual helpers::Object { protected: LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(PatternConverterPrivate, m_priv) PatternConverter(LOG4CXX_PRIVATE_PTR(PatternConverterPrivate) priv); /** * Create a new pattern converter. Use this constructor when you have a subclass * that does not have any private data. * @param name name for pattern converter. * @param style CSS style for formatted output. */ PatternConverter(const LogString& name, const LogString& style); virtual ~PatternConverter(); public: DECLARE_LOG4CXX_PATTERN(PatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(PatternConverter) END_LOG4CXX_CAST_MAP() /** * Formats an object into a string buffer. * @param obj event to format, may not be null. * @param toAppendTo string buffer to which the formatted event will be appended. May not be null. * @param p pool for any allocations necessary during formatting. */ virtual void format(const helpers::ObjectPtr& obj, LogString& toAppendTo, helpers::Pool& p) const = 0; /** * This method returns the name of the conversion pattern. * * The name can be useful to certain Layouts such as HTMLLayout. * * @return the name of the conversion pattern */ LogString getName() const; /** * This method returns the CSS style class that should be applied to * the LoggingEvent passed as parameter, which can be null. * * This information is currently used only by HTMLLayout. * * @param e null values are accepted * @return the name of the conversion pattern */ virtual LogString getStyleClass(const helpers::ObjectPtr& e) const; protected: /** * Appends content in the locale code page to a LogString. * @param toAppendTo string to which content is appended. * @param src content. */ static void append(LogString& toAppendTo, const std::string& src); }; LOG4CXX_PTR_DEF(PatternConverter); } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/pattern/fulllocationpatternconverter.h0000644000175100001770000000346714721727031030303 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_PATTERN_FULL_LOCATION_PATTERN_CONVERTER #define _LOG4CXX_PATTERN_FULL_LOCATION_PATTERN_CONVERTER #include namespace LOG4CXX_NS { namespace pattern { /** * Format the event's line location information. * * * */ class LOG4CXX_EXPORT FullLocationPatternConverter : public LoggingEventPatternConverter { public: DECLARE_LOG4CXX_PATTERN(FullLocationPatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(FullLocationPatternConverter) LOG4CXX_CAST_ENTRY_CHAIN(LoggingEventPatternConverter) END_LOG4CXX_CAST_MAP() FullLocationPatternConverter(); /** * Obtains an instance of pattern converter. * @param options options, may be null. * @return instance of pattern converter. */ static PatternConverterPtr newInstance( const std::vector& options); using LoggingEventPatternConverter::format; void format(const spi::LoggingEventPtr& event, LogString& toAppendTo, helpers::Pool& p) const override; }; } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/pattern/loggingeventpatternconverter.h0000644000175100001770000000527614721727031030300 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_PATTERN_LOGGING_EVENT_PATTERN_CONVERTER_H #define _LOG4CXX_PATTERN_LOGGING_EVENT_PATTERN_CONVERTER_H #include #include namespace LOG4CXX_NS { namespace pattern { /** * LoggingEventPatternConverter is a base class for pattern converters * that can format information from instances of LoggingEvent. * * * * */ class LOG4CXX_EXPORT LoggingEventPatternConverter : public PatternConverter { protected: /** * Constructs an instance of LoggingEventPatternConverter. * @param name name of converter. * @param style CSS style for output. */ LoggingEventPatternConverter( const LogString& name, const LogString& style); LoggingEventPatternConverter(std::unique_ptr priv); public: DECLARE_LOG4CXX_PATTERN(LoggingEventPatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(LoggingEventPatternConverter) LOG4CXX_CAST_ENTRY_CHAIN(PatternConverter) END_LOG4CXX_CAST_MAP() /** * Formats an event into a string buffer. * @param event event to format, may not be null. * @param toAppendTo string buffer to which the formatted event will be appended. May not be null. * @param p pool for memory allocations needing during format. */ virtual void format( const spi::LoggingEventPtr& event, LogString& toAppendTo, helpers::Pool& p) const = 0; void format(const helpers::ObjectPtr& obj, LogString& toAppendTo, helpers::Pool& p) const override; /** * Normally pattern converters are not meant to handle Exceptions although * few pattern converters might. * * By examining the return values for this method, the containing layout will * determine whether it handles throwables or not. * @return true if this PatternConverter handles throwables */ virtual bool handlesThrowable() const; }; LOG4CXX_PTR_DEF(LoggingEventPatternConverter); } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/pattern/classnamepatternconverter.h0000644000175100001770000000356314721727031027553 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_PATTERN_CLASSNAME_PATTERN_CONVERTER_H #define _LOG4CXX_PATTERN_CLASSNAME_PATTERN_CONVERTER_H #include namespace LOG4CXX_NS { namespace pattern { /** * Formats the class name of the site of the logging request. * * * */ class LOG4CXX_EXPORT ClassNamePatternConverter : public NamePatternConverter { public: /** * @param options options, may be null. */ ClassNamePatternConverter(const std::vector& options); DECLARE_LOG4CXX_PATTERN(ClassNamePatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(ClassNamePatternConverter) LOG4CXX_CAST_ENTRY_CHAIN(NamePatternConverter) END_LOG4CXX_CAST_MAP() /** * Gets an instance of ClassNamePatternConverter. * @param options options, may be null. * @return instance of pattern converter. */ static PatternConverterPtr newInstance( const std::vector& options); using NamePatternConverter::format; void format(const spi::LoggingEventPtr& event, LogString& toAppendTo, helpers::Pool& p) const override; }; } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/pattern/integerpatternconverter.h0000644000175100001770000000332014721727031027231 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_PATTERN_INTEGER_PATTERN_CONVERTER #define _LOG4CXX_PATTERN_INTEGER_PATTERN_CONVERTER #include namespace LOG4CXX_NS { namespace pattern { /** * Formats an integer. * * * */ class LOG4CXX_EXPORT IntegerPatternConverter : public PatternConverter { public: DECLARE_LOG4CXX_PATTERN(IntegerPatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(IntegerPatternConverter) LOG4CXX_CAST_ENTRY_CHAIN(PatternConverter) END_LOG4CXX_CAST_MAP() IntegerPatternConverter(); /** * Obtains an instance of pattern converter. * @param options options, may be null. * @return instance of pattern converter. */ static PatternConverterPtr newInstance( const std::vector& options); void format(const helpers::ObjectPtr& obj, LogString& toAppendTo, helpers::Pool& p) const override; }; LOG4CXX_PTR_DEF(IntegerPatternConverter); } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/pattern/filelocationpatternconverter.h0000644000175100001770000000351014721727031030245 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_PATTERN_FILE_LOCATION_PATTERN_CONVERTER #define _LOG4CXX_PATTERN_FILE_LOCATION_PATTERN_CONVERTER #include namespace LOG4CXX_NS { namespace pattern { /** * Return the event's line location information in a StringBuffer. * * * */ class LOG4CXX_EXPORT FileLocationPatternConverter : public LoggingEventPatternConverter { public: DECLARE_LOG4CXX_PATTERN(FileLocationPatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(FileLocationPatternConverter) LOG4CXX_CAST_ENTRY_CHAIN(LoggingEventPatternConverter) END_LOG4CXX_CAST_MAP() FileLocationPatternConverter(); /** * Obtains an instance of pattern converter. * @param options options, may be null. * @return instance of pattern converter. */ static PatternConverterPtr newInstance( const std::vector& options); using LoggingEventPatternConverter::format; void format(const spi::LoggingEventPtr& event, LogString& toAppendTo, helpers::Pool& p) const override; }; } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/pattern/shortfilelocationpatternconverter.h0000644000175100001770000000361614721727031031334 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_PATTERN_SHORT_FILE_LOCATION_PATTERN_CONVERTER #define _LOG4CXX_PATTERN_SHORT_FILE_LOCATION_PATTERN_CONVERTER #include namespace LOG4CXX_NS { namespace pattern { /** * Return the event's line location information in a StringBuffer. * * * */ class LOG4CXX_EXPORT ShortFileLocationPatternConverter : public LoggingEventPatternConverter { /** * Private constructor. */ ShortFileLocationPatternConverter(); public: DECLARE_LOG4CXX_PATTERN(ShortFileLocationPatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(ShortFileLocationPatternConverter) LOG4CXX_CAST_ENTRY_CHAIN(LoggingEventPatternConverter) END_LOG4CXX_CAST_MAP() /** * Obtains an instance of pattern converter. * @param options options, may be null. * @return instance of pattern converter. */ static PatternConverterPtr newInstance( const std::vector& options); using LoggingEventPatternConverter::format; void format(const spi::LoggingEventPtr& event, LogString& toAppendTo, helpers::Pool& p) const override; }; } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/pattern/messagepatternconverter.h0000644000175100001770000000341714721727031027227 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_PATTERN_MESSAGE_PATTERN_CONVERTER #define _LOG4CXX_PATTERN_MESSAGE_PATTERN_CONVERTER #include namespace LOG4CXX_NS { namespace pattern { /** * Formats the message of an logging event. * * * */ class LOG4CXX_EXPORT MessagePatternConverter : public LoggingEventPatternConverter { public: DECLARE_LOG4CXX_PATTERN(MessagePatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(MessagePatternConverter) LOG4CXX_CAST_ENTRY_CHAIN(LoggingEventPatternConverter) END_LOG4CXX_CAST_MAP() MessagePatternConverter(); /** * Obtains an instance of pattern converter. * @param options options, may be null. * @return instance of pattern converter. */ static PatternConverterPtr newInstance( const std::vector& options); using LoggingEventPatternConverter::format; void format(const spi::LoggingEventPtr& event, LogString& toAppendTo, helpers::Pool& p) const override; }; } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/pattern/threadusernamepatternconverter.h0000644000175100001770000000323414721727031030607 0ustar runnerdocker/* * 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. */ #ifndef LOG4CXX_THREAD_USERNAME_PATTERN_CONVERTER_H #define LOG4CXX_THREAD_USERNAME_PATTERN_CONVERTER_H #include #include namespace LOG4CXX_NS { namespace pattern { class LOG4CXX_EXPORT ThreadUsernamePatternConverter : public LoggingEventPatternConverter { public: DECLARE_LOG4CXX_PATTERN(ThreadUsernamePatternConverter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(ThreadUsernamePatternConverter) LOG4CXX_CAST_ENTRY_CHAIN(LoggingEventPatternConverter) END_LOG4CXX_CAST_MAP() ThreadUsernamePatternConverter(); static PatternConverterPtr newInstance( const std::vector& options); void format(const spi::LoggingEventPtr& event, LogString& toAppendTo, LOG4CXX_NS::helpers::Pool& p) const override; }; } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/version_info.h.in0000644000175100001770000000056214721727031023703 0ustar runnerdocker// Information used by resource files #define INFO_PRODUCT_VERSION_LIST @log4cxx_VERSION_MAJOR@,@log4cxx_VERSION_MINOR@,@log4cxx_VERSION_PATCH@ #define INFO_PRODUCT_VERSION_STRING "@log4cxx_VERSION@" #define INFO_FILE_VERSION_LIST INFO_PRODUCT_VERSION_LIST,@log4cxx_VERSION_TWEAK@ #define INFO_FILE_VERSION_STRING INFO_PRODUCT_VERSION_STRING "." @log4cxx_VERSION_TWEAK@ apache-log4cxx-1.3.1/src/main/include/log4cxx/private/0000755000175100001770000000000014721727031022074 5ustar runnerdockerapache-log4cxx-1.3.1/src/main/include/log4cxx/private/rollingpolicybase_priv.h0000644000175100001770000000300514721727031027024 0ustar runnerdocker/* * 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. */ #include #include #include #include #ifndef _LOG4CXX_ROLLINGPOLICYBASE_PRIV_H #define _LOG4CXX_ROLLINGPOLICYBASE_PRIV_H namespace LOG4CXX_NS { namespace rolling{ struct RollingPolicyBase::RollingPolicyBasePrivate { virtual ~RollingPolicyBasePrivate() = default; /** * File name pattern converters. */ PatternConverterList patternConverters; /** * File name field specifiers. */ FormattingInfoList patternFields; /** * File name pattern. */ LogString fileNamePatternStr; bool createIntermediateDirectories = true; }; } } #endif /* _LOG4CXX_ROLLINGPOLICYBASE_PRIV_H */ apache-log4cxx-1.3.1/src/main/include/log4cxx/private/patternconverter_priv.h0000644000175100001770000000271714721727031026721 0ustar runnerdocker/* * 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. */ #ifndef LOG4CXX_PATTERNCONVERTER_PRIVATE_H #define LOG4CXX_PATTERNCONVERTER_PRIVATE_H #include namespace LOG4CXX_NS { namespace pattern { /** * Create a new pattern converter. * @param name name for pattern converter. * @param style CSS style for formatted output. */ struct PatternConverter::PatternConverterPrivate { PatternConverterPrivate( const LogString& _name, const LogString& _style ) : name(_name), style(_style) {} virtual ~PatternConverterPrivate(){} /** * Converter name. */ const LogString name; /** * Converter style name. */ const LogString style; }; } } #endif /* LOG4CXX_PATTERNCONVERTER_PRIVATE_H */ apache-log4cxx-1.3.1/src/main/include/log4cxx/private/appenderskeleton_priv.h0000644000175100001770000000434214721727031026653 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_APPENDERSKELETON_PRIV #define _LOG4CXX_APPENDERSKELETON_PRIV #include #include #include namespace LOG4CXX_NS { struct AppenderSkeleton::AppenderSkeletonPrivate { AppenderSkeletonPrivate() : threshold(Level::getAll()), errorHandler(std::make_shared()), closed(false) {} AppenderSkeletonPrivate( LayoutPtr lay ) : layout( lay ), threshold(Level::getAll()), errorHandler(std::make_shared()), closed(false) {} virtual ~AppenderSkeletonPrivate(){} /** The layout variable does not need to be set if the appender implementation has its own layout. */ LayoutPtr layout; /** Appenders are named. */ LogString name; /** There is no level threshold filtering by default. */ LevelPtr threshold; /** It is assumed and enforced that errorHandler is never null. */ spi::ErrorHandlerPtr errorHandler; /** The first filter in the filter chain. Set to null initially. */ spi::FilterPtr headFilter; /** The last filter in the filter chain. */ spi::FilterPtr tailFilter; /** Is this appender closed? */ bool closed; LOG4CXX_NS::helpers::Pool pool; mutable std::recursive_mutex mutex; bool warnedClosed = false; bool checkNotClosed(); bool warnedNoLayout = false; bool checkLayout(); }; } #endif /* _LOG4CXX_APPENDERSKELETON_PRIV */ apache-log4cxx-1.3.1/src/main/include/log4cxx/private/nteventlogappender_priv.h0000644000175100001770000000000014721727031027177 0ustar runnerdockerapache-log4cxx-1.3.1/src/main/include/log4cxx/private/aprserversocket.h0000644000175100001770000000246414721727031025475 0ustar runnerdocker/* * 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. */ #ifndef LOG4CXX_HELPERS_APRSERVERSOCKET_H #define LOG4CXX_HELPERS_APRSERVERSOCKET_H #include namespace LOG4CXX_NS { namespace helpers { /** * A ServerSocket that uses APR as the network implementation */ class LOG4CXX_EXPORT APRServerSocket : public helpers::ServerSocket { public: APRServerSocket(int port); void close() override; SocketPtr accept() override; private: struct APRServerSocketPriv; }; } } #endif /* LOG4CXX_HELPERS_APRSERVERSOCKET_H */ apache-log4cxx-1.3.1/src/main/include/log4cxx/private/filter_priv.h0000644000175100001770000000210514721727031024570 0ustar runnerdocker/* * 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. */ #ifndef LOG4CXX_FILTER_PRIVATE_H #define LOG4CXX_FILTER_PRIVATE_H #include namespace LOG4CXX_NS { namespace spi { struct Filter::FilterPrivate { virtual ~FilterPrivate(){} /** Points to the next filter in the filter chain. */ FilterPtr next; }; } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/private/writerappender_priv.h0000644000175100001770000000574714721727031026355 0ustar runnerdocker/* * 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. */ #include #include #include #include "appenderskeleton_priv.h" #if LOG4CXX_EVENTS_AT_EXIT #include "atexitregistry.h" #endif #ifndef _LOG4CXX_WRITERAPPENDER_PRIV_H #define _LOG4CXX_WRITERAPPENDER_PRIV_H namespace LOG4CXX_NS { struct WriterAppender::WriterAppenderPriv : public AppenderSkeleton::AppenderSkeletonPrivate { WriterAppenderPriv() : AppenderSkeletonPrivate(), immediateFlush(true) #if LOG4CXX_EVENTS_AT_EXIT , atExitRegistryRaii([this]{atExitActivated();}) #endif { } WriterAppenderPriv(const LayoutPtr& layout1, LOG4CXX_NS::helpers::WriterPtr& writer1) : AppenderSkeletonPrivate(layout1), immediateFlush(true), writer(writer1) #if LOG4CXX_EVENTS_AT_EXIT , atExitRegistryRaii([this]{atExitActivated();}) #endif { } WriterAppenderPriv(const LayoutPtr& layout1) : AppenderSkeletonPrivate(layout1), immediateFlush(true) #if LOG4CXX_EVENTS_AT_EXIT , atExitRegistryRaii([this]{atExitActivated();}) #endif { } #if LOG4CXX_EVENTS_AT_EXIT void atExitActivated() { std::lock_guard lock(mutex); if (writer) writer->flush(pool); } #endif /** Immediate flush means that the underlying writer or output stream will be flushed at the end of each append operation. Immediate flush is slower but ensures that each append request is actually written. If immediateFlush is set to false, then there is a good chance that the last few logs events are not actually written to persistent media if and when the application crashes.

The immediateFlush variable is set to true by default. */ std::atomic immediateFlush; /** The encoding to use when opening an input stream.

The encoding variable is set to "" by default which results in the utilization of the system's default encoding. */ LogString encoding; /** * This is the {@link Writer Writer} where we will write to. */ LOG4CXX_NS::helpers::WriterPtr writer; #if LOG4CXX_EVENTS_AT_EXIT helpers::AtExitRegistry::Raii atExitRegistryRaii; #endif bool warnedNoWriter = false; bool checkWriter(); }; } #endif /* _LOG4CXX_WRITERAPPENDER_PRIV_H */ apache-log4cxx-1.3.1/src/main/include/log4cxx/private/action_priv.h0000644000175100001770000000241314721727031024562 0ustar runnerdocker/* * 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. */ #ifndef LOG4CXX_ACTION_PRIVATE_H #define LOG4CXX_ACTION_PRIVATE_H #include namespace LOG4CXX_NS { namespace rolling { struct Action::ActionPrivate { ActionPrivate() : complete(false), interrupted(false), pool() {} virtual ~ActionPrivate(){} /** * Is action complete. */ bool complete; /** * Is action interrupted. */ bool interrupted; LOG4CXX_NS::helpers::Pool pool; std::mutex mutex; }; } } #endif /* LOG4CXX_ACTION_PRIVATE_H */ apache-log4cxx-1.3.1/src/main/include/log4cxx/private/syslogappender_priv.h0000644000175100001770000000615114721727031026347 0ustar runnerdocker/* * 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. */ #include #include "appenderskeleton_priv.h" #include #if LOG4CXX_HAVE_SYSLOG #include #else /* facility codes */ #define LOG_KERN (0<<3) /* kernel messages */ #define LOG_USER (1<<3) /* random user-level messages */ #define LOG_MAIL (2<<3) /* mail system */ #define LOG_DAEMON (3<<3) /* system daemons */ #define LOG_AUTH (4<<3) /* security/authorization messages */ #define LOG_SYSLOG (5<<3) /* messages generated internally by syslogd */ #define LOG_LPR (6<<3) /* line printer subsystem */ #define LOG_NEWS (7<<3) /* network news subsystem */ #define LOG_UUCP (8<<3) /* UUCP subsystem */ #define LOG_CRON (9<<3) /* clock daemon */ #define LOG_AUTHPRIV (10<<3) /* security/authorization messages (private) */ #define LOG_FTP (11<<3) /* ftp daemon */ /* other codes through 15 reserved for system use */ #define LOG_LOCAL0 (16<<3) /* reserved for local use */ #define LOG_LOCAL1 (17<<3) /* reserved for local use */ #define LOG_LOCAL2 (18<<3) /* reserved for local use */ #define LOG_LOCAL3 (19<<3) /* reserved for local use */ #define LOG_LOCAL4 (20<<3) /* reserved for local use */ #define LOG_LOCAL5 (21<<3) /* reserved for local use */ #define LOG_LOCAL6 (22<<3) /* reserved for local use */ #define LOG_LOCAL7 (23<<3) /* reserved for local use */ #endif namespace LOG4CXX_NS { namespace net { struct SyslogAppender::SyslogAppenderPriv : public AppenderSkeleton::AppenderSkeletonPrivate { SyslogAppenderPriv() : AppenderSkeletonPrivate(), syslogFacility(LOG_USER), facilityPrinting(false), maxMessageLength(1024) { } SyslogAppenderPriv(const LayoutPtr& layout, int syslogFacility) : AppenderSkeletonPrivate (layout), syslogFacility(syslogFacility), facilityPrinting(false), maxMessageLength(1024) { } SyslogAppenderPriv(const LayoutPtr& layout, const LogString& syslogHost, int syslogFacility) : AppenderSkeletonPrivate(layout), syslogFacility(syslogFacility), facilityPrinting(false), maxMessageLength(1024) { } int syslogFacility; // Have LOG_USER as default LogString facilityStr; bool facilityPrinting; std::unique_ptr sw; LogString syslogHost; int syslogHostPort; int maxMessageLength; }; } } apache-log4cxx-1.3.1/src/main/include/log4cxx/private/datagramsocket_priv.h0000644000175100001770000000276114721727031026304 0ustar runnerdocker/* * 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. */ #ifndef LOG4CXX_HELPERS_SOCKET_PRIV_H #define LOG4CXX_HELPERS_SOCKET_PRIV_H #include namespace LOG4CXX_NS { namespace helpers { struct DatagramSocket::DatagramSocketPriv { DatagramSocketPriv() : port(0), localPort(0) { } DatagramSocketPriv(int localPort1) : port(0), localPort(localPort1) { } DatagramSocketPriv(int localPort1, InetAddressPtr localAddress1) : localAddress(localAddress1), port(0), localPort(localPort1) { } ~DatagramSocketPriv() = default; InetAddressPtr address; InetAddressPtr localAddress; int port; /** The local port number to which this socket is connected. */ int localPort; }; } } #endif /* LOG4CXX_HELPERS_SOCKET_PRIV_H */ apache-log4cxx-1.3.1/src/main/include/log4cxx/private/log4cxx_private.h.in0000644000175100001770000000440514721727031025777 0ustar runnerdocker/* 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. */ #ifndef LOG4CXX_PRIVATE_LOG4CXX_H #define LOG4CXX_PRIVATE_LOG4CXX_H /* GENERATED FILE WARNING! DO NOT EDIT log4cxx_private.h * * You must modify log4cxx_private.h.in instead. * */ #include #if !defined(LOG4CXX) && !defined(LOG4CXX_TEST) #error "log4cxx/private/log4cxx_private.h should only be used within log4cxx implementation or tests" #endif #define LOG4CXX_RETURN_AFTER_THROW 0 #define LOG4CXX_HAS_STD_LOCALE @HAS_STD_LOCALE@ #define LOG4CXX_FORCE_WIDE_CONSOLE 0 #define LOG4CXX_FORCE_BYTE_CONSOLE 0 #if defined(_MSC_VER) #define LOG4CXX_MEMSET_IOS_BASE 1 #else #define LOG4CXX_MEMSET_IOS_BASE 0 #endif #define LOG4CXX_HAVE_ODBC @HAS_ODBC@ #define LOG4CXX_HAS_MBSRTOWCS @HAS_MBSRTOWCS@ #define LOG4CXX_HAS_WCSTOMBS @HAS_WCSTOMBS@ #define LOG4CXX_HAS_FWIDE @HAS_FWIDE@ #define LOG4CXX_INIT_IOS_BASE @INIT_IOS_BASE@ #define LOG4CXX_CHARSET_UTF8 @CHARSET_UTF8@ #define LOG4CXX_CHARSET_ISO88591 @CHARSET_ISO88591@ #define LOG4CXX_CHARSET_USASCII @CHARSET_USASCII@ #define LOG4CXX_CHARSET_EBCDIC @CHARSET_EBCDIC@ #define LOG4CXX_HAVE_LIBESMTP @HAS_LIBESMTP@ #define LOG4CXX_HAVE_SYSLOG @HAS_SYSLOG@ #define LOG4CXX_WIN32_THREAD_FMTSPEC "0x%.8x" #define LOG4CXX_APR_THREAD_FMTSPEC "0x%pt" #define LOG4CXX_HAS_PTHREAD_SELF @HAS_PTHREAD_SELF@ #define LOG4CXX_HAS_PTHREAD_SIGMASK @HAS_PTHREAD_SIGMASK@ #define LOG4CXX_HAS_PTHREAD_SETNAME @HAS_PTHREAD_SETNAME@ #define LOG4CXX_HAS_PTHREAD_GETNAME @HAS_PTHREAD_GETNAME@ #define LOG4CXX_HAS_THREAD_LOCAL @HAS_THREAD_LOCAL@ #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/private/fileappender_priv.h0000644000175100001770000000355414721727031025752 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_FILEAPPENDER_PRIV_H #define _LOG4CXX_FILEAPPENDER_PRIV_H #include #include namespace LOG4CXX_NS { struct FileAppender::FileAppenderPriv : public WriterAppender::WriterAppenderPriv { FileAppenderPriv ( LayoutPtr _layout = LayoutPtr() , const LogString& _fileName = LogString() , bool _fileAppend = true , bool _bufferedIO = false , int _bufferSize = 8 * 1024 ) : WriterAppenderPriv(_layout) , fileAppend(_fileAppend) , fileName(_fileName) , bufferedIO(_bufferedIO) , bufferSize(_bufferSize) {} /** Append to or truncate the file? The default value for this variable is true, meaning that by default a FileAppender will append to an existing file and not truncate it.

This option is meaningful only if the FileAppender opens the file. */ bool fileAppend; /** The name of the log file. */ LogString fileName; /** Do we do bufferedIO? */ bool bufferedIO; /** How big should the IO buffer be? Default is 8K. */ int bufferSize; }; } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/private/atexitregistry.h0000644000175100001770000000324514721727031025340 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_AT_EXIT_REGISTRY_H #define _LOG4CXX_HELPERS_AT_EXIT_REGISTRY_H #include #include #if !LOG4CXX_EVENTS_AT_EXIT #error atexitregistry.h should only be included if LOG4CXX_EVENTS_AT_EXIT is set #endif namespace LOG4CXX_NS { namespace helpers { /* * Provides the initiation of the minimum necessary actions (buffers flushing for example) at the static deinitialization phase. */ class LOG4CXX_EXPORT AtExitRegistry { public: struct Raii { Raii(std::function action) { AtExitRegistry::instance().add(this, std::move(action)); } ~Raii() { AtExitRegistry::instance().del(this); } Raii(const Raii&) = delete; void operator=(const Raii&) = delete; }; private: friend Raii; static AtExitRegistry& instance(); void add(void* key, std::function action); void del(void* key); }; } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/private/string_c11.h0000644000175100001770000000343114721727031024220 0ustar runnerdocker/* * 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. */ #ifndef LOG4CXX_STRING_C11_H #define LOG4CXX_STRING_C11_H #define __STDC_WANT_LIB_EXT1__ 1 #include #if !defined(__STDC_LIB_EXT1__) && !defined(__STDC_SECURE_LIB__) #include #if !defined(RSIZE_MAX) && defined(SSIZE_MAX) #define RSIZE_MAX (SSIZE_MAX >> 4) #else // !defined(RSIZE_MAX) #define RSIZE_MAX (2 << 20) #endif static size_t strnlen_s( const char *str, size_t strsz ) { size_t result = 0; if (!str) ; else while (*str++ != 0 && result < strsz) ++result; return result; } static int strcat_s(char* destArg, size_t destsz, const char* src) { if (!src || !destArg || RSIZE_MAX < destsz) return -1; if (0 == destsz) return -2; --destsz; char* dest = destArg; size_t index = 0; while (*dest && index < destsz) ++index, ++dest; while (*src && index < destsz) { *dest++ = *src++; ++index; } *dest = 0; if (*src) // longer than destsz? { *destArg = 0; // Do not return a partial result return -3; } return 0; } #endif #endif /* LOG4CXX_STRING_C11_H */ apache-log4cxx-1.3.1/src/main/include/log4cxx/private/serversocket_priv.h0000644000175100001770000000223114721727031026022 0ustar runnerdocker/* * 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. */ #ifndef LOG4CXX_HELPERS_SERVERSOCKET_PRIV_H #define LOG4CXX_HELPERS_SERVERSOCKET_PRIV_H #include namespace LOG4CXX_NS { namespace helpers { struct ServerSocket::ServerSocketPrivate{ ServerSocketPrivate() : timeout(0){} virtual ~ServerSocketPrivate() = default; int timeout; }; } } #endif /* LOG4CXX_HELPERS_SERVERSOCKET_PRIV_H */ apache-log4cxx-1.3.1/src/main/include/log4cxx/private/odbcappender_priv.h0000644000175100001770000000720514721727031025737 0ustar runnerdocker/* * 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. */ #ifndef LOG4CXX_ODBCAPPENDER_PRIV #define LOG4CXX_ODBCAPPENDER_PRIV #include #include #include "appenderskeleton_priv.h" #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include #if LOG4CXX_HAVE_ODBC #if defined(WIN32) || defined(_WIN32) #include #endif #include #else typedef void* SQLHSTMT; typedef void* SQLPOINTER; typedef uint64_t SQLULEN; typedef int64_t SQLLEN; typedef long SQLINTEGER; typedef short SQLSMALLINT; #endif #if LOG4CXX_EVENTS_AT_EXIT #include #endif namespace LOG4CXX_NS { namespace db { struct ODBCAppender::ODBCAppenderPriv : public AppenderSkeleton::AppenderSkeletonPrivate { ODBCAppenderPriv( #if LOG4CXX_EVENTS_AT_EXIT std::function atExitActivated #endif ) : AppenderSkeletonPrivate() , connection(0) , env(0) , preparedStatement(0) , bufferSize(1) , timeZone(helpers::TimeZone::getDefault()) #if LOG4CXX_EVENTS_AT_EXIT , atExitRegistryRaii(std::move(atExitActivated)) #endif {} /** * URL of the DB for default connection handling */ LogString databaseURL; /** * User to connect as for default connection handling */ LogString databaseUser; /** * User to use for default connection handling */ LogString databasePassword; /** * Connection used by default. The connection is opened the first time it * is needed and then held open until the appender is closed (usually at * garbage collection). This behavior is best modified by creating a * sub-class and overriding the getConnection and * closeConnection methods. */ SQLHDBC connection; SQLHENV env; /** * Stores the string given to the pattern layout for conversion into a SQL */ LogString sqlStatement; /** * size of LoggingEvent buffer before writing to the database. * Default is 1. */ size_t bufferSize; /** * ArrayList holding the buffer of Logging Events. */ std::vector buffer; /** Provides timestamp components */ helpers::TimeZonePtr timeZone; /** * The prepared statement handle and the bound column names, converters and buffers */ SQLHSTMT preparedStatement; struct DataBinding { using ConverterPtr = pattern::LoggingEventPatternConverterPtr; ConverterPtr converter; SQLSMALLINT paramType; SQLULEN paramMaxCharCount; SQLPOINTER paramValue; SQLINTEGER paramValueSize; SQLLEN strLen_or_Ind; }; std::vector mappedName; std::vector parameterValue; #if LOG4CXX_HAVE_ODBC void setPreparedStatement(SQLHDBC con, helpers::Pool& p); void setParameterValues(const spi::LoggingEventPtr& event, helpers::Pool& p); #endif #if LOG4CXX_EVENTS_AT_EXIT helpers::AtExitRegistry::Raii atExitRegistryRaii; #endif }; } } #endif /* LOG4CXX_ODBCAPPENDER_PRIV */ apache-log4cxx-1.3.1/src/main/include/log4cxx/private/aprdatagramsocket.h0000644000175100001770000000322614721727031025744 0ustar runnerdocker/* * 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. */ #ifndef LOG4CXX_HELPERS_APRDATAGRAM_SOCKET_H #define LOG4CXX_HELPERS_APRDATAGRAM_SOCKET_H #include namespace LOG4CXX_NS { namespace helpers { class APRDatagramSocket : public DatagramSocket { private: struct APRDatagramSocketPriv; public: APRDatagramSocket(); APRDatagramSocket(int port); APRDatagramSocket(int port, InetAddressPtr laddr); void bind(int lport, InetAddressPtr laddress) override; void close() override; bool isClosed() const override; /** Receives a datagram packet from this socket. */ virtual void receive(DatagramPacketPtr& p) override; /** Sends a datagram packet from this socket. */ virtual void send(DatagramPacketPtr& p) override; virtual void connect(InetAddressPtr address, int port) override; private: void init(); }; } } #endif /* LOG4CXX_HELPERS_APRDATAGRAM_SOCKET_H */ apache-log4cxx-1.3.1/src/main/include/log4cxx/private/socketappenderskeleton_priv.h0000644000175100001770000000526214721727031030066 0ustar runnerdocker/* * 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. */ #ifndef LOG4CXX_SOCKETAPPENDERSKELETON_PRIVATE_H #define LOG4CXX_SOCKETAPPENDERSKELETON_PRIVATE_H #include #include #include #if LOG4CXX_EVENTS_AT_EXIT #include #endif namespace LOG4CXX_NS { namespace net { struct SocketAppenderSkeleton::SocketAppenderSkeletonPriv : public AppenderSkeletonPrivate { SocketAppenderSkeletonPriv(int defaultPort, int reconnectionDelay) : AppenderSkeletonPrivate(), remoteHost(), address(), port(defaultPort), reconnectionDelay(reconnectionDelay), locationInfo(false) #if LOG4CXX_EVENTS_AT_EXIT , atExitRegistryRaii([this]{stopMonitor();}) #endif { } SocketAppenderSkeletonPriv(helpers::InetAddressPtr address, int defaultPort, int reconnectionDelay) : AppenderSkeletonPrivate(), remoteHost(), address(address), port(defaultPort), reconnectionDelay(reconnectionDelay), locationInfo(false) #if LOG4CXX_EVENTS_AT_EXIT , atExitRegistryRaii([this]{stopMonitor();}) #endif { } SocketAppenderSkeletonPriv(const LogString& host, int port, int delay) : AppenderSkeletonPrivate(), remoteHost(host), address(helpers::InetAddress::getByName(host)), port(port), reconnectionDelay(delay), locationInfo(false) #if LOG4CXX_EVENTS_AT_EXIT , atExitRegistryRaii([this]{stopMonitor();}) #endif { } ~SocketAppenderSkeletonPriv() { stopMonitor(); } /** host name */ LogString remoteHost; /** IP address */ helpers::InetAddressPtr address; int port; int reconnectionDelay; bool locationInfo; std::thread thread; std::condition_variable interrupt; std::mutex interrupt_mutex; #if LOG4CXX_EVENTS_AT_EXIT helpers::AtExitRegistry::Raii atExitRegistryRaii; #endif void stopMonitor(); }; } // namespace net } // namespace log4cxx #endif /* LOG4CXX_SOCKETAPPENDERSKELETON_PRIVATE_H */ apache-log4cxx-1.3.1/src/main/include/log4cxx/private/aprsocket.h0000644000175100001770000000262514721727031024245 0ustar runnerdocker/* * 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. */ #ifndef LOG4CXX_HELPERS_APRSOCKET_H #define LOG4CXX_HELPERS_APRSOCKET_H #include struct apr_socket_t; namespace LOG4CXX_NS { namespace helpers { class LOG4CXX_EXPORT APRSocket : public helpers::Socket { public: /** Creates a stream socket and connects it to the specified port number at the specified IP address. */ APRSocket(InetAddressPtr& address, int port); APRSocket(apr_socket_t*, apr_pool_t* pool); virtual size_t write(ByteBuffer&); /** Closes this socket. */ virtual void close(); private: struct APRSocketPriv; }; } } #endif /* LOG4CXX_HELPERS_APRSOCKET_H */ apache-log4cxx-1.3.1/src/main/include/log4cxx/private/socket_priv.h0000644000175100001770000000252614721727031024602 0ustar runnerdocker/* * 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. */ #ifndef LOG4CXX_HELPERS_SOCKET_PRIV_H #define LOG4CXX_HELPERS_SOCKET_PRIV_H #include namespace LOG4CXX_NS { namespace helpers { struct Socket::SocketPrivate { SocketPrivate(const InetAddressPtr& addr = InetAddressPtr(), int _port = 0) : address(addr), port(_port) {} virtual ~SocketPrivate() = default; /** The IP address of the remote end of this socket. */ InetAddressPtr address; /** The port number on the remote host to which this socket is connected. */ int port; }; } } #endif /* LOG4CXX_HELPERS_SOCKET_PRIV_H */ apache-log4cxx-1.3.1/src/main/include/log4cxx/varia/0000755000175100001770000000000014721727031021524 5ustar runnerdockerapache-log4cxx-1.3.1/src/main/include/log4cxx/varia/fallbackerrorhandler.h0000644000175100001770000000654114721727031026052 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_VARIA_FALLBACK_ERROR_HANDLER_H #define _LOG4CXX_VARIA_FALLBACK_ERROR_HANDLER_H #include #include #include #include #include namespace LOG4CXX_NS { namespace varia { /** The FallbackErrorHandler implements the ErrorHandler interface such that a secondary appender may be specified. This secondary appender takes over if the primary appender fails for whatever reason.

The error message is printed on System.err, and logged in the new secondary appender. */ class LOG4CXX_EXPORT FallbackErrorHandler : public virtual spi::ErrorHandler { private: LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(FallbackErrorHandlerPrivate, m_priv) public: DECLARE_LOG4CXX_OBJECT(FallbackErrorHandler) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(FallbackErrorHandler) LOG4CXX_CAST_ENTRY_CHAIN(spi::ErrorHandler) END_LOG4CXX_CAST_MAP() FallbackErrorHandler(); ~FallbackErrorHandler(); /** Adds the logger passed as parameter to the list of loggers that we need to search for in case of appender failure. */ void setLogger(const LoggerPtr& logger) override; /** \copybrief spi::OptionHandler::activateOptions() No action is performed in this implementation. */ void activateOptions(helpers::Pool& p) override; /** \copybrief spi::OptionHandler::setOption() */ void setOption(const LogString& option, const LogString& value) override; /** Prints the message and the stack trace of the exception on System.err. */ void error(const LogString& message, const std::exception& e, int errorCode) const override; /** Prints the message and the stack trace of the exception on System.err. */ void error(const LogString& message, const std::exception& e, int errorCode, const spi::LoggingEventPtr& event) const override; /** Print a the error message passed as parameter on System.err. */ void error(const LogString& /* message */) const override {} /** The appender to which this error handler is attached. */ void setAppender(const AppenderPtr& primary) override; /** Set the backup appender. */ void setBackupAppender(const AppenderPtr& backup) override; /** Has an error been reported? */ #if 15 < LOG4CXX_ABI_VERSION bool errorReported() const override; #else bool errorReported() const; #endif }; LOG4CXX_PTR_DEF(FallbackErrorHandler); } // namespace varia } // namespace log4cxx #endif //_LOG4CXX_VARIA_FALLBACK_ERROR_HANDLER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/hierarchy.h0000644000175100001770000002264514721727031022562 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HIERARCHY_H #define _LOG4CXX_HIERARCHY_H #include #include #include #include namespace LOG4CXX_NS { class Hierarchy; LOG4CXX_PTR_DEF(Hierarchy); /** This class is specialized in retrieving loggers by name and also maintaining the logger hierarchy.

The casual user does not have to deal with this class directly.

The structure of the logger hierarchy is maintained by the #getLogger method. The hierarchy is such that children link to their parent but parents do not have any pointers to their children. Moreover, loggers can be instantiated in any order, in particular descendant before ancestor.

In case a descendant is created before a particular ancestor, then it creates a provision node for the ancestor and adds itself to the provision node. Other descendants of the same ancestor add themselves to the previously created provision node. */ class LOG4CXX_EXPORT Hierarchy : public spi::LoggerRepository { private: LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(HierarchyPrivate, m_priv) public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(Hierarchy) BEGIN_LOG4CXX_CAST_MAP() #if 15 < LOG4CXX_ABI_VERSION LOG4CXX_CAST_ENTRY(Hierarchy) LOG4CXX_CAST_ENTRY_CHAIN(spi::LoggerRepository) #else LOG4CXX_CAST_ENTRY(spi::LoggerRepository) #endif END_LOG4CXX_CAST_MAP() private: /** Create a new logger hierarchy. */ Hierarchy(); public: static HierarchyPtr create(); ~Hierarchy(); void addHierarchyEventListener(const spi::HierarchyEventListenerPtr& listener) override; /** * Remove a previously added HierarchyEventListener. * */ #if LOG4CXX_ABI_VERSION <= 15 void removeHierarchyEventListener(const spi::HierarchyEventListenerPtr& listener); #else void removeHierarchyEventListener(const spi::HierarchyEventListenerPtr& listener) override; #endif /** * Call \c configurator if not yet configured. */ void ensureIsConfigured(std::function configurator) override; /** This call will clear all logger definitions from the internal hashtable. Invoking this method will irrevocably mess up the logger hierarchy.

You should really know what you are doing before invoking this method. */ void clear(); void emitNoAppenderWarning(const Logger* logger) override; /** Check if the named logger exists in the hierarchy. If so return its reference, otherwise returns null. @param name The name of the logger to search for. */ LoggerPtr exists(const LogString& name) override; /** The string form of {@link #setThreshold(const LevelPtr&) setThreshold}. */ void setThreshold(const LogString& levelStr) override; /** Enable logging for logging requests with level newLevel or higher. By default all levels are enabled. @param newLevel The minimum level of logging requests that are sent to appenders. */ void setThreshold(const LevelPtr& newLevel) override; void fireAddAppenderEvent(const Logger* logger, const Appender* appender) override; void fireRemoveAppenderEvent(const Logger* logger, const Appender* appender) override; /** Returns a Level representation of the enable state. */ LevelPtr getThreshold() const override; /** Retrieve the \c name Logger instance using the default factory to create it if required. 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 name The name of the logger to retrieve. */ LoggerPtr getLogger(const LogString& name) override; /** Retrieve the \c name Logger instance using factory to create it if required. 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 name The name of the logger to retrieve. @param factory The factory that will make the new logger instance. */ LoggerPtr getLogger(const LogString& name, const spi::LoggerFactoryPtr& factory) override; /** Returns all the currently defined loggers in this hierarchy as a LoggerList.

The root logger is not included in the returned LoggerList. */ LoggerList getCurrentLoggers() const override; /** Get the root of this hierarchy. */ LoggerPtr getRootLogger() const override; /** This method will return true if this repository is disabled for level object passed as parameter and false otherwise. See also the {@link #setThreshold(const LevelPtr&) setThreshold} method. */ bool isDisabled(int level) const override; /** 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.

*/ void resetConfiguration() override; /** Used by subclasses to add a renderer to the hierarchy passed as parameter. */ /** Shutting down a hierarchy will safely close and remove all appenders in all categories including the root logger.

Some appenders such as {@link net::XMLSocketAppender XMLSocketAppender} 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. */ void shutdown() override; virtual bool isConfigured() override; virtual void setConfigured(bool configured) override; /** Refresh the threshold in children of parent */ void updateChildren(const Logger* parent); void clearAppenders(); void addAppender(AppenderPtr appender); /** Remove the \c name Logger from the hierarchy. Note: The \c name Logger must be retrieved from the hierarchy \b after any subsequent configuration file change for the newly loaded settings to be used. @param name The logger to remove. @param ifNotUsed If true and use_count() indicates there are other references, do not remove the Logger and return false. @returns true if \c name Logger was removed from the hierarchy. */ #if LOG4CXX_ABI_VERSION <= 15 bool removeLogger(const LogString& name, bool ifNotUsed = true); #else bool removeLogger(const LogString& name, bool ifNotUsed = true) override; #endif private: /** * Set the threshold. The mutex must already be locked. */ void setThresholdInternal(const LevelPtr& l); /** * Internal shutdown. The mutex must already be locked. */ void shutdownInternal(); /** This method loops through all the *potential* parents of \c logger using the logger name. For example, for a logger named "w.x.y.z", loop through "w.x.y", "w.x" and "w", but not "w.x.y.z". There 3 possible cases: 1) No entry for the potential parent of "w.x.y.z" exists We create a ProvisionNode for this potential parent and insert "w.x.y.z" in that provision node. 2) There entry is of type Logger for the potential parent. The entry is "w.x.y.z"'s nearest existing parent. We update "w.x.y.z"'s parent field with this entry. We also break from the loop because updating our parent's parent is our parent's responsibility. 3) There entry is of type ProvisionNode for this potential parent. We add "w.x.y.z" to the list of children for this potential parent. */ void updateParents(const LoggerPtr& logger, const LoggerPtr& root); /** We update the links for all the children that placed themselves in the provision node 'pn'. The \c logger argument is a newly created Logger, a potential parent of all the children in 'pn' We loop on all the children 'c' in 'pn': If the child 'c' has been already linked to a child of 'cat' then there is no need to update 'c'. Otherwise, we set the \c logger parent to 'c's parent and set 'c's parent field to \c logger. */ void updateChildren(ProvisionNode& pn, const LoggerPtr& logger); Hierarchy(const Hierarchy&); Hierarchy& operator=(const Hierarchy&); }; } //namespace log4cxx #endif //_LOG4CXX_HIERARCHY_H apache-log4cxx-1.3.1/src/main/include/log4cxx/fileappender.h0000644000175100001770000001571614721727031023243 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_FILE_APPENDER_H #define _LOG4CXX_FILE_APPENDER_H #include #include #include #include #include namespace LOG4CXX_NS { namespace helpers { class Pool; } /** * FileAppender appends log events to a file. * *

Support for java.io.Writer and console appending * has been deprecated and then removed. See the replacement * solutions: WriterAppender and ConsoleAppender. */ class LOG4CXX_EXPORT FileAppender : public WriterAppender { protected: struct FileAppenderPriv; public: DECLARE_LOG4CXX_OBJECT(FileAppender) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(FileAppender) LOG4CXX_CAST_ENTRY_CHAIN(WriterAppender) END_LOG4CXX_CAST_MAP() /** The default constructor does not do anything. */ FileAppender(); /** Instantiate a FileAppender and open the file designated by filename. The opened filename will become the output destination for this appender.

If the append parameter is true, the file will be appended to. Otherwise, the file designated by filename will be truncated before being opened.

If the bufferedIO parameter is true, then buffered IO will be used to write to the output file. */ FileAppender(const LayoutPtr& layout, const LogString& filename, bool append, bool bufferedIO, int bufferSize); /** Instantiate a FileAppender and open the file designated by filename. The opened filename will become the output destination for this appender.

If the append parameter is true, the file will be appended to. Otherwise, the file designated by filename will be truncated before being opened. */ FileAppender(const LayoutPtr& layout, const LogString& filename, bool append); /** Instantiate a FileAppender and open the file designated by filename. The opened filename will become the output destination for this appender.

The file will be appended to. */ FileAppender(const LayoutPtr& layout, const LogString& filename); ~FileAppender(); /** The File property takes a string value which should be the name of the file to append to.

Note that the special values "System.out" or "System.err" are no longer honored.

Note: Actual opening of the file is made when #activateOptions is called, not when the options are set. */ virtual void setFile(const LogString& file); /** Returns the value of the Append option. */ bool getAppend() const; /** Returns the value of the File option. */ LogString getFile() const; /** \copybrief AppenderSkeleton::activateOptions() Sets and opens the file where the log output will go. The specified file must be writable. If there was already an opened file, then the previous file is closed first. */ void activateOptions(helpers::Pool& p) override; /** \copybrief AppenderSkeleton::setOption() Supported options | Supported values | Default value :-------------- | :----------------: | :---------------: FileName | {any} | - Append | True,False | True BufferedIO | True,False | False ImmediateFlush | True,False | False BufferSize | (\ref fileSz1 "1") | 8 KB \anchor fileSz1 (1) An integer in the range 0 - 2^63. You can specify the value with the suffixes "KB", "MB" or "GB" so that the integer is interpreted being expressed respectively in kilobytes, megabytes or gigabytes. For example, the value "10KB" will be interpreted as 10240. \sa AppenderSkeleton::setOption() */ void setOption(const LogString& option, const LogString& value) override; /** Get the value of the BufferedIO option.

BufferedIO will significatnly increase performance on heavily loaded systems. */ bool getBufferedIO() const; /** Get the size of the IO buffer. */ int getBufferSize() const; /** The Append option takes a boolean value. It is set to true by default. If true, then File will be opened in append mode by #setFile (see above). Otherwise, setFile will open File in truncate mode.

Note: Actual opening of the file is made when #activateOptions is called, not when the options are set. */ void setAppend(bool fileAppend1); /** The BufferedIO option takes a boolean value. It is set to false by default. If true, then File will be opened in buffered mode. BufferedIO will significantly increase performance on heavily loaded systems. */ void setBufferedIO(bool bufferedIO); /** Set the size of the IO buffer. */ void setBufferSize(int bufferSize1); /** * Replaces double backslashes with single backslashes * for compatibility with paths from earlier XML configurations files. * @param name file name * @return corrected file name */ static LogString stripDuplicateBackslashes(const LogString& name); protected: void activateOptionsInternal(LOG4CXX_NS::helpers::Pool& p); /** Sets and opens the file where the log output will go. The specified file must be writable.

If there was already an opened file, then the previous file is closed first.

Do not use this method directly. To configure a FileAppender or one of its subclasses, set its properties one by one and then call activateOptions. The mutex must be locked before calling this function. @param file The path to the log file. @param append If true will append to fileName. Otherwise will truncate fileName. @param bufferedIO Do we do bufferedIO? @param bufferSize How big should the IO buffer be? @param p memory pool for operation. */ void setFileInternal(const LogString& file, bool append, bool bufferedIO, size_t bufferSize, LOG4CXX_NS::helpers::Pool& p); void setFileInternal(const LogString& file); private: FileAppender(const FileAppender&); FileAppender& operator=(const FileAppender&); protected: FileAppender(std::unique_ptr priv); }; // class FileAppender LOG4CXX_PTR_DEF(FileAppender); } // namespace log4cxx #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/logmanager.h0000644000175100001770000002162314721727031022713 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_LOG_MANAGER_H #define _LOG4CXX_LOG_MANAGER_H #include #include #include namespace LOG4CXX_NS { class Logger; typedef std::shared_ptr LoggerPtr; typedef std::vector LoggerList; namespace spi { class LoggerFactory; typedef std::shared_ptr LoggerFactoryPtr; } /** * Use the LogManager class to retreive Logger * instances or to operate on the current * {@link log4cxx::spi::LoggerRepository LoggerRepository}. * DefaultConfigurator::configure will be used to configure LoggerRepository * when the first logger is retrieved if it is not already configured. */ class LOG4CXX_EXPORT LogManager { private: static void* guard; static spi::RepositorySelectorPtr getRepositorySelector(); public: /** Use \c selector to source the {@link spi::LoggerRepository LoggerRepository}, but only if the correct \c guard is passed as parameter.

Initally the guard is null. If the guard is null, then invoking this method sets the logger factory and the guard. Following invocations will throw a {@link helpers::IllegalArgumentException IllegalArgumentException}, unless the previously set \c guard is passed as the second parameter.

This allows a high-level component to set the {@link spi::RepositorySelector RepositorySelector} used by the LogManager. */ static void setRepositorySelector(spi::RepositorySelectorPtr selector, void* guard); static spi::LoggerRepositoryPtr getLoggerRepository(); /** Retrieve the root logger from the {@link spi::LoggerRepository LoggerRepository}. Calls {@link spi::LoggerRepository::ensureIsConfigured ensureIsConfigured} passing {@link DefaultConfigurator::configure} to ensure the repository is configured. */ static LoggerPtr getRootLogger(); /** Retrieve the \c name Logger instance from the {@link spi::LoggerRepository LoggerRepository} using the default factory to create it if required. Calls {@link spi::LoggerRepository::ensureIsConfigured ensureIsConfigured} passing {@link DefaultConfigurator::configure} to ensure the repository is configured. */ static LoggerPtr getLogger(const std::string& name); /** Retrieve the \c name Logger instance from the {@link spi::LoggerRepository LoggerRepository} using \c factory to create it if required. Calls {@link spi::LoggerRepository::ensureIsConfigured ensureIsConfigured} passing {@link DefaultConfigurator::configure} to ensure the repository is configured. */ static LoggerPtr getLogger(const std::string& name, const spi::LoggerFactoryPtr& factory); /** A pointer to the Logger \c name instance if it exists in the {@link spi::LoggerRepository LoggerRepository}. @returns A null pointer unless the \c name Logger already exists. */ static LoggerPtr exists(const std::string& name); #if LOG4CXX_WCHAR_T_API /** Retrieve the \c name Logger instance from the {@link spi::LoggerRepository LoggerRepository} using the default factory to create it if required. Calls {@link spi::LoggerRepository::ensureIsConfigured ensureIsConfigured} passing {@link DefaultConfigurator::configure} to ensure the repository is configured. */ static LoggerPtr getLogger(const std::wstring& name); /** Retrieve the \c name Logger instance from the {@link spi::LoggerRepository LoggerRepository} using \c factory to create it if required. Calls {@link spi::LoggerRepository::ensureIsConfigured ensureIsConfigured} passing {@link DefaultConfigurator::configure} to ensure the repository is configured. */ static LoggerPtr getLogger(const std::wstring& name, const spi::LoggerFactoryPtr& factory); /** A pointer to the Logger \c name instance if it exists in the {@link spi::LoggerRepository LoggerRepository}. @returns A null pointer unless the \c name Logger already exists. */ static LoggerPtr exists(const std::wstring& name); #endif #if LOG4CXX_UNICHAR_API /** Retrieve the \c name Logger instance from the {@link spi::LoggerRepository LoggerRepository} using the default factory to create it if required. Calls {@link spi::LoggerRepository::ensureIsConfigured ensureIsConfigured} passing {@link DefaultConfigurator::configure} to ensure the repository is configured. */ static LoggerPtr getLogger(const std::basic_string& name); /** Retrieve the \c name Logger instance from the {@link spi::LoggerRepository LoggerRepository} using \c factory to create it if required. Calls {@link spi::LoggerRepository::ensureIsConfigured ensureIsConfigured} passing {@link DefaultConfigurator::configure} to ensure the repository is configured. */ static LoggerPtr getLogger(const std::basic_string& name, const spi::LoggerFactoryPtr& factory); /** A pointer to the Logger \c name instance if it exists in the {@link spi::LoggerRepository LoggerRepository}. @returns A null pointer unless the \c name Logger already exists. */ static LoggerPtr exists(const std::basic_string& name); #endif #if LOG4CXX_CFSTRING_API /** Retrieve the \c name Logger instance from the {@link spi::LoggerRepository LoggerRepository} using the default factory to create it if required. Calls {@link spi::LoggerRepository::ensureIsConfigured ensureIsConfigured} passing {@link DefaultConfigurator::configure} to ensure the repository is configured. */ static LoggerPtr getLogger(const CFStringRef& name); /** Retrieve the \c name Logger instance from the {@link spi::LoggerRepository LoggerRepository} using \c factory to create it if required. Calls {@link spi::LoggerRepository::ensureIsConfigured ensureIsConfigured} passing {@link DefaultConfigurator::configure} to ensure the repository is configured. */ static LoggerPtr getLogger(const CFStringRef& name, const spi::LoggerFactoryPtr& factory); /** A pointer to the Logger \c name instance if it exists in the {@link spi::LoggerRepository LoggerRepository}. @returns A null pointer unless the \c name Logger already exists. */ static LoggerPtr exists(const CFStringRef& name); #endif /** Retrieve the \c name Logger instance from the {@link spi::LoggerRepository LoggerRepository} using the default factory to create it if required. Calls {@link spi::LoggerRepository::ensureIsConfigured ensureIsConfigured} passing {@link DefaultConfigurator::configure} to ensure the repository is configured. */ static LoggerPtr getLoggerLS(const LogString& name); /** Retrieve the \c name Logger instance from the {@link spi::LoggerRepository LoggerRepository} using \c factory to create it if required. Calls {@link spi::LoggerRepository::ensureIsConfigured ensureIsConfigured} passing {@link DefaultConfigurator::configure} to ensure the repository is configured. */ static LoggerPtr getLoggerLS(const LogString& name, const spi::LoggerFactoryPtr& factory); /** A pointer to the Logger \c name instance if it exists in the {@link spi::LoggerRepository LoggerRepository}. @returns A null pointer unless the \c name Logger already exists. */ static LoggerPtr existsLS(const LogString& name); static LoggerList getCurrentLoggers(); /** Safely close and remove all appenders in all loggers including the root logger. */ static void shutdown(); /** Reset all values contained in this current {@link spi::LoggerRepository LoggerRepository} to their default. */ static void resetConfiguration(); /** Remove the \c name Logger from the {@link spi::LoggerRepository LoggerRepository}. Note: The \c name Logger must be retrieved from the {@link spi::LoggerRepository LoggerRepository} \b after any subsequent configuration file change for the newly loaded settings to be used. @param name The logger to remove. @param ifNotUsed If true and use_count() indicates there are other references, do not remove the Logger and return false. @returns true if \c name Logger was removed from the {@link spi::LoggerRepository LoggerRepository}. */ static bool removeLogger(const LogString& name, bool ifNotUsed = true); }; // class LogManager } // namespace log4cxx #endif //_LOG4CXX_LOG_MANAGER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/ndc.h0000644000175100001770000002442214721727031021343 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_NDC_H #define _LOG4CXX_NDC_H #include #include #include namespace LOG4CXX_NS { /** A Nested Diagnostic Context, or #NDC in short, is an instrument to distinguish interleaved log output from different sources. Log output is typically interleaved when a server handles multiple clients near-simultaneously. Interleaved log output can still be meaningful if each log entry from different contexts have a distinctive stamp. This is where contexts come into play. #NDC provides a constructor and destructor which simply call the #push and #pop methods, allowing for automatic cleanup when the current scope ends. #NDC operations such as #push, #pop, #clear and #remove affect only logging events emitted in the calling thread. The contexts of other threads are not changed. That is, contexts are managed on a per thread basis. For example, a servlet can build a per client request context consisting of the client's host name and other information contained in the the request. Cookies are another source of distinctive information. Contexts can be nested:

  • when entering a context, initialize a log4cxx::NDC type variable with a distinctive string. If there is no nested diagnostic context for the current thread, a NDC stack will be created. The distinctive string will be automatically removed from the current thread's context stack when the variable goes out of scope.
  • when exiting a thread call NDC::remove to deal with any #push operation not matched with a corresponding #pop.
If configured to do so, PatternLayout, xml::XMLLayout and JSONLayout instances automatically retrieve the nested diagnostic context for the current thread without any user intervention. hence, even if a process is serving multiple clients simultaneously, the logging events emanating from the same code (belonging to the same logger) can still be distinguished because each client request will have a different tag. #NDC implements nested diagnostic contexts as defined by Neil Harrison in the article "Patterns for Logging Diagnostic Messages" part of the book "Pattern Languages of Program Design 3" edited by Martin et al. */ class LOG4CXX_EXPORT NDC { public: /** * Pair of Message and FullMessage. */ typedef std::pair DiagnosticContext; typedef std::stack Stack; /** Add \c message onto the context stack. @see The #push method. @param message The text added to the diagnostic context information. */ NDC(const std::string& message); /** Remove the topmost element from the context stack associated with the current thread. @see The #pop method. */ ~NDC(); /** Clear any nested diagnostic information if any. This method is useful in cases where the same thread can be potentially used over and over in different unrelated contexts. */ static void clear(); /** Clone the diagnostic context for the current thread.

Internally a diagnostic context is represented as a stack. A given thread can supply the stack (i.e. diagnostic context) to a child thread so that the child can inherit the parent thread's diagnostic context.

The child thread uses the #inherit method to inherit the parent's diagnostic context.

If not passed to #inherit, returned stack should be deleted by caller. @return Stack A clone of the current thread's diagnostic context, will not be null. */ static Stack* cloneStack(); /** Inherit the diagnostic context of another thread.

The parent thread can obtain a reference to its diagnostic context using the #cloneStack method. It should communicate this information to its child so that it may inherit the parent's diagnostic context.

The parent's diagnostic context is cloned before being inherited. In other words, once inherited, the two diagnostic contexts can be managed independently. @param stack The diagnostic context of the parent thread, will be deleted during call. If NULL, NDC will not be modified. */ static void inherit(Stack* stack); /** * Get the current value of the NDC of the * currrent thread. * @param dest destination to which to append content of NDC. * @return true if NDC is set. */ static bool get(LogString& dest); /** Get the current nesting depth of this diagnostic context. */ static int getDepth(); /** * Tests if the NDC is empty. */ static bool empty(); /** Get the value at the top of the stack associated with the current thread and then remove it.

The returned value is the value that was pushed last. If no context is available, then the empty string "" is returned. @return String The text of the innermost diagnostic context. */ static LogString pop(); /** Append to \c buf the top value in the stack associated with the current thread and then remove it. @param buf to which top value is appended. @return true if NDC contained at least one value. */ static bool pop(std::string& buf); /** Get the value at the top of the stack associated with the current thread without removing it.

The returned value is the value that was pushed last. If no context is available, then the empty string "" is returned. @return String The text of the innermost diagnostic context. */ static LogString peek(); /** Append to \c buf the top value in the stack associated with the current thread without removing it. @param buf to which top value is appended. @return true if NDC contained at least one value. */ static bool peek(std::string& buf); /** Add \c message to the stack associated with the current thread.

The contents of the message parameter is determined solely by the client. @param message The text added to the diagnostic context information. */ static void push(const std::string& message); /** Add \c message to the stack associated with the current thread.

The contents of the message parameter is determined solely by the client. @param message The text added to the diagnostic context information. */ static void pushLS(const LogString& message); /** Remove all the diagnostic context data for this thread.

A thread that adds to a diagnostic context by calling #push should call this method before exiting to prevent unbounded memory usage. */ static void remove(); #if LOG4CXX_WCHAR_T_API /** Add \c message onto the context stack. @see The #push method. @param message The text added to the diagnostic context information. */ NDC(const std::wstring& message); /** Add \c message to the stack associated with the current thread. @param message The text added to the diagnostic context information. */ static void push(const std::wstring& message); /** Append to \c dst the top value in the stack associated with the current thread without removing it. @param dst to which top value is appended. @return true if NDC contained at least one value. */ static bool peek(std::wstring& dst); /** * Appends the current NDC content to the provided string and removes the value from the NDC. * @param dst destination. * @return true if NDC value set. */ static bool pop(std::wstring& dst); #endif #if LOG4CXX_UNICHAR_API /** Add \c message onto the context stack. @see The #push method. @param message The text added to the diagnostic context information. */ NDC(const std::basic_string& message); /** Add \c message to the stack associated with the current thread.

The contents of the message parameter is determined solely by the client. @param message The text added to the diagnostic context information. */ static void push(const std::basic_string& message); /** Append to \c dst the top value in the stack associated with the current thread without removing it. @param dst to which top value is appended. @return true if NDC contained at least one value. */ static bool peek(std::basic_string& dst); /** Append to \c dst the top value in the stack associated with the current thread and then remove it. @param dst to which top value is appended. @return true if NDC contained at least one value. */ static bool pop(std::basic_string& dst); #endif #if LOG4CXX_CFSTRING_API /** Add \c message onto the context stack. @see The #push method. @param message The text added to the diagnostic context information. */ NDC(const CFStringRef& message); /** Add \c message to the stack associated with the current thread. @param message The text added to the diagnostic context information. */ static void push(const CFStringRef& message); /** Append to \c dst the top value in the stack associated with the current thread without removing it. @param dst to which top value is appended. @return true if NDC contained at least one value. */ static bool peek(CFStringRef& dst); /** Append to \c dst the top value in the stack associated with the current thread and then remove it. @param dst to which top value is appended. @return true if NDC contained at least one value. */ static bool pop(CFStringRef& dst); #endif static const LogString& getMessage(const DiagnosticContext& ctx); static const LogString& getFullMessage(const DiagnosticContext& ctx); private: NDC(const NDC&); NDC& operator=(const NDC&); }; // class NDC; } // namespace log4cxx #endif // _LOG4CXX_NDC_H apache-log4cxx-1.3.1/src/main/include/log4cxx/logger.h0000644000175100001770000030026014721727031022053 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_LOGGER_H #define _LOG4CXX_LOGGER_H #include #include #include #include #include #include namespace LOG4CXX_NS { namespace spi { class LoggerRepository; LOG4CXX_PTR_DEF(LoggerRepository); class LoggerFactory; LOG4CXX_PTR_DEF(LoggerFactory); } class Logger; /** smart pointer to a Logger class */ LOG4CXX_PTR_DEF(Logger); LOG4CXX_LIST_DEF(LoggerList, LoggerPtr); /** This is the central class in the log4cxx package. Most logging operations, except configuration, are done through this class. */ class LOG4CXX_EXPORT Logger : public virtual spi::AppenderAttachable { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(Logger) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(Logger) LOG4CXX_CAST_ENTRY(spi::AppenderAttachable) END_LOG4CXX_CAST_MAP() private: LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(LoggerPrivate, m_priv) int m_threshold; //!< The cached level of this logger public: /** This constructor initializes a new logger instance and sets its name.

It is intended to be only used by factory-classes. */ Logger(const LogString& name); #if LOG4CXX_ABI_VERSION <= 15 [[ deprecated( "Pool is no longer required" ) ]] Logger(helpers::Pool& pool, const LogString& name); #endif ~Logger(); /** Add newAppender to the list of appenders of this Logger instance.

If newAppender is already in the list of appenders, then it won't be added again. */ void addAppender(const AppenderPtr newAppender) override; /** Call the appenders in the hierrachy starting at this. If no appenders could be found, emit a warning.

This method calls all the appenders inherited from the hierarchy circumventing any evaluation of whether to log or not to log the particular log request. @param event the event to log. @param p memory pool for any allocations needed to process request. */ void callAppenders(const spi::LoggingEventPtr& event, helpers::Pool& p) const; /** Close all attached appenders implementing the AppenderAttachable interface. */ void closeNestedAppenders(); /** Add a new logging event containing \c msg and \c location to attached appender(s) if this logger is enabled for DEBUG events.

This method first checks if this logger is DEBUG enabled by comparing the level of this logger with the DEBUG level. If this logger is DEBUG enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. @param location The source code location of the logging request. */ void debug(const std::string& msg, const LOG4CXX_NS::spi::LocationInfo& location) const; /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for DEBUG events.

This method first checks if this logger is DEBUG enabled by comparing the level of this logger with the DEBUG level. If this logger is DEBUG enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. See also #LOG4CXX_DEBUG. */ void debug(const std::string& msg) const; #if LOG4CXX_WCHAR_T_API /** Add a new logging event containing \c msg and \c location to attached appender(s) if this logger is enabled for DEBUG events.

This method first checks if this logger is DEBUG enabled by comparing the level of this logger with the DEBUG level. If this logger is DEBUG enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. @param location The source code location of the logging request. See also #LOG4CXX_DEBUG. */ void debug(const std::wstring& msg, const LOG4CXX_NS::spi::LocationInfo& location) const; /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for DEBUG events.

This method first checks if this logger is DEBUG enabled by comparing the level of this logger with the DEBUG level. If this logger is DEBUG enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. See also #LOG4CXX_DEBUG. */ void debug(const std::wstring& msg) const; #endif #if LOG4CXX_UNICHAR_API /** Add a new logging event containing \c msg and \c location to attached appender(s) if this logger is enabled for DEBUG events.

This method first checks if this logger is DEBUG enabled by comparing the level of this logger with the DEBUG level. If this logger is DEBUG enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. @param location The source code location of the logging request. See also #LOG4CXX_DEBUG. */ void debug(const std::basic_string& msg, const LOG4CXX_NS::spi::LocationInfo& location) const; /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for DEBUG events.

This method first checks if this logger is DEBUG enabled by comparing the level of this logger with the DEBUG level. If this logger is DEBUG enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. See also #LOG4CXX_DEBUG. */ void debug(const std::basic_string& msg) const; #endif #if LOG4CXX_CFSTRING_API /** Add a new logging event containing \c msg and \c location to attached appender(s) if this logger is enabled for DEBUG events.

This method first checks if this logger is DEBUG enabled by comparing the level of this logger with the DEBUG level. If this logger is DEBUG enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. @param location The source code location of the logging request. See also #LOG4CXX_DEBUG. */ void debug(const CFStringRef& msg, const LOG4CXX_NS::spi::LocationInfo& location) const; /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for DEBUG events.

This method first checks if this logger is DEBUG enabled by comparing the level of this logger with the DEBUG level. If this logger is DEBUG enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. See also #LOG4CXX_DEBUG. */ void debug(const CFStringRef& msg) const; #endif /** Add a new logging event containing \c msg and \c location to attached appender(s) if this logger is enabled for ERROR events.

This method first checks if this logger is ERROR enabled by comparing the level of this logger with the ERROR level. If this logger is ERROR enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. @param location The source code location of the logging request. See also #LOG4CXX_ERROR. */ void error(const std::string& msg, const LOG4CXX_NS::spi::LocationInfo& location) const; /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for ERROR events.

This method first checks if this logger is ERROR enabled by comparing the level of this logger with the ERROR level. If this logger is ERROR enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. See also #LOG4CXX_ERROR. */ void error(const std::string& msg) const; #if LOG4CXX_WCHAR_T_API /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for ERROR events.

This method first checks if this logger is ERROR enabled by comparing the level of this logger with the ERROR level. If this logger is ERROR enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. See also #LOG4CXX_ERROR. */ void error(const std::wstring& msg) const; /** Add a new logging event containing \c msg and \c location to attached appender(s) if this logger is enabled for ERROR events.

This method first checks if this logger is ERROR enabled by comparing the level of this logger with the ERROR level. If this logger is ERROR enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. @param location The source code location of the logging request. See also #LOG4CXX_ERROR. */ void error(const std::wstring& msg, const LOG4CXX_NS::spi::LocationInfo& location) const; #endif #if LOG4CXX_UNICHAR_API /** Add a new logging event containing \c msg and \c location to attached appender(s) if this logger is enabled for ERROR events.

This method first checks if this logger is ERROR enabled by comparing the level of this logger with the ERROR level. If this logger is ERROR enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. @param location The source code location of the logging request. See also #LOG4CXX_ERROR. */ void error(const std::basic_string& msg, const LOG4CXX_NS::spi::LocationInfo& location) const; /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for ERROR events.

This method first checks if this logger is ERROR enabled by comparing the level of this logger with the ERROR level. If this logger is ERROR enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. See also #LOG4CXX_ERROR. */ void error(const std::basic_string& msg) const; #endif #if LOG4CXX_CFSTRING_API /** Add a new logging event containing \c msg and \c location to attached appender(s) if this logger is enabled for ERROR events.

This method first checks if this logger is ERROR enabled by comparing the level of this logger with the ERROR level. If this logger is ERROR enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. @param location The source code location of the logging request. See also #LOG4CXX_ERROR. */ void error(const CFStringRef& msg, const LOG4CXX_NS::spi::LocationInfo& location) const; /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for ERROR events.

This method first checks if this logger is ERROR enabled by comparing the level of this logger with the ERROR level. If this logger is ERROR enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. See also #LOG4CXX_ERROR. */ void error(const CFStringRef& msg) const; #endif /** Add a new logging event containing \c msg and \c location to attached appender(s) if this logger is enabled for FATAL events.

This method first checks if this logger is FATAL enabled by comparing the level of this logger with the FATAL level. If this logger is FATAL enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. @param location The source code location of the logging request. See also #LOG4CXX_FATAL. */ void fatal(const std::string& msg, const LOG4CXX_NS::spi::LocationInfo& location) const; /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for FATAL events.

This method first checks if this logger is ERROR enabled by comparing the level of this logger with the ERROR level. If this logger is ERROR enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. See also #LOG4CXX_FATAL. */ void fatal(const std::string& msg) const; #if LOG4CXX_WCHAR_T_API /** Add a new logging event containing \c msg and \c location to attached appender(s) if this logger is enabled for FATAL events.

This method first checks if this logger is ERROR enabled by comparing the level of this logger with the ERROR level. If this logger is ERROR enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. @param location The source code location of the logging request. See also #LOG4CXX_FATAL. */ void fatal(const std::wstring& msg, const LOG4CXX_NS::spi::LocationInfo& location) const; /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for FATAL events.

This method first checks if this logger is ERROR enabled by comparing the level of this logger with the ERROR level. If this logger is ERROR enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. See also #LOG4CXX_FATAL. */ void fatal(const std::wstring& msg) const; #endif #if LOG4CXX_UNICHAR_API /** Add a new logging event containing \c msg and \c location to attached appender(s) if this logger is enabled for FATAL events.

This method first checks if this logger is ERROR enabled by comparing the level of this logger with the ERROR level. If this logger is ERROR enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. @param location The source code location of the logging request. See also #LOG4CXX_FATAL. */ void fatal(const std::basic_string& msg, const LOG4CXX_NS::spi::LocationInfo& location) const; /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for FATAL events.

This method first checks if this logger is ERROR enabled by comparing the level of this logger with the ERROR level. If this logger is ERROR enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. See also #LOG4CXX_FATAL. */ void fatal(const std::basic_string& msg) const; #endif #if LOG4CXX_CFSTRING_API /** Add a new logging event containing \c msg and \c location to attached appender(s) if this logger is enabled for FATAL events.

This method first checks if this logger is ERROR enabled by comparing the level of this logger with the ERROR level. If this logger is ERROR enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. @param location The source code location of the logging request. See also #LOG4CXX_FATAL. */ void fatal(const CFStringRef& msg, const LOG4CXX_NS::spi::LocationInfo& location) const; /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for FATAL events.

This method first checks if this logger is ERROR enabled by comparing the level of this logger with the ERROR level. If this logger is ERROR enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. See also #LOG4CXX_FATAL. */ void fatal(const CFStringRef& msg) const; #endif /** Add a new logging event containing \c message and \c location to attached appender(s) without further checks. @param level The logging event level. @param message The text to add to the logging event. @param location The source code location of the logging request. */ void addEvent(const LevelPtr& level, std::string&& message , const spi::LocationInfo& location = spi::LocationInfo::getLocationUnavailable()) const; /** Add a new fatal level logging event containing \c message and \c location to attached appender(s) without further checks. @param message The text to add to the logging event. @param location The source code location of the logging request. */ void addFatalEvent(std::string&& message, const spi::LocationInfo& location = spi::LocationInfo::getLocationUnavailable()) const; /** Add a new error level logging event containing \c message and \c location to attached appender(s) without further checks. @param message The text to add to the logging event. @param location The source code location of the logging request. */ void addErrorEvent(std::string&& message, const spi::LocationInfo& location = spi::LocationInfo::getLocationUnavailable()) const; /** Add a new warning level logging event containing \c message and \c location to attached appender(s) without further checks. @param message The text to add to the logging event. @param location The source code location of the logging request. */ void addWarnEvent(std::string&& message, const spi::LocationInfo& location = spi::LocationInfo::getLocationUnavailable()) const; /** Add a new info level logging event containing \c message and \c location to attached appender(s) without further checks. @param message The text to add to the logging event. @param location The source code location of the logging request. */ void addInfoEvent(std::string&& message, const spi::LocationInfo& location = spi::LocationInfo::getLocationUnavailable()) const; /** Add a new debug level logging event containing \c message and \c location to attached appender(s) without further checks. @param message The text to add to the logging event. @param location The source code location of the logging request. */ void addDebugEvent(std::string&& message, const spi::LocationInfo& location = spi::LocationInfo::getLocationUnavailable()) const; /** Add a new trace level logging event containing \c message and \c location to attached appender(s) without further checks. @param message The text to add to the logging event. @param location The source code location of the logging request. */ void addTraceEvent(std::string&& message, const spi::LocationInfo& location = spi::LocationInfo::getLocationUnavailable()) const; /** Add a new logging event containing \c message and \c location to attached appender(s) without further checks. @param level The logging event level. @param message The text to add to the logging event. @param location The source code location of the logging request. */ void forcedLog(const LevelPtr& level, const std::string& message, const LOG4CXX_NS::spi::LocationInfo& location) const; /** Add a new logging event containing \c message to attached appender(s) without further checks. @param level The logging event level. @param message The text to add to the logging event. */ void forcedLog(const LevelPtr& level, const std::string& message) const; #if LOG4CXX_WCHAR_T_API /** Add a new logging event containing \c message and \c location to attached appender(s) without further checks. @param level The logging event level. @param message The text to add to the logging event. @param location The source code location of the logging request. */ void addEvent(const LevelPtr& level, std::wstring&& message , const spi::LocationInfo& location = spi::LocationInfo::getLocationUnavailable()) const; /** Add a new fatal level logging event containing \c message and \c location to attached appender(s) without further checks. @param message The text to add to the logging event. @param location The source code location of the logging request. */ void addFatalEvent(std::wstring&& message, const spi::LocationInfo& location = spi::LocationInfo::getLocationUnavailable()) const; /** Add a new error level logging event containing \c message and \c location to attached appender(s) without further checks. @param message The text to add to the logging event. @param location The source code location of the logging request. */ void addErrorEvent(std::wstring&& message, const spi::LocationInfo& location = spi::LocationInfo::getLocationUnavailable()) const; /** Add a new warning level logging event containing \c message and \c location to attached appender(s) without further checks. @param message The text to add to the logging event. @param location The source code location of the logging request. */ void addWarnEvent(std::wstring&& message, const spi::LocationInfo& location = spi::LocationInfo::getLocationUnavailable()) const; /** Add a new info level logging event containing \c message and \c location to attached appender(s) without further checks. @param message The text to add to the logging event. @param location The source code location of the logging request. */ void addInfoEvent(std::wstring&& message, const spi::LocationInfo& location = spi::LocationInfo::getLocationUnavailable()) const; /** Add a new debug level logging event containing \c message and \c location to attached appender(s) without further checks. @param message The text to add to the logging event. @param location The source code location of the logging request. */ void addDebugEvent(std::wstring&& message, const spi::LocationInfo& location = spi::LocationInfo::getLocationUnavailable()) const; /** Add a new trace level logging event containing \c message and \c location to attached appender(s) without further checks. @param message The text to add to the logging event. @param location The source code location of the logging request. */ void addTraceEvent(std::wstring&& message, const spi::LocationInfo& location = spi::LocationInfo::getLocationUnavailable()) const; /** Add a new logging event containing \c message and \c location to attached appender(s) without further checks. @param level The logging event level. @param message The text to add to the logging event. @param location The source code location of the logging request. */ void forcedLog(const LevelPtr& level, const std::wstring& message, const LOG4CXX_NS::spi::LocationInfo& location) const; /** Add a new logging event containing \c message to attached appender(s) without further checks. @param level The logging event level. @param message The text to add to the logging event. */ void forcedLog(const LevelPtr& level, const std::wstring& message) const; #endif #if LOG4CXX_UNICHAR_API /** Add a new logging event containing \c message and \c location to attached appender(s) without further checks. @param level The logging event level. @param message The text to add to the logging event. @param location The source code location of the logging request. */ void addEvent(const LevelPtr& level, std::basic_string&& message, const spi::LocationInfo& location = spi::LocationInfo::getLocationUnavailable()) const; /** Add a new fatal level logging event containing \c message and \c location to attached appender(s) without further checks. @param message The text to add to the logging event. @param location The source code location of the logging request. */ void addFatalEvent(std::basic_string&& message,const spi::LocationInfo& location = spi::LocationInfo::getLocationUnavailable()) const; /** Add a new error level logging event containing \c message and \c location to attached appender(s) without further checks. @param message The text to add to the logging event. @param location The source code location of the logging request. */ void addErrorEvent(std::basic_string&& message,const spi::LocationInfo& location = spi::LocationInfo::getLocationUnavailable()) const; /** Add a new warning level logging event containing \c message and \c location to attached appender(s) without further checks. @param message The text to add to the logging event. @param location The source code location of the logging request. */ void addWarnEvent(std::basic_string&& message,const spi::LocationInfo& location = spi::LocationInfo::getLocationUnavailable()) const; /** Add a new info level logging event containing \c message and \c location to attached appender(s) without further checks. @param message The text to add to the logging event. @param location The source code location of the logging request. */ void addInfoEvent(std::basic_string&& message,const spi::LocationInfo& location = spi::LocationInfo::getLocationUnavailable()) const; /** Add a new debug level logging event containing \c message and \c location to attached appender(s) without further checks. @param message The text to add to the logging event. @param location The source code location of the logging request. */ void addDebugEvent(std::basic_string&& message,const spi::LocationInfo& location = spi::LocationInfo::getLocationUnavailable()) const; /** Add a new trace level logging event containing \c message and \c location to attached appender(s) without further checks. @param message The text to add to the logging event. @param location The source code location of the logging request. */ void addTraceEvent(std::basic_string&& message,const spi::LocationInfo& location = spi::LocationInfo::getLocationUnavailable()) const; /** Add a new logging event containing \c message and \c location to attached appender(s) without further checks. @param level The logging event level. @param message The text to add to the logging event. @param location The source code location of the logging request. */ void forcedLog(const LevelPtr& level, const std::basic_string& message, const LOG4CXX_NS::spi::LocationInfo& location) const; /** Add a new logging event containing \c message to attached appender(s) without further checks. @param level The logging event level. @param message The text to add to the logging event. */ void forcedLog(const LevelPtr& level, const std::basic_string& message) const; #endif #if LOG4CXX_CFSTRING_API /** Add a new logging event containing \c message and \c location to attached appender(s) without further checks. @param level The logging event level. @param message The text to add to the logging event. @param location The source code location of the logging request. */ void forcedLog(const LevelPtr& level, const CFStringRef& message, const LOG4CXX_NS::spi::LocationInfo& location) const; /** Add a new logging event containing \c message to attached appender(s) without further checks. @param level The logging event level. @param message The text to add to the logging event. */ void forcedLog(const LevelPtr& level, const CFStringRef& message) const; #endif /** Add a new logging event containing \c message and \c location to attached appender(s) without further checks. @param level The logging event level. @param message the message string to log. @param location location of the logging statement. */ void addEventLS(const LevelPtr& level, LogString&& message , const spi::LocationInfo& location = spi::LocationInfo::getLocationUnavailable()) const; /** Add a new logging event containing \c message and \c location to attached appender(s) without further checks. @param level The logging event level. @param message the message string to log. @param location location of the logging statement. */ void forcedLogLS(const LevelPtr& level, const LogString& message, const LOG4CXX_NS::spi::LocationInfo& location) const; /** Get the additivity flag for this logger. */ bool getAdditivity() const; /** Get the appenders contained in this logger as an AppenderList. If no appenders can be found, then an empty AppenderList is returned. @return AppenderList An collection of the appenders in this logger.*/ AppenderList getAllAppenders() const override; /** Look for the appender named as name.

Return the appender with that name if in the list. Return NULL otherwise. */ AppenderPtr getAppender(const LogString& name) const override; /** Starting from this logger, search the logger hierarchy for a non-null level and return it.

The Logger class is designed so that this method executes as quickly as possible. @throws RuntimeException if all levels are null in the hierarchy */ virtual const LevelPtr& getEffectiveLevel() const; /** Return the the LoggerRepository where this Logger is attached. */ LOG4CXX_NS::spi::LoggerRepository* getLoggerRepository() const; /** * Get the logger name. * @return logger name as LogString. */ const LogString& getName() const; /** * Put name of this logger into \c name in current encoding. * @param name buffer to which name is appended. */ void getName(std::string& name) const; #if LOG4CXX_WCHAR_T_API /** * Put name of this logger into \c name. * @param name buffer to which name is appended. */ void getName(std::wstring& name) const; #endif #if LOG4CXX_UNICHAR_API /** * Put name of this logger into \c name. * @param name buffer to which name is appended. */ void getName(std::basic_string& name) const; #endif #if LOG4CXX_CFSTRING_API /** * Put name of this logger into \c name. * @param name buffer to which name is appended. */ void getName(CFStringRef& name) const; #endif /** The parent of this logger. Note that the parent of a given logger may change during the lifetime of the logger.

The root logger will return 0. */ LoggerPtr getParent() const; /** The assigned Level, if any, for this logger. @return Level - the assigned Level, can be null. */ const LevelPtr& getLevel() const; /** * Retrieve a logger by name in current encoding. * @param name logger name. */ static LoggerPtr getLogger(const std::string& name); /** * Retrieve a logger by name in current encoding. * @param name logger name. */ static LoggerPtr getLogger(const char* const name); #if LOG4CXX_WCHAR_T_API /** * Retrieve a logger by name. * @param name logger name. */ static LoggerPtr getLogger(const std::wstring& name); /** * Retrieve a logger by name. * @param name logger name. */ static LoggerPtr getLogger(const wchar_t* const name); #endif #if LOG4CXX_UNICHAR_API /** * Retrieve a logger by name. * @param name logger name. */ static LoggerPtr getLogger(const std::basic_string& name); #endif #if LOG4CXX_CFSTRING_API /** * Retrieve a logger by name. * @param name logger name. */ static LoggerPtr getLogger(const CFStringRef& name); #endif /** * Retrieve a logger by name in Unicode. * @param name logger name. */ static LoggerPtr getLoggerLS(const LogString& name); /** Retrieve the root logger. */ static LoggerPtr getRootLogger(); /** Like #getLogger except that the type of logger instantiated depends on the type returned by the LoggerFactory#makeNewLoggerInstance method of the factory parameter.

This method is intended to be used by sub-classes. @param name The name of the logger to retrieve. @param factory A LoggerFactory implementation that will actually create a new Instance. */ static LoggerPtr getLoggerLS(const LogString& name, const LOG4CXX_NS::spi::LoggerFactoryPtr& factory); /** Like #getLogger except that the type of logger instantiated depends on the type returned by the LoggerFactory#makeNewLoggerInstance method of the factory parameter.

This method is intended to be used by sub-classes. @param name The name of the logger to retrieve. @param factory A LoggerFactory implementation that will actually create a new Instance. */ static LoggerPtr getLogger(const std::string& name, const LOG4CXX_NS::spi::LoggerFactoryPtr& factory); #if LOG4CXX_WCHAR_T_API /** Like #getLogger except that the type of logger instantiated depends on the type returned by the LoggerFactory#makeNewLoggerInstance method of the factory parameter.

This method is intended to be used by sub-classes. @param name The name of the logger to retrieve. @param factory A LoggerFactory implementation that will actually create a new Instance. */ static LoggerPtr getLogger(const std::wstring& name, const LOG4CXX_NS::spi::LoggerFactoryPtr& factory); #endif #if LOG4CXX_UNICHAR_API /** Like #getLogger except that the type of logger instantiated depends on the type returned by the LoggerFactory#makeNewLoggerInstance method of the factory parameter.

This method is intended to be used by sub-classes. @param name The name of the logger to retrieve. @param factory A LoggerFactory implementation that will actually create a new Instance. */ static LoggerPtr getLogger(const std::basic_string& name, const LOG4CXX_NS::spi::LoggerFactoryPtr& factory); #endif #if LOG4CXX_CFSTRING_API /** Like #getLogger except that the type of logger instantiated depends on the type returned by the LoggerFactory#makeNewLoggerInstance method of the factory parameter.

This method is intended to be used by sub-classes. @param name The name of the logger to retrieve. @param factory A LoggerFactory implementation that will actually create a new Instance. */ static LoggerPtr getLogger(const CFStringRef& name, const LOG4CXX_NS::spi::LoggerFactoryPtr& factory); #endif /** Return the inherited ResourceBundle for this logger. This method walks the hierarchy to find the appropriate resource bundle. It will return the resource bundle attached to the closest ancestor of this logger, much like the way priorities are searched. In case there is no bundle in the hierarchy then NULL is returned. */ helpers::ResourceBundlePtr getResourceBundle() const; protected: /** Returns the string resource corresponding to key in this logger's inherited resource bundle. If the resource cannot be found, then an {@link #error error} message will be logged complaining about the missing resource. @see #getResourceBundle. */ LogString getResourceBundleString(const LogString& key) const; public: /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for INFO events.

This method first checks if this logger is INFO enabled by comparing the level of this logger with the INFO level. If this logger is INFO enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. @param location The source code location of the logging request. See also #LOG4CXX_INFO. */ void info(const std::string& msg, const LOG4CXX_NS::spi::LocationInfo& location) const; /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for INFO events.

This method first checks if this logger is INFO enabled by comparing the level of this logger with the INFO level. If this logger is INFO enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. See also #LOG4CXX_INFO. */ void info(const std::string& msg) const; #if LOG4CXX_WCHAR_T_API /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for INFO events.

This method first checks if this logger is INFO enabled by comparing the level of this logger with the INFO level. If this logger is INFO enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. @param location The source code location of the logging request. See also #LOG4CXX_INFO. */ void info(const std::wstring& msg, const LOG4CXX_NS::spi::LocationInfo& location) const; /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for INFO events.

This method first checks if this logger is INFO enabled by comparing the level of this logger with the INFO level. If this logger is INFO enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. See also #LOG4CXX_INFO. */ void info(const std::wstring& msg) const; #endif #if LOG4CXX_UNICHAR_API /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for INFO events.

This method first checks if this logger is INFO enabled by comparing the level of this logger with the INFO level. If this logger is INFO enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. @param location The source code location of the logging request. */ void info(const std::basic_string& msg, const LOG4CXX_NS::spi::LocationInfo& location) const; /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for INFO events.

This method first checks if this logger is INFO enabled by comparing the level of this logger with the INFO level. If this logger is INFO enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. See also #LOG4CXX_INFO. */ void info(const std::basic_string& msg) const; #endif #if LOG4CXX_CFSTRING_API /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for INFO events.

This method first checks if this logger is INFO enabled by comparing the level of this logger with the INFO level. If this logger is INFO enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. @param location The source code location of the logging request. See also #LOG4CXX_INFO. */ void info(const CFStringRef& msg, const LOG4CXX_NS::spi::LocationInfo& location) const; /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for INFO events.

This method first checks if this logger is INFO enabled by comparing the level of this logger with the INFO level. If this logger is INFO enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. See also #LOG4CXX_INFO. */ void info(const CFStringRef& msg) const; #endif /** Is \c appender attached to this logger? */ bool isAttached(const AppenderPtr appender) const override; /** * Is this logger is enabled for DEBUG level logging events? * *

By writing * ~~~{.cpp} * if(logger->isDebugEnabled()) { * logger->debug("Component: " + std::to_string(componentNumber)); * } * ~~~ * you will not incur the cost of parameter construction * (integer to string conversion plus string concatonation in this case) * if debugging is disabled for logger. * You avoid the cost constructing the message * when the message is not logged. * *

This function allows you to reduce the computational cost of * disabled log debug statements compared to writing: * ~~~{.cpp} * logger->debug("Component: " + std::to_string(componentNumber)); * ~~~ * *

On the other hand, if the logger is enabled for DEBUG logging events, * you will incur the cost of evaluating whether the logger is * enabled twice, once in isDebugEnabled and once in * the DEBUG. This really is an insignificant overhead * since evaluating a the enabled status takes about 1% of the time it * takes to send the message to the appender. * See also #isDebugEnabledFor. * See also #LOG4CXX_DEBUG. * * @return bool - true if this logger is debug * enabled, false otherwise. **/ bool isDebugEnabled() const; /** * Is \c logger is enabled for DEBUG level logging events? * *

By writing * ~~~{.cpp} * if(log4cxx::Logger::isDebugEnabledFor(logger)) { * logger->addDebugEvent("Component: " + std::to_string(componentNumber)); * } * ~~~ * you minimise the computational cost * when \c logger is not enabled for DEBUG logging events. * This function may be inlined thereby avoiding a function call * as well as the cost constructing the message * when \c logger is not enabled for DEBUG events. * * See also #LOG4CXX_DEBUG. * * @return bool - false if \c logger is null * or DEBUG logging events are disabled for \c logger, * true otherwise. **/ inline static bool isDebugEnabledFor(const LoggerPtr& logger) { return logger && logger->m_threshold <= Level::DEBUG_INT && logger->isDebugEnabled(); } /** Is this logger is enabled for logging events at \c level? @return bool True if this logger is enabled for level logging events. */ bool isEnabledFor(const LevelPtr& level) const; /** Is this logger is enabled for INFO level logging events? See #isDebugEnabled. See also #LOG4CXX_INFO. @return bool - true if this logger is enabled for level info, false otherwise. */ bool isInfoEnabled() const; /** Is \c logger is enabled for INFO level logging events? See #isDebugEnabledFor. See also #LOG4CXX_INFO. @return bool - false if \c logger is null or INFO logging events are disabled for \c logger, true otherwise. */ inline static bool isInfoEnabledFor(const LoggerPtr& logger) { return logger && logger->m_threshold <= Level::INFO_INT && logger->isInfoEnabled(); } /** Is this logger is enabled for WARN level logging events? See also #isDebugEnabled. See also #LOG4CXX_WARN. @return bool - true if this logger is enabled for level warn, false otherwise. */ bool isWarnEnabled() const; /** Is \c logger is enabled for WARN level logging events? See #isDebugEnabledFor. See also #LOG4CXX_WARN. @return bool - false if \c logger is null or WARN logging events are disabled for \c logger, true otherwise. */ inline static bool isWarnEnabledFor(const LoggerPtr& logger) { return logger && logger->m_threshold <= Level::WARN_INT && logger->isWarnEnabled(); } /** Is this logger is enabled for ERROR level logging events? See also #isDebugEnabled. See also #LOG4CXX_ERROR. @return bool - true if this logger is enabled for level error, false otherwise. */ bool isErrorEnabled() const; /** Is \c logger is enabled for ERROR level logging events? See #isDebugEnabledFor. See also #LOG4CXX_ERROR. @return bool - false if \c logger is null or ERROR logging events are disabled for \c logger, true otherwise. */ inline static bool isErrorEnabledFor(const LoggerPtr& logger) { return logger && logger->m_threshold <= Level::ERROR_INT && logger->isErrorEnabled(); } /** Is this logger is enabled for FATAL level logging events? See also #isDebugEnabled. See also #LOG4CXX_FATAL. @return bool - true if this logger is enabled for level fatal, false otherwise. */ bool isFatalEnabled() const; /** Is \c logger is enabled for FATAL level logging events? See #isDebugEnabledFor. See also #LOG4CXX_FATAL. @return bool - false if \c logger is null or FATAL logging events are disabled for \c logger, true otherwise. */ inline static bool isFatalEnabledFor(const LoggerPtr& logger) { return logger && logger->m_threshold <= Level::FATAL_INT && logger->isFatalEnabled(); } /** Is this logger is enabled for TRACE level logging events? See also #isDebugEnabled. See also #LOG4CXX_FATAL. @return bool - true if this logger is enabled for level trace, false otherwise. */ bool isTraceEnabled() const; /** Is \c logger is enabled for TRACE level logging events? See #isDebugEnabledFor. See also #LOG4CXX_TRACE. @return bool - false if \c logger is null or TRACE logging events are disabled for \c logger, true otherwise. */ inline static bool isTraceEnabledFor(const LoggerPtr& logger) { return logger && logger->m_threshold <= Level::TRACE_INT && logger->isTraceEnabled(); } /** Add a new logging event containing \c locationInfo and the localized message \c key using \c values for parameter substitution to attached appender(s) if this logger is enabled for \c level events. First, the user supplied key is searched in the resource bundle. Next, the resulting pattern is formatted using helpers::StringHelper::format method. @param level The level of the logging request. @param key The key to be searched in the ResourceBundle. @param locationInfo The location info of the logging request. @param values The values for the placeholders {0}, {1} etc. within the pattern. @see #setResourceBundle See also #LOG4CXX_L7DLOG1. */ void l7dlog(const LevelPtr& level, const LogString& key, const LOG4CXX_NS::spi::LocationInfo& locationInfo, const std::vector& values) const; /** Add a new logging event containing \c locationInfo and the localized message \c key to attached appender(s) if this logger is enabled for \c level events. First, the user supplied key is searched in the resource bundle. Next, the resulting pattern is formatted using helpers::StringHelper::format method. @param level The level of the logging request. @param key The key to be searched in the ResourceBundle. @param locationInfo The location info of the logging request. @see #setResourceBundle See also #LOG4CXX_L7DLOG. */ void l7dlog(const LevelPtr& level, const std::string& key, const LOG4CXX_NS::spi::LocationInfo& locationInfo) const; /** Add a new logging event containing \c locationInfo and the localized message \c key using parameter \c val to attached appender(s) if this logger is enabled for \c level events. First, the user supplied key is searched in the resource bundle. Next, the resulting pattern is formatted using helpers::StringHelper::format method with the supplied parameters in a string array. @param level The level of the logging request. @param key The key to be searched in the ResourceBundle. @param locationInfo The location info of the logging request. @param val The first value for the placeholders within the pattern. @see #setResourceBundle See also #LOG4CXX_L7DLOG1. */ void l7dlog(const LevelPtr& level, const std::string& key, const LOG4CXX_NS::spi::LocationInfo& locationInfo, const std::string& val) const; /** Add a new logging event containing \c locationInfo and the localized message \c key using parameters \c val1 and \c val2 to attached appender(s) if this logger is enabled for \c level events. First, the user supplied key is searched in the resource bundle. Next, the resulting pattern is formatted using helpers::StringHelper::format method with the supplied parameters in a string array. @param level The level of the logging request. @param key The key to be searched in the ResourceBundle. @param locationInfo The location info of the logging request. @param val1 The first value for the placeholders within the pattern. @param val2 The second value for the placeholders within the pattern. @see #setResourceBundle See also #LOG4CXX_L7DLOG2. */ void l7dlog(const LevelPtr& level, const std::string& key, const LOG4CXX_NS::spi::LocationInfo& locationInfo, const std::string& val1, const std::string& val2) const; /** Add a new logging event containing \c locationInfo and the localized message \c key using parameters \c val1, \c val2 and \c val3 to attached appender(s) if this logger is enabled for \c level events. First, the user supplied key is searched in the resource bundle. Next, the resulting pattern is formatted using helpers::StringHelper::format method with the supplied parameters in a string array. @param level The level of the logging request. @param key The key to be searched in the ResourceBundle. @param locationInfo The location info of the logging request. @param val1 The value for the first placeholder within the pattern. @param val2 The value for the second placeholder within the pattern. @param val3 The value for the third placeholder within the pattern. @see #setResourceBundle See also #LOG4CXX_L7DLOG3. */ void l7dlog(const LevelPtr& level, const std::string& key, const LOG4CXX_NS::spi::LocationInfo& locationInfo, const std::string& val1, const std::string& val2, const std::string& val3) const; #if LOG4CXX_WCHAR_T_API /** Add a new logging event containing \c locationInfo and the localized message \c key to attached appender(s) if this logger is enabled for \c level events. First, the user supplied key is searched in the resource bundle. Next, the resulting pattern is formatted using helpers::StringHelper::format method . @param level The level of the logging request. @param key The key to be searched in the ResourceBundle. @param locationInfo The location info of the logging request. @see #setResourceBundle See also #LOG4CXX_L7DLOG. */ void l7dlog(const LevelPtr& level, const std::wstring& key, const LOG4CXX_NS::spi::LocationInfo& locationInfo) const; /** Add a new logging event containing \c locationInfo and the localized message \c key using parameter \c val to attached appender(s) if this logger is enabled for \c level events. First, the user supplied key is searched in the resource bundle. Next, the resulting pattern is formatted using helpers::StringHelper::format method with the supplied parameter in a string array. @param level The level of the logging request. @param key The key to be searched in the ResourceBundle. @param locationInfo The location info of the logging request. @param val The value for the first placeholder within the pattern. @see #setResourceBundle See also #LOG4CXX_L7DLOG1. */ void l7dlog(const LevelPtr& level, const std::wstring& key, const LOG4CXX_NS::spi::LocationInfo& locationInfo, const std::wstring& val) const; /** Add a new logging event containing \c locationInfo and the localized message \c key using parameters \c val1 and \c val2 to attached appender(s) if this logger is enabled for \c level events. First, the user supplied key is searched in the resource bundle. Next, the resulting pattern is formatted using helpers::StringHelper::format method with the supplied parameters in a string array. @param level The level of the logging request. @param key The key to be searched in the ResourceBundle. @param locationInfo The location info of the logging request. @param val1 The value for the first placeholder within the pattern. @param val2 The value for the second placeholder within the pattern. @see #setResourceBundle See also #LOG4CXX_L7DLOG2. */ void l7dlog(const LevelPtr& level, const std::wstring& key, const LOG4CXX_NS::spi::LocationInfo& locationInfo, const std::wstring& val1, const std::wstring& val2) const; /** Add a new logging event containing \c locationInfo and the localized message \c key using parameters \c val1, \c val2 and \c val3 to attached appender(s) if this logger is enabled for \c level events. First, the user supplied key is searched in the resource bundle. Next, the resulting pattern is formatted using helpers::StringHelper::format method with the supplied parameters in a string array. @param level The level of the logging request. @param key The key to be searched in the ResourceBundle. @param locationInfo The location info of the logging request. @param val1 The value for the first placeholder within the pattern. @param val2 The value for the second placeholder within the pattern. @param val3 The value for the third placeholder within the pattern. @see #setResourceBundle See also #LOG4CXX_L7DLOG3. */ void l7dlog(const LevelPtr& level, const std::wstring& key, const LOG4CXX_NS::spi::LocationInfo& locationInfo, const std::wstring& val1, const std::wstring& val2, const std::wstring& val3) const; #endif #if LOG4CXX_UNICHAR_API /** Add a new logging event containing \c locationInfo and the localized message \c key to attached appender(s) if this logger is enabled for \c level events. First, the user supplied key is searched in the resource bundle. Next, the resulting pattern is formatted using helpers::StringHelper::format method. @param level The level of the logging request. @param key The key to be searched in the ResourceBundle. @param locationInfo The location info of the logging request. @see #setResourceBundle See also #LOG4CXX_L7DLOG. */ void l7dlog(const LevelPtr& level, const std::basic_string& key, const LOG4CXX_NS::spi::LocationInfo& locationInfo) const; /** Add a new logging event containing \c locationInfo and the localized message \c key using parameter \c val to attached appender(s) if this logger is enabled for \c level events. First, the user supplied key is searched in the resource bundle. Next, the resulting pattern is formatted using helpers::StringHelper::format method with the supplied parameter in a string array. @param level The level of the logging request. @param key The key to be searched in the ResourceBundle. @param locationInfo The location info of the logging request. @param val The value for the first placeholder within the pattern. @see #setResourceBundle See also #LOG4CXX_L7DLOG1. */ void l7dlog(const LevelPtr& level, const std::basic_string& key, const LOG4CXX_NS::spi::LocationInfo& locationInfo, const std::basic_string& val) const; /** Add a new logging event containing \c locationInfo and the localized message \c key using parameters \c val1 and \c val2 to attached appender(s) if this logger is enabled for \c level events. First, the user supplied key is searched in the resource bundle. Next, the resulting pattern is formatted using helpers::StringHelper::format method with the supplied parameters in a string array. @param level The level of the logging request. @param key The key to be searched in the ResourceBundle. @param locationInfo The location info of the logging request. @param val1 The value for the first placeholder within the pattern. @param val2 The value for the second placeholder within the pattern. @see #setResourceBundle See also #LOG4CXX_L7DLOG2. */ void l7dlog(const LevelPtr& level, const std::basic_string& key, const LOG4CXX_NS::spi::LocationInfo& locationInfo, const std::basic_string& val1, const std::basic_string& val2) const; /** Add a new logging event containing \c locationInfo and the localized message \c key using parameters \c val1, \c val2 and \c val3 to attached appender(s) if this logger is enabled for \c level events. First, the user supplied key is searched in the resource bundle. Next, the resulting pattern is formatted using helpers::StringHelper::format method with the supplied parameters in a string array. @param level The level of the logging request. @param key The key to be searched in the ResourceBundle. @param locationInfo The location info of the logging request. @param val1 The value for the first placeholder within the pattern. @param val2 The value for the second placeholder within the pattern. @param val3 The value for the third placeholder within the pattern. @see #setResourceBundle See also #LOG4CXX_L7DLOG3. */ void l7dlog(const LevelPtr& level, const std::basic_string& key, const LOG4CXX_NS::spi::LocationInfo& locationInfo, const std::basic_string& val1, const std::basic_string& val2, const std::basic_string& val3) const; #endif #if LOG4CXX_CFSTRING_API /** Add a new logging event containing \c locationInfo and the localized message \c key to attached appender(s) if this logger is enabled for \c level events. First, the user supplied key is searched in the resource bundle. Next, the resulting pattern is formatted using helpers::StringHelper::format method. @param level The level of the logging request. @param key The key to be searched in the ResourceBundle. @param locationInfo The location info of the logging request. @see #setResourceBundle See also #LOG4CXX_L7DLOG. */ void l7dlog(const LevelPtr& level, const CFStringRef& key, const LOG4CXX_NS::spi::LocationInfo& locationInfo) const; /** Add a new logging event containing \c locationInfo and the localized message \c key using parameter \c val to attached appender(s) if this logger is enabled for \c level events. First, the user supplied key is searched in the resource bundle. Next, the resulting pattern is formatted using helpers::StringHelper::format method with the supplied parameter in a string array. @param level The level of the logging request. @param key The key to be searched in the ResourceBundle. @param locationInfo The location info of the logging request. @param val1 The value for the first placeholder within the pattern. @see #setResourceBundle See also #LOG4CXX_L7DLOG1. */ void l7dlog(const LevelPtr& level, const CFStringRef& key, const LOG4CXX_NS::spi::LocationInfo& locationInfo, const CFStringRef& val1) const; /** Add a new logging event containing \c locationInfo and the localized message \c key using parameters \c val1 and \c val2 to attached appender(s) if this logger is enabled for \c level events. First, the user supplied key is searched in the resource bundle. Next, the resulting pattern is formatted using helpers::StringHelper::format method with the supplied parameters in a string array. @param level The level of the logging request. @param key The key to be searched in the ResourceBundle. @param locationInfo The location info of the logging request. @param val1 The value for the first placeholder within the pattern. @param val2 The value for the second placeholder within the pattern. @see #setResourceBundle See also #LOG4CXX_L7DLOG2. */ void l7dlog(const LevelPtr& level, const CFStringRef& key, const LOG4CXX_NS::spi::LocationInfo& locationInfo, const CFStringRef& val1, const CFStringRef& val2) const; /** Add a new logging event containing \c locationInfo and the localized message \c key using parameters \c val1, \c val2 and \c val3 to attached appender(s) if this logger is enabled for \c level events. First, the user supplied key is searched in the resource bundle. Next, the resulting pattern is formatted using helpers::StringHelper::format method with the supplied parameters in a string array. @param level The level of the logging request. @param key The key to be searched in the ResourceBundle. @param locationInfo The location info of the logging request. @param val1 The value for the first placeholder within the pattern. @param val2 The value for the second placeholder within the pattern. @param val3 The value for the third placeholder within the pattern. @see #setResourceBundle See also #LOG4CXX_L7DLOG3. */ void l7dlog(const LevelPtr& level, const CFStringRef& key, const LOG4CXX_NS::spi::LocationInfo& locationInfo, const CFStringRef& val1, const CFStringRef& val2, const CFStringRef& val3) const; #endif /** Add a new logging event containing \c message and \c location to the appenders attached to this logger if this logger is enabled for \c level events. This is the most generic printing method. It is intended to be invoked by wrapper classes. @param level The level of the logging request. @param message The message of the logging request. @param location The source file of the logging request, may be null. */ void log(const LevelPtr& level, const std::string& message, const LOG4CXX_NS::spi::LocationInfo& location) const; /** Add a new logging event containing \c message to the appenders attached to this logger if this logger is enabled for \c level events. This is the most generic printing method. It is intended to be invoked by wrapper classes. @param level The level of the logging request. @param message The message of the logging request. */ void log(const LevelPtr& level, const std::string& message) const; #if LOG4CXX_WCHAR_T_API /** Add a new logging event containing \c message and \c location to the appenders attached to this logger if this logger is enabled for \c level events. This is the most generic printing method. It is intended to be invoked by wrapper classes. @param level The level of the logging request. @param message The message of the logging request. @param location The source file of the logging request, may be null. */ void log(const LevelPtr& level, const std::wstring& message, const LOG4CXX_NS::spi::LocationInfo& location) const; /** Add a new logging event containing \c message to the appenders attached to this logger if this logger is enabled for \c level events. This is the most generic printing method. It is intended to be invoked by wrapper classes. @param level The level of the logging request. @param message The message of the logging request. */ void log(const LevelPtr& level, const std::wstring& message) const; #endif #if LOG4CXX_UNICHAR_API /** Add a new logging event containing \c message and \c location to the appenders attached to this logger if this logger is enabled for \c level events. This is the most generic printing method. It is intended to be invoked by wrapper classes. @param level The level of the logging request. @param message The message of the logging request. @param location The source file of the logging request, may be null. */ void log(const LevelPtr& level, const std::basic_string& message, const LOG4CXX_NS::spi::LocationInfo& location) const; /** Add a new logging event containing \c message to the appenders attached to this logger if this logger is enabled for \c level events. This is the most generic printing method. It is intended to be invoked by wrapper classes. @param level The level of the logging request. @param message The message of the logging request. */ void log(const LevelPtr& level, const std::basic_string& message) const; #endif #if LOG4CXX_CFSTRING_API /** Add a new logging event containing \c message and \c location to the appenders attached to this logger if this logger is enabled for \c level events. This is the most generic printing method. It is intended to be invoked by wrapper classes. @param level The level of the logging request. @param message The message of the logging request. @param location The source file of the logging request, may be null. */ void log(const LevelPtr& level, const CFStringRef& message, const LOG4CXX_NS::spi::LocationInfo& location) const; /** Add a new logging event containing \c message to the appenders attached to this logger if this logger is enabled for \c level events. This is the most generic printing method. It is intended to be invoked by wrapper classes. @param level The level of the logging request. @param message The message of the logging request. */ void log(const LevelPtr& level, const CFStringRef& message) const; #endif /** Add a new logging event containing \c message and \c location to the appenders attached to this logger if this logger is enabled for \c level events. This is the most generic printing method. It is intended to be invoked by wrapper classes. @param level The level of the logging request. @param message The message of the logging request. @param location The source file of the logging request, may be null. */ void logLS(const LevelPtr& level, const LogString& message, const LOG4CXX_NS::spi::LocationInfo& location) const; /** Remove all previously added appenders from this logger instance.

This is useful when re-reading configuration information. */ void removeAllAppenders() override; /** Remove the appender passed as parameter form the list of appenders. */ void removeAppender(const AppenderPtr appender) override; /** Remove the appender with the name passed as parameter form the list of appenders. */ void removeAppender(const LogString& name) override; /** Set the additivity flag for this logger. */ void setAdditivity(bool additive); protected: friend class Hierarchy; /** Only the Hierarchy class can remove the hierarchy of a logger. */ void removeHierarchy(); /** Only the Hierarchy class can set the hierarchy of a logger. */ void setHierarchy(spi::LoggerRepository* repository); /** Only the Hierarchy class can set the parent of a logger. */ void setParent(LoggerPtr parentLogger); /** Only the Hierarchy class can change the threshold of a logger. */ void updateThreshold(); private: spi::LoggerRepository* getHierarchy() const; public: /** Set the level of this logger.

As in logger->setLevel(Level::getDebug());

Null values are admitted. */ virtual void setLevel(const LevelPtr level); /** Set the resource bundle to be used with localized logging methods. */ void setResourceBundle(const helpers::ResourceBundlePtr& bundle); #if LOG4CXX_WCHAR_T_API /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for WARN events.

This method first checks if this logger is WARN enabled by comparing the level of this logger with the WARN level. If this logger is WARN enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. @param location The source code location of the logging request. See also #LOG4CXX_WARN. */ void warn(const std::wstring& msg, const LOG4CXX_NS::spi::LocationInfo& location) const; /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for WARN events.

This method first checks if this logger is WARN enabled by comparing the level of this logger with the WARN level. If this logger is WARN enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. See also #LOG4CXX_WARN. */ void warn(const std::wstring& msg) const; #endif #if LOG4CXX_UNICHAR_API /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for WARN events.

This method first checks if this logger is WARN enabled by comparing the level of this logger with the WARN level. If this logger is WARN enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. @param location The source code location of the logging request. See also #LOG4CXX_WARN. */ void warn(const std::basic_string& msg, const LOG4CXX_NS::spi::LocationInfo& location) const; /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for WARN events.

This method first checks if this logger is WARN enabled by comparing the level of this logger with the WARN level. If this logger is WARN enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. See also #LOG4CXX_WARN. */ void warn(const std::basic_string& msg) const; #endif #if LOG4CXX_CFSTRING_API /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for WARN events.

This method first checks if this logger is WARN enabled by comparing the level of this logger with the WARN level. If this logger is WARN enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. @param location The source code location of the logging request. See also #LOG4CXX_WARN. */ void warn(const CFStringRef& msg, const LOG4CXX_NS::spi::LocationInfo& location) const; /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for WARN events.

This method first checks if this logger is WARN enabled by comparing the level of this logger with the WARN level. If this logger is WARN enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. See also #LOG4CXX_WARN. */ void warn(const CFStringRef& msg) const; #endif /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for WARN events.

This method first checks if this logger is WARN enabled by comparing the level of this logger with the WARN level. If this logger is WARN enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. @param location The source code location of the logging request. See also #LOG4CXX_WARN. */ void warn(const std::string& msg, const LOG4CXX_NS::spi::LocationInfo& location) const; /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for WARN events.

This method first checks if this logger is WARN enabled by comparing the level of this logger with the WARN level. If this logger is WARN enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. See also #LOG4CXX_WARN. */ void warn(const std::string& msg) const; #if LOG4CXX_WCHAR_T_API /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for TRACE events.

This method first checks if this logger is TRACE enabled by comparing the level of this logger with the TRACE level. If this logger is TRACE enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. @param location The source code location of the logging request. See also #LOG4CXX_TRACE. */ void trace(const std::wstring& msg, const LOG4CXX_NS::spi::LocationInfo& location) const; /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for TRACE events.

This method first checks if this logger is TRACE enabled by comparing the level of this logger with the TRACE level. If this logger is TRACE enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. See also #LOG4CXX_TRACE. */ void trace(const std::wstring& msg) const; #endif #if LOG4CXX_UNICHAR_API /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for TRACE events.

This method first checks if this logger is TRACE enabled by comparing the level of this logger with the TRACE level. If this logger is TRACE enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. @param location The source code location of the logging request. See also #LOG4CXX_TRACE. */ void trace(const std::basic_string& msg, const LOG4CXX_NS::spi::LocationInfo& location) const; /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for TRACE events.

This method first checks if this logger is TRACE enabled by comparing the level of this logger with the TRACE level. If this logger is TRACE enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. See also #LOG4CXX_TRACE. */ void trace(const std::basic_string& msg) const; #endif #if LOG4CXX_CFSTRING_API /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for TRACE events.

This method first checks if this logger is TRACE enabled by comparing the level of this logger with the TRACE level. If this logger is TRACE enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. @param location The source code location of the logging request. See also #LOG4CXX_TRACE. */ void trace(const CFStringRef& msg, const LOG4CXX_NS::spi::LocationInfo& location) const; /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for TRACE events.

This method first checks if this logger is TRACE enabled by comparing the level of this logger with the TRACE level. If this logger is TRACE enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. See also #LOG4CXX_TRACE. */ void trace(const CFStringRef& msg) const; #endif /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for TRACE events.

This method first checks if this logger is TRACE enabled by comparing the level of this logger with the TRACE level. If this logger is TRACE enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. @param location The source code location of the logging request. See also #LOG4CXX_TRACE. */ void trace(const std::string& msg, const LOG4CXX_NS::spi::LocationInfo& location) const; /** Add a new logging event containing \c msg to attached appender(s) if this logger is enabled for TRACE events.

This method first checks if this logger is TRACE enabled by comparing the level of this logger with the TRACE level. If this logger is TRACE enabled, it proceeds to call all the registered appenders in this logger and also higher in the hierarchy depending on the value of the additivity flag. @param msg the message string to log. See also #LOG4CXX_TRACE. */ void trace(const std::string& msg) const; /** * Reconfigure this logger by configuring all of the appenders. * * @param appenders The appenders to set. Any currently existing appenders are removed. * @param additivity The additivity of this logger */ void reconfigure( const std::vector& appenders, bool additivity ); private: // // prevent copy and assignment Logger(const Logger&); Logger& operator=(const Logger&); }; LOG4CXX_LIST_DEF(LoggerList, LoggerPtr); } #if !defined(LOG4CXX_UNLIKELY) #if __GNUC__ >= 3 /** Provides optimization hint to the compiler to optimize for the expression being false. @param expr boolean expression. @returns value of expression. */ #define LOG4CXX_UNLIKELY(expr) __builtin_expect(expr, 0) #else /** Provides optimization hint to the compiler to optimize for the expression being false. @param expr boolean expression. @returns value of expression. **/ #define LOG4CXX_UNLIKELY(expr) expr #endif #endif #if defined(LOG4CXX_ENABLE_STACKTRACE) && !defined(LOG4CXX_STACKTRACE) #ifndef __has_include #include #define LOG4CXX_STACKTRACE ::LOG4CXX_NS::MDC mdc_("stacktrace", LOG4CXX_EOL + boost::stacktrace::to_string(boost::stacktrace::stacktrace())); #elif __has_include() #include #define LOG4CXX_STACKTRACE ::LOG4CXX_NS::MDC mdc_("stacktrace", LOG4CXX_EOL + std::stacktrace::to_string(std::stacktrace::stacktrace())); #elif __has_include() #include #define LOG4CXX_STACKTRACE ::LOG4CXX_NS::MDC mdc_("stacktrace", LOG4CXX_EOL + boost::stacktrace::to_string(boost::stacktrace::stacktrace())); #else #warning "Stacktrace requested but no implementation found" #endif #endif /* LOG4CXX_ENABLE_STACKTRACE */ #if !defined(LOG4CXX_STACKTRACE) #define LOG4CXX_STACKTRACE #endif #ifndef LOG4CXX_FMT_VA_ARG #if __cplusplus >= 202002L #define LOG4CXX_FMT_VA_ARG(...) __VA_OPT__(,) __VA_ARGS__ #else #define LOG4CXX_FMT_VA_ARG(...) , __VA_ARGS__ #endif #endif /** @addtogroup LoggingMacros Logging macros @{ */ /** Add a new logging event containing \c message to attached appender(s) if this logger is enabled for \c events. @param logger the logger to be used. @param level The logging event level. @param message a valid r-value expression of an operator<<(std::ostream&. ...) overload. */ #define LOG4CXX_LOG(logger, level, message) do { \ if (logger->isEnabledFor(level)) {\ ::LOG4CXX_NS::helpers::MessageBuffer oss_; \ logger->addEvent(level, oss_.extract_str(oss_ << message), LOG4CXX_LOCATION); }} while (0) /** Add a new logging event containing a message defined by \c fmt and ... to attached appender(s) if this logger is enabled for \c events. @param logger the logger to be used. @param level The logging event level. @param fmt the layout of the message. @param ... the variable parts of the message. */ #define LOG4CXX_LOG_FMT(logger, level, fmt, ...) do { \ if (logger->isEnabledFor(level)) {\ logger->addEvent(level, ::LOG4CXX_FORMAT_NS::format(fmt LOG4CXX_FMT_VA_ARG(__VA_ARGS__) ), LOG4CXX_LOCATION); }} while (0) /** Add a new logging event containing \c message to attached appender(s) if this logger is enabled for \c events. @param logger the logger to be used. @param level The logging event level. @param message a valid r-value expression of an operator<<(std::ostream&. ...) overload. in the internal encoding. */ #define LOG4CXX_LOGLS(logger, level, message) do { \ if (logger->isEnabledFor(level)) {\ ::LOG4CXX_NS::helpers::LogCharMessageBuffer oss_; \ logger->addEvent(level, oss_.extract_str(oss_ << message), LOG4CXX_LOCATION); }} while (0) #if !defined(LOG4CXX_THRESHOLD) || LOG4CXX_THRESHOLD <= 10000 /** Add a new logging event containing \c message to attached appender(s) if \c logger is enabled for DEBUG events. \usage ~~~{.cpp} LOG4CXX_DEBUG(m_log, "AddMesh:" << " name " << meshName << " type 0x" << std:: hex << traits.Type << " materialName " << meshObject.GetMaterialName() << " visible? " << traits.IsDefaultVisible << " at " << obj->getBoundingBox().getCenter() << " +/- " << obj->getBoundingBox().getHalfSize() ); ~~~ @param logger the logger that has the enabled status. @param message a valid r-value expression of an operator<<(std::ostream&. ...) overload. */ #define LOG4CXX_DEBUG(logger, message) do { \ if (LOG4CXX_UNLIKELY(::LOG4CXX_NS::Logger::isDebugEnabledFor(logger))) {\ ::LOG4CXX_NS::helpers::MessageBuffer oss_; \ logger->addDebugEvent(oss_.extract_str(oss_ << message), LOG4CXX_LOCATION); }} while (0) /** Add a new logging event containing a message defined by \c fmt and ... to attached appender(s) if \c logger is enabled for DEBUG events. \usage ~~~{.cpp} LOG4CXX_DEBUG_FMT(m_log, "AddMesh: name {} type 0x{x} materialName {} visible? {d} at {} +/- {}" , meshName , traits.Type , meshObject.GetMaterialName() , traits.IsDefaultVisible , obj->getBoundingBox().getCenter() , obj->getBoundingBox().getHalfSize() ); ~~~ @param logger the logger to be used. @param fmt the layout of the message. @param ... the variable parts of the message. */ #define LOG4CXX_DEBUG_FMT(logger, fmt, ...) do { \ if (LOG4CXX_UNLIKELY(::LOG4CXX_NS::Logger::isDebugEnabledFor(logger))) {\ logger->addDebugEvent(::LOG4CXX_FORMAT_NS::format(fmt LOG4CXX_FMT_VA_ARG(__VA_ARGS__) ), LOG4CXX_LOCATION); }} while (0) #else #define LOG4CXX_DEBUG(logger, message) #define LOG4CXX_DEBUG_FMT(logger, fmt, ...) #endif #if !defined(LOG4CXX_THRESHOLD) || LOG4CXX_THRESHOLD <= 5000 /** Add a new logging event containing \c message to attached appender(s) if \c logger is enabled for TRACE events. \usage ~~~{.cpp} LOG4CXX_TRACE(m_log, "AddVertex:" << " at " << p << " n " << n << ' ' << color); ~~~ @param logger the logger that has the enabled status. @param message a valid r-value expression of an operator<<(std::ostream&. ...) overload. */ #define LOG4CXX_TRACE(logger, message) do { \ if (LOG4CXX_UNLIKELY(::LOG4CXX_NS::Logger::isTraceEnabledFor(logger))) {\ ::LOG4CXX_NS::helpers::MessageBuffer oss_; \ logger->addTraceEvent(oss_.extract_str(oss_ << message), LOG4CXX_LOCATION); }} while (0) /** Add a new logging event containing a message defined by \c fmt and ... to attached appender(s) if \c logger is enabled for TRACE events. \usage ~~~{.cpp} LOG4CXX_TRACE_FMT(m_log, "AddVertex: at {} n {} {}", p, n, color); ~~~ @param logger the logger to be used. @param fmt the layout of the message. @param ... the variable parts of the message. */ #define LOG4CXX_TRACE_FMT(logger, fmt, ...) do { \ if (LOG4CXX_UNLIKELY(::LOG4CXX_NS::Logger::isTraceEnabledFor(logger))) {\ logger->addTraceEvent(::LOG4CXX_FORMAT_NS::format(fmt LOG4CXX_FMT_VA_ARG(__VA_ARGS__)), LOG4CXX_LOCATION); }} while (0) #else #define LOG4CXX_TRACE(logger, message) #define LOG4CXX_TRACE_FMT(logger, fmt, ...) #endif #if !defined(LOG4CXX_THRESHOLD) || LOG4CXX_THRESHOLD <= 20000 /** Add a new logging event containing \c message to attached appender(s) if \c logger is enabled for INFO events. \usage ~~~{.cpp} LOG4CXX_INFO(m_log, surface->GetName() << " successfully planned " << std::fixed << std::setprecision(1) << ((plannedArea / (plannedArea + unplannedArea)) * 100.0) << "%" << " planned area " << std::fixed << std::setprecision(4) << plannedArea << "m^2" << " unplanned area " << unplannedArea << "m^2" << " planned segments " << surface->GetSegmentPlanCount() << " of " << surface->GetSegmentCount() ); ~~~ @param logger the logger that has the enabled status. @param message a valid r-value expression of an operator<<(std::ostream&. ...) overload. */ #define LOG4CXX_INFO(logger, message) do { \ if (::LOG4CXX_NS::Logger::isInfoEnabledFor(logger)) {\ ::LOG4CXX_NS::helpers::MessageBuffer oss_; \ logger->addInfoEvent(oss_.extract_str(oss_ << message), LOG4CXX_LOCATION); }} while (0) /** Add a new logging event containing a message defined by \c fmt and ... to attached appender(s) if \c logger is enabled for INFO events. \usage ~~~{.cpp} LOG4CXX_INFO_FMT(m_log, "{} successfully planned {:.1f}% planned area {:.4f}m^2 unplanned area {:.4f}m^2 planned segments {:d} of {:d}" , surface->GetName(), (plannedArea / (plannedArea + unplannedArea)) * 100.0 , plannedArea, unplannedArea , surface->GetSegmentPlanCount(), surface->GetSegmentCount() ); ~~~ @param logger the logger to be used. @param fmt the layout of the message. @param ... the variable parts of the message. */ #define LOG4CXX_INFO_FMT(logger, fmt, ...) do { \ if (::LOG4CXX_NS::Logger::isInfoEnabledFor(logger)) {\ logger->addInfoEvent(::LOG4CXX_FORMAT_NS::format(fmt LOG4CXX_FMT_VA_ARG(__VA_ARGS__)), LOG4CXX_LOCATION); }} while (0) #else #define LOG4CXX_INFO(logger, message) #define LOG4CXX_INFO_FMT(logger, fmt, ...) #endif #if !defined(LOG4CXX_THRESHOLD) || LOG4CXX_THRESHOLD <= 30000 /** Add a new logging event containing \c message to attached appender(s) if \c logger is enabled for WARN events. \usage ~~~{.cpp} catch (const std::exception& ex) { LOG4CXX_WARN(m_log, ex.what() << ": in " << m_task->GetParamFilePath()); } ~~~ @param logger the logger to be used. @param message a valid r-value expression of an operator<<(std::ostream&. ...) overload. */ #define LOG4CXX_WARN(logger, message) do { \ if (::LOG4CXX_NS::Logger::isWarnEnabledFor(logger)) {\ ::LOG4CXX_NS::helpers::MessageBuffer oss_; \ logger->addWarnEvent(oss_.extract_str(oss_ << message), LOG4CXX_LOCATION); }} while (0) /** Add a new logging event containing a message defined by \c fmt and ... to attached appender(s) if \c logger is enabled for WARN events. \usage ~~~{.cpp} catch (const std::exception& ex) { LOG4CXX_WARN_FMT(m_log, "{}: in {}", ex.what(), m_task->GetParamFilePath()); } ~~~ @param logger the logger to be used. @param fmt the layout of the message. @param ... the variable parts of the message. */ #define LOG4CXX_WARN_FMT(logger, fmt, ...) do { \ if (::LOG4CXX_NS::Logger::isWarnEnabledFor(logger)) {\ logger->addWarnEvent(::LOG4CXX_FORMAT_NS::format(fmt LOG4CXX_FMT_VA_ARG(__VA_ARGS__)), LOG4CXX_LOCATION); }} while (0) #else #define LOG4CXX_WARN(logger, message) #define LOG4CXX_WARN_FMT(logger, fmt, ...) #endif #if !defined(LOG4CXX_THRESHOLD) || LOG4CXX_THRESHOLD <= 40000 /** Add a new logging event containing \c message to attached appender(s) if \c logger is enabled for ERROR events. \usage ~~~{.cpp} catch (std::exception& ex) { LOG4CXX_ERROR(m_log, ex.what() << " in AddScanData"); } ~~~ @param logger the logger to be used. @param message a valid r-value expression of an operator<<(std::ostream&. ...) overload. */ #define LOG4CXX_ERROR(logger, message) do { \ if (::LOG4CXX_NS::Logger::isErrorEnabledFor(logger)) {\ ::LOG4CXX_NS::helpers::MessageBuffer oss_; \ logger->addErrorEvent(oss_.extract_str(oss_ << message), LOG4CXX_LOCATION); }} while (0) /** Add a new logging event containing a message defined by \c fmt and ... to attached appender(s) if \c logger is enabled for ERROR events. \usage ~~~{.cpp} catch (std::exception& ex) { LOG4CXX_ERROR_FMT(m_log, "{} in AddScanData", ex.what()); } ~~~ @param logger the logger to be used. @param fmt the layout of the message. @param ... the variable parts of the message. */ #define LOG4CXX_ERROR_FMT(logger, fmt, ...) do { \ if (::LOG4CXX_NS::Logger::isErrorEnabledFor(logger)) {\ logger->addErrorEvent(::LOG4CXX_FORMAT_NS::format(fmt LOG4CXX_FMT_VA_ARG(__VA_ARGS__)), LOG4CXX_LOCATION); }} while (0) /** If \c condition is not true, add a new logging event containing \c message to attached appender(s) if \c logger is enabled for ERROR events. @param logger the logger to be used. @param condition condition @param message a valid r-value expression of an operator<<(std::ostream&. ...) overload. */ #define LOG4CXX_ASSERT(logger, condition, message) do { \ if (!(condition) && ::LOG4CXX_NS::Logger::isErrorEnabledFor(logger)) {\ ::LOG4CXX_NS::helpers::MessageBuffer oss_; \ LOG4CXX_STACKTRACE \ logger->addErrorEvent(oss_.extract_str(oss_ << message), LOG4CXX_LOCATION); }} while (0) /** If \c condition is not true, add a new logging event containing a message defined by \c fmt and ... to attached appender(s) if \c logger is enabled for ERROR events. @param logger the logger to be used. @param condition condition @param fmt the layout of the message. @param ... the variable parts of the message. */ #define LOG4CXX_ASSERT_FMT(logger, condition, fmt, ...) do { \ if (!(condition) && ::LOG4CXX_NS::Logger::isErrorEnabledFor(logger)) {\ LOG4CXX_STACKTRACE \ logger->addErrorEvent(::LOG4CXX_FORMAT_NS::format(fmt LOG4CXX_FMT_VA_ARG(__VA_ARGS__)), LOG4CXX_LOCATION); }} while (0) #else #define LOG4CXX_ERROR(logger, message) #define LOG4CXX_ERROR_FMT(logger, fmt, ...) #define LOG4CXX_ASSERT(logger, condition, message) #define LOG4CXX_ASSERT_FMT(logger, condition, fmt, ...) #endif #if !defined(LOG4CXX_THRESHOLD) || LOG4CXX_THRESHOLD <= 50000 /** Add a new logging event containing \c message to attached appender(s) if \c logger is enabled for FATAL events. \usage ~~~{.cpp} LOG4CXX_FATAL(m_log, m_renderSystem->getName() << " is not supported"); ~~~ @param logger the logger to be used. @param message a valid r-value expression of an operator<<(std::ostream&. ...) overload. */ #define LOG4CXX_FATAL(logger, message) do { \ if (::LOG4CXX_NS::Logger::isFatalEnabledFor(logger)) {\ ::LOG4CXX_NS::helpers::MessageBuffer oss_; \ logger->addFatalEvent(oss_.extract_str(oss_ << message), LOG4CXX_LOCATION); }} while (0) /** Add a new logging event containing a message defined by \c fmt and ... to attached appender(s) if \c logger is enabled for FATAL events. \usage ~~~{.cpp} LOG4CXX_FATAL_FMT(m_log, "{} is not supported", m_renderSystem->getName()); ~~~ @param logger the logger to be used. @param fmt the layout of the message. @param ... the variable parts of the message. */ #define LOG4CXX_FATAL_FMT(logger, fmt, ...) do { \ if (::LOG4CXX_NS::Logger::isFatalEnabledFor(logger)) {\ logger->addFatalEvent(::LOG4CXX_FORMAT_NS::format(fmt LOG4CXX_FMT_VA_ARG(__VA_ARGS__)), LOG4CXX_LOCATION); }} while (0) #else #define LOG4CXX_FATAL(logger, message) #define LOG4CXX_FATAL_FMT(logger, fmt, ...) #endif /** Add a new logging event containing the localized message \c key to attached appender(s) if \c logger is enabled for \c level events. @param logger the logger to be used. @param level The logging event level. @param key the key to be searched in the resourceBundle of the logger. */ #define LOG4CXX_L7DLOG(logger, level, key) do { \ if (logger->isEnabledFor(level)) {\ logger->l7dlog(level, key, LOG4CXX_LOCATION); }} while (0) /** Add a new logging event containing the localized message \c key to attached appender(s) if \c logger is enabled for \c level events with one parameter. @param logger the logger to be used. @param level The logging event level. @param key the key to be searched in the resourceBundle of the logger. @param p1 the unique parameter. */ #define LOG4CXX_L7DLOG1(logger, level, key, p1) do { \ if (logger->isEnabledFor(level)) {\ logger->l7dlog(level, key, LOG4CXX_LOCATION, p1); }} while (0) /** Add a new logging event containing the localized message \c key to attached appender(s) if \c logger is enabled for \c level events with two parameters. @param logger the logger to be used. @param level The logging event level. @param key the key to be searched in the resourceBundle of the logger. @param p1 the first parameter. @param p2 the second parameter. */ #define LOG4CXX_L7DLOG2(logger, level, key, p1, p2) do { \ if (logger->isEnabledFor(level)) {\ logger->l7dlog(level, key, LOG4CXX_LOCATION, p1, p2); }} while (0) /** Add a new logging event containing the localized message \c key to attached appender(s) if \c logger is enabled for \c level events with three parameters. @param logger the logger to be used. @param level The logging event level. @param key the key to be searched in the resourceBundle of the logger. @param p1 the first parameter. @param p2 the second parameter. @param p3 the third parameter. */ #define LOG4CXX_L7DLOG3(logger, level, key, p1, p2, p3) do { \ if (logger->isEnabledFor(level)) {\ logger->l7dlog(level, key, LOG4CXX_LOCATION, p1, p2, p3); }} while (0) /**@}*/ #include #endif //_LOG4CXX_LOGGER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/fmtlayout.h0000644000175100001770000002216614721727031022626 0ustar runnerdocker/* * 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. */ #ifndef LOG4CXX_FMT_LAYOUT_H #define LOG4CXX_FMT_LAYOUT_H #if defined(_MSC_VER) #pragma warning ( push ) #pragma warning ( disable: 4231 4251 4275 4786 ) #endif #include namespace LOG4CXX_NS { /** * The FMTLayout class uses libfmt to layout messages. This is an alternative to the PatternLayout class. * Most of the standard PatternLayout arguments are also accepted as arguments, so that you can easily * convert a PatternLayout to a FMTLayout. For example, given the following PatternLayout: * *

%c %-5p - %m%n
* which outputs something like: *
root INFO  - Hello there!
* * The equivalent FMTLayout can be written as: *
{c} {p:<5} - {m}{n}
* Or more verbosely as: *
{logger} {level:<5} - {message}{newline}
* * All replacements are done using the named arguments feature of {fmt}. * *

The recognized conversion strings are:

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Conversion stringEffect
*

c

*

logger

*
* Used to output the logger of the logging event. Unlike PatternConverter, * this does not take a parameter to shorten the name of the logger. *
*

C

*

class

*
* Used to output the class of the issuer of the logging event if the compiler * used supports a macro to retrieve the method of the currently compiled line and * if the LOG4CXX_TRACE-like macros are used to issue a logging request. In this * case the macro LOG4CXX_* is expanded at compile time to generate location info * of the logging event and adds the method name, besides file and line, if * available. In most cases the provided method contains the classname and can * therefore be retrieved form the location info as needed. *

* Currently supported compilers are those from Microsoft, GNU-C and Borland. *

*
*

f

*

shortfilename

*
* Used to output the short file name where the logging request was issued. *
*

F

*

filename

*
* Used to output the file name where the logging request was issued. *
*

l

*

location

*
* Used to output location information of the caller which generated the logging * event. *
*

L

*

line

*
* Used to output the line number from where the logging request was issued. *
*

m

*

message

*
* Used to output the application supplied message associated with the logging * event. *
* M *

method

*
* Used to output the method of the issuer of the logging event if the compiler * used supports a macro to retrieve the method of the currently compiled line * and if the LOG4CXX_TRACE-like macros are used to issue a logging request. In * this case the macro LOG4CXX_* is expanded at compile time to generate location * info of the logging event and adds the method name, besides file and line, if * available. In most cases the provided method contains the classname which is * ignored in every attempt to retrieve the method from the location info. *

* Currently supported compilers are those from Microsoft, GNU-C and Borland. *

*
*

n

*

newline

*
* Outputs the platform dependent line separator character or characters. *

* This conversion character offers practically the same performance as using * non-portable line separator strings such as "\n", or "\r\n". Thus, it is the * preferred way of specifying a line separator. *

*
*

p

*

level

*
Used to output the level of the logging event.
*

r

*
* Used to output the number of milliseconds elapsed since the start of the * application until the creation of the logging event. *
*

t

*

thread

*
Used to output the ID of the thread that generated the logging event.
*

T

*

threadname

*
Used to output the name of the thread that generated the logging event. May not be available on all platforms.
*

x

*

ndc

*
* Used to output the NDC (nested diagnostic context) associated with the thread that * generated the logging event. *
*

mdc[1-6]

*
* Used to output the MDC (mapped diagnostic context) associated with the thread that * generated the logging event. The keys must be specified in the configuration for * the layout. A maximum of 6 MDC keys are available to be output(mdc1, mdc2, ..., mdc6) *
*/ class LOG4CXX_EXPORT FMTLayout : public Layout { LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(FMTLayoutPrivate, m_priv) public: DECLARE_LOG4CXX_OBJECT(FMTLayout) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(FMTLayout) LOG4CXX_CAST_ENTRY_CHAIN(Layout) END_LOG4CXX_CAST_MAP() FMTLayout(); FMTLayout(const LogString& pattern); ~FMTLayout(); /** * Set the ConversionPattern option. This is the string which * controls formatting and consists of a mix of literal content and * conversion specifiers. */ void setConversionPattern(const LogString& conversionPattern); /** * Returns the value of the ConversionPattern option. */ LogString getConversionPattern() const; /** Returns the log statement in a format consisting of the level, followed by " - " and then the message. For example,
 INFO - "A message"
		
*/ void format(LogString& output, const spi::LoggingEventPtr& event, helpers::Pool& pool) const override; bool ignoresThrowable() const override { return true; } /** \copybrief spi::OptionHandler::activateOptions() No action is performed in this implementation. */ void activateOptions(helpers::Pool& /* p */) override; /** \copybrief spi::OptionHandler::setOption() Supported options | Supported values | Default value -------------- | ---------------- | --------------- ConversionPattern | {any} | - */ void setOption(const LogString& /* option */, const LogString& /* value */) override; }; LOG4CXX_PTR_DEF(FMTLayout); } // namespace log4cxx #if defined(_MSC_VER) #pragma warning ( pop ) #endif #endif //LOG4CXX_FMT_LAYOUT_H apache-log4cxx-1.3.1/src/main/include/log4cxx/htmllayout.h0000644000175100001770000000673314721727031023006 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HTML_LAYOUT_H #define _LOG4CXX_HTML_LAYOUT_H #include #include namespace LOG4CXX_NS { /** This layout outputs events in a HTML table. */ class LOG4CXX_EXPORT HTMLLayout : public Layout { private: LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(HTMLLayoutPrivate, m_priv) public: DECLARE_LOG4CXX_OBJECT(HTMLLayout) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(HTMLLayout) LOG4CXX_CAST_ENTRY_CHAIN(Layout) END_LOG4CXX_CAST_MAP() HTMLLayout(); ~HTMLLayout(); /** 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 net::SMTPAppender SMTPAppender} then make sure to set the LocationInfo option of that appender as well. */ void setLocationInfo(bool locationInfoFlag); /** Returns the current value of the LocationInfo option. */ bool getLocationInfo() const; /** The Title option takes a String value. This option sets the document title of the generated HTML document.

Defaults to 'Log4cxx Log Messages'. */ void setTitle(const LogString& title1); /** Returns the current value of the Title option. */ const LogString& getTitle() const; /** Returns the content type output by this layout, i.e "text/html". */ LogString getContentType() const override; /** \copybrief spi::OptionHandler::activateOptions() No action is performed in this implementation. */ void activateOptions(helpers::Pool& /* p */) override {} /** \copybrief spi::OptionHandler::setOption() Supported options | Supported values | Default value -------------- | ---------------- | --------------- Title | {any} | Log4cxx Log Messages LocationInfo | True,False | False */ void setOption(const LogString& option, const LogString& value) override; void format(LogString& output, const spi::LoggingEventPtr& event, helpers::Pool& pool) const override; /** Append appropriate HTML headers. */ void appendHeader(LogString& output, helpers::Pool& pool) override; /** Append the appropriate HTML footers. */ void appendFooter(LogString& output, helpers::Pool& pool) override; /** The HTML layout handles the throwable contained in logging events. Hence, this method return false. */ bool ignoresThrowable() const override; }; // class HtmlLayout LOG4CXX_PTR_DEF(HTMLLayout); } // namespace log4cxx #endif // _LOG4CXX_HTML_LAYOUT_H apache-log4cxx-1.3.1/src/main/include/log4cxx/jsonlayout.h0000644000175100001770000000776314721727031023017 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_JSON_LAYOUT_H #define _LOG4CXX_JSON_LAYOUT_H #include #include #include namespace LOG4CXX_NS { /** This layout outputs events in a JSON dictionary. */ class LOG4CXX_EXPORT JSONLayout : public Layout { private: LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(JSONLayoutPrivate, m_priv) protected: void appendQuotedEscapedString(LogString& buf, const LogString& input) const; void appendSerializedMDC(LogString& buf, const spi::LoggingEventPtr& event) const; void appendSerializedNDC(LogString& buf, const spi::LoggingEventPtr& event) const; void appendSerializedLocationInfo(LogString& buf, const spi::LoggingEventPtr& event, LOG4CXX_NS::helpers::Pool& p) const; public: static void appendItem(const LogString& item, LogString& toAppendTo); DECLARE_LOG4CXX_OBJECT(JSONLayout) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(JSONLayout) LOG4CXX_CAST_ENTRY_CHAIN(Layout) END_LOG4CXX_CAST_MAP() JSONLayout(); ~JSONLayout(); /** 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. */ void setLocationInfo(bool locationInfoFlag); /** Returns the current value of the LocationInfo option. */ bool getLocationInfo() const; /** The PrettyPrint option takes a boolean value. By default, it is set to false which means output by this layout will be one line per log event. If the option is set to true, then then each log event will produce multiple lines, each indented for readability. */ void setPrettyPrint(bool prettyPrintFlag); /** Returns the current value of the PrettyPrint option. */ bool getPrettyPrint() const; /** Set thread info output mode to \c newValue. @param newValue true to include a thread identifier. */ void setThreadInfo(bool newValue); /** Is a thread identifier included in the output? */ bool getThreadInfo() const; /** Returns the content type output by this layout, i.e "application/json". */ LogString getContentType() const override; /** \copybrief spi::OptionHandler::activateOptions() No action is performed in this implementation. */ void activateOptions(helpers::Pool& /* p */) override; /** \copybrief spi::OptionHandler::setOption() Supported options | Supported values | Default value -------------- | ---------------- | --------------- LocationInfo | True,False | false ThreadInfo | True,False | false PrettyPrint | True,False | false */ void setOption(const LogString& option, const LogString& value) override; void format(LogString& output, const spi::LoggingEventPtr& event, helpers::Pool& pool) const override; /** The JSON layout handles the throwable contained in logging events. Hence, this method return false. */ bool ignoresThrowable() const override { return false; } }; // class JSONLayout LOG4CXX_PTR_DEF(JSONLayout); } // namespace log4cxx #endif // _LOG4CXX_JSON_LAYOUT_H apache-log4cxx-1.3.1/src/main/include/log4cxx/levelchange.h0000644000175100001770000000566314721727031023062 0ustar runnerdocker/* * 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. */ #ifndef LOG4CXX_LEVEL_CHANGE_HDR_ #define LOG4CXX_LEVEL_CHANGE_HDR_ #include #include namespace LOG4CXX_NS { /** * Changes a verbosity level for the instance variable's lifetime. * Create a LevelChange variable on the stack * to temporarily (e.g. for a single method) * increase the quantity of information logged. * Typically used to propagate the locally used logger's level (e.g. DEBUG or TRACE) * to another named (e.g. the name of the class of the method invoked next) logger. * The LevelChange variable does not need to be removed from the code (e.g. for a release build) * as it has no impact when the local and other logger point to the same level * (e.g. null_ptr, implying their level is inherited). */ class LevelChange { LoggerPtr m_otherCategory; LevelPtr m_savedLevel; public: // ...structors /// Set \c otherCategory to \c level LevelChange(const LoggerPtr& otherCategory, const LevelPtr& level) : m_otherCategory(otherCategory) , m_savedLevel(otherCategory->getLevel()) { m_otherCategory->setLevel(level); } /// Set \c otherCategory to the level of \c thisCategory LevelChange(const LoggerPtr& otherCategory, const LoggerPtr& thisCategory) : LevelChange(otherCategory, thisCategory->getLevel()) { } /// Set the logger named \c otherCategory to \c level template LevelChange(const StringType& otherCategory, const LevelPtr& level) : LevelChange(LogManager::getLogger(otherCategory), level) { } /// Set the logger named \c otherCategory to the level of \c thisCategory template LevelChange(const StringType& otherCategory, const LoggerPtr& thisCategory) : LevelChange(LogManager::getLogger(otherCategory), thisCategory->getLevel()) { } /// Restore the verbosity level of the other logger ~LevelChange() { m_otherCategory->setLevel(m_savedLevel); } private: // Prevent copies and assignment LevelChange(const LevelChange&) = delete; LevelChange(LevelChange&&) = delete; LevelChange& operator=(const LevelChange&) = delete; LevelChange& operator=(LevelChange&&) = delete; }; } // namespace LOG4CXX_NS #endif // LOG4CXX_LEVEL_CHANGE_HDR_ apache-log4cxx-1.3.1/src/main/include/log4cxx/db/0000755000175100001770000000000014721727031021007 5ustar runnerdockerapache-log4cxx-1.3.1/src/main/include/log4cxx/db/odbcappender.h0000644000175100001770000002266614721727031023622 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_DB_ODBC_APPENDER_H #define _LOG4CXX_DB_ODBC_APPENDER_H #include #include #include #include #if LOG4CXX_EVENTS_AT_EXIT #include #endif #include #include namespace LOG4CXX_NS { namespace db { class LOG4CXX_EXPORT SQLException : public LOG4CXX_NS::helpers::Exception { public: SQLException(short fHandleType, void* hInput, const char* prolog, LOG4CXX_NS::helpers::Pool& p); SQLException(const char* msg); SQLException(const SQLException& src); private: const char* formatMessage(short fHandleType, void* hInput, const char* prolog, LOG4CXX_NS::helpers::Pool& p); }; /** The ODBCAppender sends log events to a database.

Each append call adds the spi::LoggingEvent to a buffer. When the buffer is full, values are extracted from each spi::LoggingEvent and the sql insert statement executed. The SQL insert statement pattern must be provided either in the Log4cxx configuration file using the sql parameter element or programatically by calling the setSql(String sql) method. The following param elements are optional: - one of DSN, URL, ConnectionString - The serverName parameter value in the SQLConnect call. - User - The UserName parameter value in the SQLConnect call. - Password - The Authentication parameter value in the SQLConnect call. - BufferSize - Delay executing the sql until this many logging events are available. One by default, meaning an sql statement is executed whenever a logging event is appended. - ColumnMapping - One element for each "?" in the sql statement in a sequence corresponding to the columns in the insert statement. The following values are supported: - logger - the name of the logger that generated the logging event - level - the level of the logging event - thread - the thread number as a hex string that generated the logging event - threadname - the name assigned to the thread that generated the logging event - time - a datetime or datetime2 SQL field type at which the event was generated - shortfilename - the basename of the file containing the logging statement - fullfilename - the path of the file containing the logging statement - line - the position in the file at which the logging event was generated - class - the class from which the logging event was generated (\ref usingMacros "1") - method - the function in which the logging event was generated (\ref usingMacros "1") - message - the data sent by the logging statement - mdc - A JSON format string of all entries in the logging thread's mapped diagnostic context - mdc{key} - the value associated with the key entry in the logging thread's mapped diagnostic context - ndc - the last entry the logging thread's nested diagnostic context \anchor usingMacros (1) Only available when the LOG4CXX_* macros are used to issue the logging request.

For use as a base class:

  • Override getConnection() to pass any connection you want. Typically this is used to enable application wide connection pooling.
  • Override closeConnection -- if you override getConnection make sure to implement closeConnection to handle the connection you generated. Typically this would return the connection to the pool it came from.
An example configuration that writes to the data source named "LoggingDSN" is: ~~~{.xml} ~~~ You may also want to consider the DBAppender class, which uses APR in order to support logging to databases apart from ODBC. */ class LOG4CXX_EXPORT ODBCAppender : public AppenderSkeleton { public: DECLARE_LOG4CXX_OBJECT(ODBCAppender) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(ODBCAppender) LOG4CXX_CAST_ENTRY_CHAIN(AppenderSkeleton) END_LOG4CXX_CAST_MAP() typedef void* SQLHDBC; typedef void* SQLHENV; typedef void* SQLHANDLE; typedef short SQLSMALLINT; ODBCAppender(); virtual ~ODBCAppender(); /** \copybrief AppenderSkeleton::setOption() Supported options | Supported values | Default value :-------------- | :----------------: | :---------------: BufferSize | {int} | 1 ConnectionString | {any} | - URL | {any} | - DSN | {any} | - User | {any} | - Password | {any} | - SQL | {any} | - ColumnMapping | (\ref colName "^") | - \anchor colName (^) One value for each '?' character in the SQL value. \sa AppenderSkeleton::setOption() */ void setOption(const LogString& option, const LogString& value) override; /** Activate the specified options. */ void activateOptions(helpers::Pool& p) override; /** * Adds the event to the buffer. When full the buffer is flushed. */ void append(const spi::LoggingEventPtr& event, helpers::Pool&) override; protected: /** * To be removed. */ LogString getLogStatement(const spi::LoggingEventPtr& event, helpers::Pool& p) const; /** * * To be removed. * */ virtual void execute(const LogString& sql, LOG4CXX_NS::helpers::Pool& p) /*throw(SQLException)*/; /** * Override this to return the connection to a pool, or to clean up the * resource. * * The default behavior holds a single connection open until the appender * is closed (typically when garbage collected). */ virtual void closeConnection(SQLHDBC con); /** * Override this to link with your connection pooling system. * * By default this creates a single connection which is held open * until the object is garbage collected. */ virtual SQLHDBC getConnection(LOG4CXX_NS::helpers::Pool& p) /*throw(SQLException)*/; /** * Closes the appender, flushing the buffer first then closing the default * connection if it is open. */ public: void close() override; /** * loops through the buffer of LoggingEvents, gets a * sql string from getLogStatement() and sends it to execute(). * Errors are sent to the errorHandler. * * If a statement fails the LoggingEvent stays in the buffer! */ virtual void flushBuffer(LOG4CXX_NS::helpers::Pool& p); /** * Does this appender require a layout? * */ bool requiresLayout() const override; /** * Set pre-formated statement eg: insert into LogTable (msg) values ("%m") */ void setSql(const LogString& s); /** * Returns pre-formated statement eg: insert into LogTable (msg) values ("%m") */ const LogString& getSql() const; void setUser(const LogString& user); void setURL(const LogString& url); void setPassword(const LogString& password); void setBufferSize(size_t newBufferSize); const LogString& getUser() const; const LogString& getURL() const; const LogString& getPassword() const; size_t getBufferSize() const; private: ODBCAppender(const ODBCAppender&); ODBCAppender& operator=(const ODBCAppender&); #if LOG4CXX_WCHAR_T_API || LOG4CXX_LOGCHAR_IS_WCHAR_T || defined(WIN32) || defined(_WIN32) static void encode(wchar_t** dest, const LogString& src, LOG4CXX_NS::helpers::Pool& p); #endif static void encode(unsigned short** dest, const LogString& src, LOG4CXX_NS::helpers::Pool& p); protected: struct ODBCAppenderPriv; }; // class ODBCAppender LOG4CXX_PTR_DEF(ODBCAppender); } // namespace db } // namespace log4cxx #endif // _LOG4CXX_DB_ODBC_APPENDER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/db/dbappender.h0000644000175100001770000001606214721727031023271 0ustar runnerdocker/* * 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. */ #ifndef LOG4CXX_DB_DB_APPENDER_H #define LOG4CXX_DB_DB_APPENDER_H #include #include #include #include #include #include namespace LOG4CXX_NS { namespace db { /** * The DBAppender lets you log messages to a database. This utilizes the APR's database support in order * to provide a single way of logging to multiple databases, not just ODBC as the ODBCAppender does. * * The following SQL script is an example of how you may make a table that stores log messages: * * ~~~{.sql} * CREATE TABLE logs ( * logger VARCHAR(200), * time DATETIME, * level CHAR(5), * file VARCHAR(200), * line_number INT, * message VARCHAR(1000) * ); * ~~~ * * Once you have defined the table, you must define the order in which the columns are formatted when they are inserted * along with the insert statement. * * Using APR, the following insert statement can be used to insert log statements: INSERT INTO logs (logger, time, level, file, line_number, message) VALUES (%s, %pDa, %s, %s, %d, %s) * The values to insert must be formatted appropriately and in the correct order. In order to do this, the parameter ColumnMapping must be specified as many times * as there are columns to insert. * * The following table shows the conversion specifiers. These are effectively the same as the conversion patterns provided by PatternLayout but with more descriptive names: * |Conversion Specifier|Effect| * |---|---| * |logger|The name of the logger(e.g. com.foo.bar)| * |class|The class that the log message was in| * |time|The time of the log message| * |shortfilename|The short filename where the log message is from| * |fullfilename|The full filename where the log mesasge is from| * |location|The location of the log message| * |line|The line where the log message appears| * |message|The log message| * |method|The method where the message was logged| * |level|The level of the log message| * |thread|The thread where this message was logged| * |threadname|The name of the thread that logged the message| * |ndc|The NDC(nested diagnostic context) of the log| * * Other parameters that are important: * |Parameter name|Usage| * |---|---| * |DriverName|The name of the database driver to load(ex: odbc, sqlite3)| * |DriverParams|A string of parameters to pass to the driver. This is database-specific| * |DatabaseName|The name of the database to use when connecting to the server| * * The following code shows how you might connect to an ODBC data source and insert the log messages: * ~~~{.xml} * * * * * * * * * * * * * ~~~ * * A similar configuration can be used for SQLite: * ~~~{.xml} * * * * * * * * * * * * ~~~ */ class LOG4CXX_EXPORT DBAppender : public AppenderSkeleton { public: DECLARE_LOG4CXX_OBJECT(DBAppender) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(DBAppender) LOG4CXX_CAST_ENTRY_CHAIN(AppenderSkeleton) END_LOG4CXX_CAST_MAP() DBAppender(); virtual ~DBAppender(); /** \copybrief AppenderSkeleton::setOption() Supported options | Supported values | Default value :-------------- | :----------------: | :---------------: DriverName | {any} | - DriverParams | {any} | - DatabaseName | {any} | - SQL | {any} | - ColumnMapping | (\ref rep "^") | - \anchor rep (^) One value for each '%%' character in the SQL value. \sa AppenderSkeleton::setOption() */ void setOption(const LogString& option, const LogString& value) override; /** Activate the specified options. */ void activateOptions(helpers::Pool& p) override; /** * Adds the event to the buffer. When full the buffer is flushed. */ void append(const spi::LoggingEventPtr& event, helpers::Pool&) override; void close() override; /** * DBAppender does not require a layout. * */ bool requiresLayout() const override { return false; } /** * Set pre-formated statement eg: insert into LogTable (msg) values (?) */ void setSql(const LogString& s); /** * Returns pre-formated statement eg: insert into LogTable (msg) values (?) */ const LogString& getSql() const; private: DBAppender(const DBAppender&); DBAppender& operator=(const DBAppender&); protected: struct DBAppenderPriv; }; // class DBAppender LOG4CXX_PTR_DEF(DBAppender); } // namespace db } // namespace log4cxx #endif // LOG4CXX_DB_DB_APPENDER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/defaultloggerfactory.h0000644000175100001770000000304414721727031025010 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_DEFAULT_LOGGER_FACTORY_H #define _LOG4CXX_DEFAULT_LOGGER_FACTORY_H #include #include namespace LOG4CXX_NS { class Logger; typedef std::shared_ptr LoggerPtr; #if LOG4CXX_ABI_VERSION <= 15 class LOG4CXX_EXPORT DefaultLoggerFactory : public virtual spi::LoggerFactory, public virtual helpers::Object { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(DefaultLoggerFactory) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(spi::LoggerFactory) END_LOG4CXX_CAST_MAP() [[ deprecated( "Pool is no longer required" ) ]] LoggerPtr makeNewLoggerInstance(helpers::Pool& pool, const LogString& name) const override; }; #endif } // namespace log4cxx #endif //_LOG4CXX_DEFAULT_LOGGER_FACTORY_H apache-log4cxx-1.3.1/src/main/include/log4cxx/xml/0000755000175100001770000000000014721727031021222 5ustar runnerdockerapache-log4cxx-1.3.1/src/main/include/log4cxx/xml/xmllayout.h0000644000175100001770000000743014721727031023435 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_XML_LAYOUT_H #define _LOG4CXX_XML_LAYOUT_H #include namespace LOG4CXX_NS { namespace xml { /** The output of the XMLLayout consists of a series of log4j:event elements. It does not output a complete well-formed XML file. The output is designed to be included as an external entity in a separate file to form a correct XML file.

For example, if abc is the name of the file where the XMLLayout ouput goes, then a well-formed XML file would be: ]> @&data;

This approach enforces the independence of the XMLLayout and the appender where it is embedded. */ class LOG4CXX_EXPORT XMLLayout : public Layout { private: LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(XMLLayoutPrivate, m_priv) public: DECLARE_LOG4CXX_OBJECT(XMLLayout) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(XMLLayout) LOG4CXX_CAST_ENTRY_CHAIN(Layout) END_LOG4CXX_CAST_MAP() XMLLayout(); ~XMLLayout(); /** 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 a SMTPAppender then make sure to set the LocationInfo option of that appender as well. */ void setLocationInfo(bool locationInfo1); /** Returns the current value of the LocationInfo option. */ bool getLocationInfo() const; /** * Sets whether MDC key-value pairs should be output, default false. * @param flag new value. * */ void setProperties(bool flag); /** * Gets whether MDC key-value pairs should be output. * @return true if MDC key-value pairs are output. * */ bool getProperties(); /** \copybrief spi::OptionHandler::activateOptions() No action is performed in this implementation. */ void activateOptions(helpers::Pool& /* p */) override { } /** \copybrief spi::OptionHandler::setOption() Supported options | Supported values | Default value -------------- | ---------------- | --------------- Properties | True,False | False LocationInfo | True,False | False */ void setOption(const LogString& option, const LogString& value) override; /** * Formats a {@link spi::LoggingEvent LoggingEvent} * in conformance with the log4cxx.dtd. **/ void format(LogString& output, const spi::LoggingEventPtr& event, helpers::Pool& p) const override; /** The XMLLayout prints and does not ignore exceptions. Hence the return value false. */ bool ignoresThrowable() const override { return false; } }; // class XMLLayout LOG4CXX_PTR_DEF(XMLLayout); } // namespace xml } // namespace log4cxx #endif // _LOG4CXX_XML_LAYOUT_H apache-log4cxx-1.3.1/src/main/include/log4cxx/xml/domconfigurator.h0000644000175100001770000002767214721727031024613 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_XML_DOM_CONFIGURATOR_H #define _LOG4CXX_XML_DOM_CONFIGURATOR_H #include #include #include #include #include #include #include #include #include #include #include #include #include #if LOG4CXX_HAS_DOMCONFIGURATOR extern "C" { struct apr_xml_doc; struct apr_xml_elem; } namespace LOG4CXX_NS { namespace xml { class XMLWatchdog; /** Use this class to initialize the log4cxx environment using a DOM tree.

Sometimes it is useful to see how log4cxx is reading configuration files. You can enable log4cxx internal logging by setting the debug attribute in the log4cxx element. As in

        <log4j:configuration debug="true" xmlns:log4j="http://jakarta.apache.org/log4j/">
        ...
        </log4j:configuration>

There are sample XML files included in the package. */ class LOG4CXX_EXPORT DOMConfigurator : virtual public spi::Configurator { public: ~DOMConfigurator(); protected: typedef std::map AppenderMap; /** Used internally to parse appenders by IDREF name. */ AppenderPtr findAppenderByName( LOG4CXX_NS::helpers::Pool& p, LOG4CXX_NS::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* elem, apr_xml_doc* doc, const LogString& appenderName, AppenderMap& appenders); /** Used internally to parse appenders by IDREF element. */ AppenderPtr findAppenderByReference( LOG4CXX_NS::helpers::Pool& p, LOG4CXX_NS::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* appenderRef, apr_xml_doc* doc, AppenderMap& appenders); /** Used internally to parse an appender element. */ AppenderPtr parseAppender( LOG4CXX_NS::helpers::Pool& p, LOG4CXX_NS::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* appenderElement, apr_xml_doc* doc, AppenderMap& appenders); /** Used internally to parse an {@link spi::ErrorHandler ErrorHandler } element. */ void parseErrorHandler( LOG4CXX_NS::helpers::Pool& p, LOG4CXX_NS::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* element, AppenderPtr& appender, apr_xml_doc* doc, AppenderMap& appenders); /** Used internally to parse a filter element. */ void parseFilters( LOG4CXX_NS::helpers::Pool& p, LOG4CXX_NS::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* element, std::vector& filters); /** Used internally to parse a logger element. */ void parseLogger( LOG4CXX_NS::helpers::Pool& p, LOG4CXX_NS::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* loggerElement, apr_xml_doc* doc, AppenderMap& appenders); /** Used internally to parse the logger factory element. */ void parseLoggerFactory( LOG4CXX_NS::helpers::Pool& p, LOG4CXX_NS::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* factoryElement); /** Used internally to parse the logger factory element. */ LOG4CXX_NS::helpers::ObjectPtr parseTriggeringPolicy( LOG4CXX_NS::helpers::Pool& p, LOG4CXX_NS::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* factoryElement); /** Used internally to parse the logger factory element. */ LOG4CXX_NS::rolling::RollingPolicyPtr parseRollingPolicy( LOG4CXX_NS::helpers::Pool& p, LOG4CXX_NS::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* factoryElement); /** Used internally to parse the root logger element. */ void parseRoot(LOG4CXX_NS::helpers::Pool& p, LOG4CXX_NS::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* rootElement, apr_xml_doc* doc, AppenderMap& appenders); /** Used internally to parse the children of a logger element. */ void parseChildrenOfLoggerElement( LOG4CXX_NS::helpers::Pool& p, LOG4CXX_NS::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* catElement, LoggerPtr logger, bool isRoot, apr_xml_doc* doc, AppenderMap& appenders ); /** Used internally to parse a layout element. */ LayoutPtr parseLayout( LOG4CXX_NS::helpers::Pool& p, LOG4CXX_NS::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* layout_element); /** Used internally to parse a level element. */ void parseLevel( LOG4CXX_NS::helpers::Pool& p, LOG4CXX_NS::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* element, LoggerPtr logger, bool isRoot); void setParameter( LOG4CXX_NS::helpers::Pool& p, LOG4CXX_NS::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* elem, LOG4CXX_NS::config::PropertySetter& propSetter); /** Used internally to configure the log4cxx framework from an in-memory representation of an XML document. */ void parse( LOG4CXX_NS::helpers::Pool& p, LOG4CXX_NS::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* element, apr_xml_doc* doc, AppenderMap& appenders); public: DOMConfigurator(); DECLARE_LOG4CXX_OBJECT(DOMConfigurator) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(spi::Configurator) END_LOG4CXX_CAST_MAP() DOMConfigurator(LOG4CXX_NS::helpers::Pool& p); #if LOG4CXX_ABI_VERSION <= 15 /** A static version of #doConfigure. */ static spi::ConfigurationStatus configure(const char* filename) { return configure(std::string(filename)); } /** A static version of #doConfigure. */ static spi::ConfigurationStatus configure(const std::string& filename); #if LOG4CXX_WCHAR_T_API /** A static version of #doConfigure. */ static spi::ConfigurationStatus configure(const wchar_t* filename) { return configure(std::wstring(filename)); } /** A static version of #doConfigure. */ static spi::ConfigurationStatus configure(const std::wstring& filename); #endif #if LOG4CXX_UNICHAR_API || LOG4CXX_LOGCHAR_IS_UNICHAR /** A static version of #doConfigure. */ static spi::ConfigurationStatus configure(const std::basic_string& filename); #endif #if LOG4CXX_CFSTRING_API /** A static version of #doConfigure. */ static spi::ConfigurationStatus configure(const CFStringRef& filename); #endif /** Like #configureAndWatch(const File& filename, long delay) except that the default delay as defined by log4cxx::helpers::FileWatchdog#DEFAULT_DELAY is used. @param configFilename A configuration file in XML format. */ static spi::ConfigurationStatus configureAndWatch(const std::string& configFilename); #if LOG4CXX_WCHAR_T_API /** Like #configureAndWatch(const File& filename, long delay) except that the default delay as defined by log4cxx::helpers::FileWatchdog#DEFAULT_DELAY is used. @param configFilename A configuration file in XML format. */ static spi::ConfigurationStatus configureAndWatch(const std::wstring& configFilename); #endif #if LOG4CXX_UNICHAR_API || LOG4CXX_LOGCHAR_IS_UNICHAR /** Like #configureAndWatch(const File& filename, long delay) except that the default delay as defined by log4cxx::helpers::FileWatchdog#DEFAULT_DELAY is used. @param configFilename A configuration file in XML format. */ static spi::ConfigurationStatus configureAndWatch(const std::basic_string& configFilename); #endif #if LOG4CXX_CFSTRING_API /** Like #configureAndWatch(const File& filename, long delay) except that the default delay as defined by log4cxx::helpers::FileWatchdog#DEFAULT_DELAY is used. @param configFilename A configuration file in XML format. */ static spi::ConfigurationStatus configureAndWatch(const CFStringRef& configFilename); #endif /** 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 log4cxx. The thread will be stopped by a LogManager::shutdown call. @param configFilename A configuration file in XML format. @param delay The delay in milliseconds to wait between each check. */ static spi::ConfigurationStatus configureAndWatch(const std::string& configFilename, long delay); #if LOG4CXX_WCHAR_T_API /** Refer #configureAndWatch(const File& filename, long delay) */ static spi::ConfigurationStatus configureAndWatch(const std::wstring& configFilename, long delay); #endif #if LOG4CXX_UNICHAR_API || LOG4CXX_LOGCHAR_IS_UNICHAR /** Refer #configureAndWatch(const File& filename, long delay) */ static spi::ConfigurationStatus configureAndWatch(const std::basic_string& configFilename, long delay); #endif #if LOG4CXX_CFSTRING_API /** Refer #configureAndWatch(const File& filename, long delay) */ static spi::ConfigurationStatus configureAndWatch(const CFStringRef& configFilename, long delay); #endif #endif // LOG4CXX_ABI_VERSION <= 15 /** Interpret \c filename as an XML file and set up Log4cxx accordingly. If \c repository is not provided, the spi::LoggerRepository held by LogManager is used. The existing configuration is not cleared nor reset. If you require a different behavior, call {@link spi::LoggerRepository::resetConfiguration resetConfiguration} before calling doConfigure. @param filename The file to parse. @param repository Where the Logger instances reside. */ spi::ConfigurationStatus doConfigure ( const File& filename #if LOG4CXX_ABI_VERSION <= 15 , spi::LoggerRepositoryPtr repository #else , const spi::LoggerRepositoryPtr& repository = spi::LoggerRepositoryPtr() #endif ) override; /** Read configuration options from \c configFilename. Stores Logger instances in the spi::LoggerRepository held by LogManager. */ static spi::ConfigurationStatus configure(const File& configFilename); /** Read configuration options from \c configFilename (if it exists). A thread will be created that periodically checks whether \c configFilename has been created or modified. A period of log4cxx::helpers::FileWatchdog#DEFAULT_DELAY is used if \c delay is not a positive number. If a change or file creation is detected, then \c configFilename is read to configure Log4cxx. The thread will be stopped by a LogManager::shutdown call. @param configFilename A XML format file. @param delay The delay in milliseconds to wait between each check. */ static spi::ConfigurationStatus configureAndWatch(const File& configFilename, long delay = 0); protected: static LogString getAttribute( LOG4CXX_NS::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem*, const std::string& attrName); LogString subst(const LogString& value); private: // prevent assignment or copy statements DOMConfigurator(const DOMConfigurator&); DOMConfigurator& operator=(const DOMConfigurator&); static XMLWatchdog* xdog; LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(DOMConfiguratorPrivate, m_priv) }; LOG4CXX_PTR_DEF(DOMConfigurator); } // namespace xml } // namespace log4cxx #endif /* LOG4CXX_HAS_DOMCONFIGURATOR */ #endif // _LOG4CXX_XML_DOM_CONFIGURATOR_H apache-log4cxx-1.3.1/src/main/include/log4cxx/layout.h0000644000175100001770000000516314721727031022115 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_LAYOUT_H #define _LOG4CXX_LAYOUT_H #include #include #include namespace LOG4CXX_NS { /** Extend this abstract class to create your own log layout format. */ class LOG4CXX_EXPORT Layout : public virtual spi::OptionHandler, public virtual helpers::Object { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(Layout) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(Layout) LOG4CXX_CAST_ENTRY(spi::OptionHandler) END_LOG4CXX_CAST_MAP() virtual ~Layout(); /** Implement this method to create your own layout format. */ virtual void format(LogString& output, const spi::LoggingEventPtr& event, LOG4CXX_NS::helpers::Pool& pool) const = 0; /** Returns the content type output by this layout. The base class returns "text/plain". */ virtual LogString getContentType() const; /** Append the header for the layout format. The base class does nothing. */ virtual void appendHeader(LogString& output, LOG4CXX_NS::helpers::Pool& p); /** Append the footer for the layout format. The base class does nothing. */ virtual void appendFooter(LogString& output, LOG4CXX_NS::helpers::Pool& p); /** If the layout handles the throwable object contained within {@link spi::LoggingEvent LoggingEvent}, then the layout should return false. Otherwise, if the layout ignores throwable object, then the layout should return true.

The SimpleLayout, FMTLayout and PatternLayout return true. The other layouts return false. */ virtual bool ignoresThrowable() const = 0; protected: /** * The expected length of a formatted event excluding the message text */ size_t getFormattedEventCharacterCount() const; }; LOG4CXX_PTR_DEF(Layout); } #endif // _LOG4CXX_LAYOUT_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/0000755000175100001770000000000014721727031022064 5ustar runnerdockerapache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/inetaddress.h0000644000175100001770000000512314721727031024543 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPER_INETADDRESS_H #define _LOG4CXX_HELPER_INETADDRESS_H #include #include #include #include namespace LOG4CXX_NS { namespace helpers { class UnknownHostException : public Exception { public: UnknownHostException(const LogString& msg); UnknownHostException(const UnknownHostException& src); UnknownHostException& operator=(const UnknownHostException& src); }; class InetAddress; LOG4CXX_PTR_DEF(InetAddress); LOG4CXX_LIST_DEF(InetAddressList, InetAddressPtr); class LOG4CXX_EXPORT InetAddress : public Object { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(InetAddress) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(InetAddress) END_LOG4CXX_CAST_MAP() InetAddress(const LogString& hostName, const LogString& hostAddr); ~InetAddress(); /** Determines all the IP addresses of a host, given the host's name. */ static InetAddressList getAllByName(const LogString& host); /** Determines the IP address of a host, given the host's name. */ static InetAddressPtr getByName(const LogString& host); /** Returns the IP address string "%d.%d.%d.%d". */ LogString getHostAddress() const; /** Gets the host name for this IP address. */ LogString getHostName() const; /** Returns the local host. */ static InetAddressPtr getLocalHost(); /** Returns an InetAddress which can be used as any * address, for example when listening on a port from any * remote addresss. */ static InetAddressPtr anyAddress(); /** Converts this IP address to a String. */ LogString toString() const; private: LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(InetAddressPrivate, m_priv) }; // class InetAddress } // namespace helpers } // namespace log4cxx #endif // _LOG4CXX_HELPER_INETADDRESS_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/appenderattachableimpl.h0000644000175100001770000000610014721727031026723 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_APPENDER_ATTACHABLE_IMPL_H #define _LOG4CXX_HELPERS_APPENDER_ATTACHABLE_IMPL_H #include #include #include namespace LOG4CXX_NS { namespace spi { class LoggingEvent; typedef std::shared_ptr LoggingEventPtr; } namespace helpers { class LOG4CXX_EXPORT AppenderAttachableImpl : public virtual spi::AppenderAttachable { protected: AppenderList& appenderList(); public: /** * Create new instance. */ AppenderAttachableImpl(); #if LOG4CXX_ABI_VERSION <= 15 [[ deprecated( "Pool is no longer required" ) ]] AppenderAttachableImpl(Pool& pool); #endif ~AppenderAttachableImpl(); DECLARE_ABSTRACT_LOG4CXX_OBJECT(AppenderAttachableImpl) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(AppenderAttachableImpl) LOG4CXX_CAST_ENTRY(spi::AppenderAttachable) END_LOG4CXX_CAST_MAP() // Methods /** * Add an appender. */ void addAppender(const AppenderPtr newAppender) override; /** Call the doAppend method on all attached appenders. */ int appendLoopOnAppenders(const spi::LoggingEventPtr& event, LOG4CXX_NS::helpers::Pool& p); /** * Get all previously added appenders as an Enumeration. */ AppenderList getAllAppenders() const override; /** * Get an appender by name. */ AppenderPtr getAppender(const LogString& name) const override; /** Returns true if the specified appender is in the list of attached appenders, false otherwise. */ bool isAttached(const AppenderPtr appender) const override; /** * Remove all previously added appenders. */ void removeAllAppenders() override; /** * Remove the appender passed as parameter from the list of appenders. */ void removeAppender(const AppenderPtr appender) override; /** * Remove the appender with the name passed as parameter from the * list of appenders. */ void removeAppender(const LogString& name) override; private: LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(priv_data, m_priv) AppenderAttachableImpl(const AppenderAttachableImpl&); AppenderAttachableImpl& operator=(const AppenderAttachableImpl&); }; LOG4CXX_PTR_DEF(AppenderAttachableImpl); } } #endif //_LOG4CXX_HELPERS_APPENDER_ATTACHABLE_IMPL_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/datetimedateformat.h0000644000175100001770000000272414721727031026105 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_DATE_TIME_DATE_FORMAT_H #define _LOG4CXX_HELPERS_DATE_TIME_DATE_FORMAT_H #include namespace LOG4CXX_NS { namespace helpers { /** Formats a date in the format dd MMM yyyy HH:mm:ss,SSS for example, "06 Nov 1994 15:49:37,459". */ class LOG4CXX_EXPORT DateTimeDateFormat : public SimpleDateFormat { public: DateTimeDateFormat() : SimpleDateFormat(LOG4CXX_STR("dd MMM yyyy HH:mm:ss,SSS")) {} DateTimeDateFormat(const std::locale* locale) : SimpleDateFormat(LOG4CXX_STR("dd MMM yyyy HH:mm:ss,SSS"), locale) {} }; } // namespace helpers } // namespace log4cxx #endif // _LOG4CXX_HELPERS_DATE_TIME_DATE_FORMAT_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/optionconverter.h0000644000175100001770000001525414721727031025504 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPER_OPTION_CONVERTER_H #define _LOG4CXX_HELPER_OPTION_CONVERTER_H #include #include namespace LOG4CXX_NS { class Level; class File; typedef std::shared_ptr LevelPtr; namespace spi { class LoggerRepository; typedef std::shared_ptr LoggerRepositoryPtr; } namespace helpers { class Properties; class Object; typedef std::shared_ptr ObjectPtr; class Class; /** A convenience class to convert property values to specific types.*/ class LOG4CXX_EXPORT OptionConverter { /** OptionConverter is a static class. */ private: OptionConverter() {} public: static LogString convertSpecialChars(const LogString& s); /** The boolean equivalent of \c value if it is not empty, otherwise \c defaultValue. If value is "true", then true is returned. If value is "false", then true is returned. Case of \c value is unimportant. @return defaultValue if \c value is not "true" or "false", otherwise the boolean equivalent of \c value */ static bool toBoolean(const LogString& value, bool defaultValue); /** The numeric equivalent of \c value if it is not empty, otherwise \c defaultValue. @return Zero if \c value does not begin with a valid integral number otherwise the numeric equivalent of \c value */ static int toInt(const LogString& value, int defaultValue); /** The numeric equivalent of \c value if it is not empty, otherwise \c defaultValue. A suffix "KB", "MB" or "GB" after an integer value converts the provided number respectively to kilobytes, megabytes and gigabytes. For example, the value "10KB" will be interpreted as 10240. */ static long toFileSize(const LogString& value, long defaultValue); /** The Level indicated by \c value if recognised otherwise \c defaultValue. To be recognised, \c value must be one of "Trace", "Debug", "Info", "Warn", "Error", "Fatal", "Off", "All" or a custom level in which case it is of the form {levelName}#{registeredClassName}.

Case of \c value is unimportant. */ static LevelPtr toLevel(const LogString& value, const LevelPtr& defaultValue); /** Find the value corresponding to key in props. Then perform variable substitution on the found value. */ static LogString findAndSubst(const LogString& key, Properties& props); /** Perform variable substitution in string val from the values of keys found in the system propeties.

The variable substitution delimeters are ${ and }.

For example, if the System properties contains "key=value", then the call ~~~{.cpp} auto s = OptionConverter.substituteVars("Value of key is ${key}."); ~~~ will set the variable s to "Value of key is value.".

If no value could be found for the specified key, then the props parameter is searched, if the value could not be found there, then substitution defaults to the empty string.

For example, if system propeties contains no value for the key "inexistentKey", then the call ~~~{.cpp} auto s = OptionConverter.subsVars("Value of inexistentKey is [${inexistentKey}]"); ~~~ will set s to "Value of inexistentKey is []"

An IllegalArgumentException is thrown if val contains a start delimeter "${" which is not balanced by a stop delimeter "}".

@param val The string on which variable substitution is performed. @param props The properties from which variable substitution is performed. @throws IllegalArgumentException if val is malformed. */ static LogString substVars(const LogString& val, Properties& props); /** * Gets the specified system property. @param key The key to search for. @param def The default value to return. @return the string value of the system property, or the default value if there is no property with that key. */ static LogString getSystemProperty(const LogString& key, const LogString& def); /** Instantiate an object given a class name. Check that the className is a subclass of superClass. If that test fails or the object could not be instantiated, then defaultValue is returned. @param className The fully qualified class name of the object to instantiate. @param superClass The class to which the new object should belong. @param defaultValue The object to return in case of non-fulfillment */ static ObjectPtr instantiateByClassName(const LogString& className, const Class& superClass, const ObjectPtr& defaultValue); static ObjectPtr instantiateByKey(Properties& props, const LogString& key, const Class& superClass, const ObjectPtr& defaultValue); /** Configure log4cxx given a configFileName.

The configFileName must point to a file which will be interpreted by a new instance of a log4cxx configurator.

All configurations steps are taken on the hierarchy passed as a parameter.

@param configFileName The location of the configuration file. @param clazz The classname, of the log4cxx configurator which will parse the file configFileName. This must be a subclass of Configurator, or null. If this value is null then a default configurator of PropertyConfigurator is used, unless the filename pointed to by configFileName ends in '.xml', in which case DOMConfigurator is used. @param hierarchy The Hierarchy to act on. @param delay If greater than zero, the milliseconds to sleep between checking if configFileName has been modified and needs to be reloaded. */ static void selectAndConfigure(const File& configFileName, const LogString& clazz, spi::LoggerRepositoryPtr hierarchy, int delay = 0); }; } // namespace helpers } // namespace log4cxx #endif //_LOG4CXX_HELPER_OPTION_CONVERTER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/widelife.h0000644000175100001770000000427414721727031024034 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_WIDELIFE_H #define _LOG4CXX_HELPERS_WIDELIFE_H #include #if defined(__cpp_concepts) && __cpp_concepts >= 201500 #include #endif namespace LOG4CXX_NS { namespace helpers { /** The WideLife wrapper is destined to prolongate the runtime logger state lifetime from static duration to infinite */ template class WideLife { public: WideLife() { new(&storage) T(); } template #if defined(__cpp_concepts) && __cpp_concepts >= 201500 requires (!std::same_as) #endif WideLife(Arg0&& arg0, Args&&... args) { new(&storage) T(std::forward(arg0), std::forward(args)...); } ~WideLife() { #if LOG4CXX_EVENTS_AT_EXIT // keep the holded value alive #else value().~T(); #endif } T& value() { return *reinterpret_cast(&storage); } const T& value() const { return *reinterpret_cast(&storage); } operator T&() { return value(); } operator const T&() const { return value(); } private: alignas(T) char storage[sizeof(T)]; // Non-copyable WideLife(const WideLife& other) = delete; WideLife(const WideLife&& other) = delete; // Non-assignable WideLife& operator=(const WideLife& other) = delete; WideLife& operator=(const WideLife&& other) = delete; }; // class WideLife } // namespace helpers } // namespace log4cx #endif //_LOG4CXX_HELPERS_WIDELIFE_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/transcoder.h0000644000175100001770000002721114721727031024404 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_TRANSCODER_H #define _LOG4CXX_HELPERS_TRANSCODER_H #include namespace LOG4CXX_NS { namespace helpers { class ByteBuffer; class Pool; /** * Simple transcoder for converting between * external char and wchar_t strings and * internal strings. * */ class LOG4CXX_EXPORT Transcoder { public: /** * Appends this specified string of UTF-8 characters to LogString. */ static void decodeUTF8(const std::string& src, LogString& dst); /** * Converts the LogString to a UTF-8 string. */ static void encodeUTF8(const LogString& src, std::string& dst); /** * Converts the LogString to a UTF-8 string. */ static char* encodeUTF8(const LogString& src, LOG4CXX_NS::helpers::Pool& p); /** * Append UCS-4 code point to a byte buffer as UTF-8. */ static void encodeUTF8(unsigned int sv, ByteBuffer& dst); /** * Append UCS-4 code point to a byte buffer as UTF-16LE. */ static void encodeUTF16LE(unsigned int sv, ByteBuffer& dst); /** * Append UCS-4 code point to a byte buffer as UTF-16BE. */ static void encodeUTF16BE(unsigned int sv, ByteBuffer& dst); /** * Decodes next character from a UTF-8 string. * @param in string from which the character is extracted. * @param iter iterator addressing start of character, will be * advanced to next character if successful. * @return scalar value (UCS-4) or 0xFFFF if invalid sequence. */ static unsigned int decode(const std::string& in, std::string::const_iterator& iter); /** * Appends UCS-4 value to a UTF-8 string. * @param ch UCS-4 value. * @param dst destination. */ static void encode(unsigned int ch, std::string& dst); /** * Appends string in the current code-page * to a LogString. */ static void decode(const std::string& src, LogString& dst); /** * Appends a LogString to a string in the current * code-page. Unrepresentable characters may be * replaced with loss characters. */ static void encode(const LogString& src, std::string& dst); /** * Encodes the specified LogString to the current * character set. * @param src string to encode. * @param p pool from which to allocate return value. * @return pool allocated string. */ static char* encode(const LogString& src, LOG4CXX_NS::helpers::Pool& p); #if LOG4CXX_WCHAR_T_API || LOG4CXX_LOGCHAR_IS_WCHAR_T || defined(WIN32) || defined(_WIN32) static void decode(const std::wstring& src, LogString& dst); static void encode(const LogString& src, std::wstring& dst); static wchar_t* wencode(const LogString& src, LOG4CXX_NS::helpers::Pool& p); /** * Decodes next character from a wstring. * @param in string from which the character is extracted. * @param iter iterator addressing start of character, will be * advanced to next character if successful. * @return scalar value (UCS-4) or 0xFFFF if invalid sequence. */ static unsigned int decode(const std::wstring& in, std::wstring::const_iterator& iter); /** * Appends UCS-4 value to a UTF-8 string. * @param ch UCS-4 value. * @param dst destination. */ static void encode(unsigned int ch, std::wstring& dst); #endif #if LOG4CXX_UNICHAR_API || LOG4CXX_LOGCHAR_IS_UNICHAR static void decode(const std::basic_string& src, LogString& dst); static void encode(const LogString& src, std::basic_string& dst); /** * Decodes next character from a UniChar string. * @param in string from which the character is extracted. * @param iter iterator addressing start of character, will be * advanced to next character if successful. * @return scalar value (UCS-4) or 0xFFFF if invalid sequence. */ static unsigned int decode(const std::basic_string& in, std::basic_string::const_iterator& iter); /** * Appends UCS-4 value to a UTF-8 string. * @param ch UCS-4 value. * @param dst destination. */ static void encode(unsigned int ch, std::basic_string& dst); #endif #if LOG4CXX_CFSTRING_API static void decode(const CFStringRef& src, LogString& dst); static CFStringRef encode(const LogString& src); #endif enum { LOSSCHAR = 0x3F }; /** * Returns a logchar value given a character literal in the ASCII charset. * Used to implement the LOG4CXX_STR macro for EBCDIC and UNICHAR. */ static logchar decode(char v); /** * Returns a LogString given a string literal in the ASCII charset. * Used to implement the LOG4CXX_STR macro for EBCDIC and UNICHAR. */ static LogString decode(const char* v); /** * Encodes a charset name in the default encoding * without using a CharsetEncoder (which could trigger recursion). */ static std::string encodeCharsetName(const LogString& charsetName); private: private: Transcoder(); Transcoder(const Transcoder&); Transcoder& operator=(const Transcoder&); enum { BUFSIZE = 256 }; static size_t encodeUTF8(unsigned int ch, char* dst); static size_t encodeUTF16BE(unsigned int ch, char* dst); static size_t encodeUTF16LE(unsigned int ch, char* dst); }; } } #if LOG4CXX_CHARSET_UTF8 && LOG4CXX_LOGCHAR_IS_UTF8 /** Create a std::string equivalent of \c src. Defines a std::string variable \c var initialized with characters equivalent to the log4cxx::LogString \c src contents. @param var The name of the new std::string variable. @param src The log4cxx::LogString variable. */ #define LOG4CXX_ENCODE_CHAR(var, src) \ const std::string& var = src /** Create a log4cxx::LogString equivalent of \c src. Defines a log4cxx::LogString variable \c var initialized with characters equivalent to the std::string \c src contents. @param var The name of the new log4cxx::LogString variable. @param src The std::string variable. */ #define LOG4CXX_DECODE_CHAR(var, src) \ const LOG4CXX_NS::LogString& var = src #else /** Create a std::string equivalent of \c src. Defines a std::string variable \c var initialized with characters equivalent to the log4cxx::LogString \c src contents. @param var The name of the new std::string variable. @param src The log4cxx::LogString variable. */ #define LOG4CXX_ENCODE_CHAR(var, src) \ std::string var; \ LOG4CXX_NS::helpers::Transcoder::encode(src, var) /** Create a log4cxx::LogString equivalent of \c src. Defines a log4cxx::LogString variable \c var initialized with characters equivalent to the std::string \c src contents. @param var The name of the new log4cxx::LogString variable. @param src The std::string variable. */ #define LOG4CXX_DECODE_CHAR(var, src) \ LOG4CXX_NS::LogString var; \ LOG4CXX_NS::helpers::Transcoder::decode(src, var) #endif /** Create a log4cxx::LogString equivalent of \c src. Defines a log4cxx::LogString variable \c var initialized with characters equivalent to the CFStringRef \c src contents. @param var The name of the new log4cxx::LogString variable. @param src The CFStringRef variable. */ #define LOG4CXX_DECODE_CFSTRING(var, src) \ LOG4CXX_NS::LogString var; \ LOG4CXX_NS::helpers::Transcoder::decode(src, var) /** Create a CFStringRef equivalent of \c src. Defines a CFStringRef variable \c var initialized with characters equivalent to the log4cxx::LogString \c src contents. @param var The name of the new CFStringRef variable. @param src The log4cxx::LogString variable. */ #define LOG4CXX_ENCODE_CFSTRING(var, src) \ CFStringRef var = LOG4CXX_NS::helpers::Transcoder::encode(src) #if LOG4CXX_LOGCHAR_IS_WCHAR /** Create a std::wstring equivalent of \c src. Defines a std::wstring variable \c var initialized with characters equivalent to the log4cxx::LogString \c src contents. @param var The name of the new std::wstring variable. @param src The log4cxx::LogString variable. */ #define LOG4CXX_ENCODE_WCHAR(var, src) \ const std::wstring& var = src /** Create a log4cxx::LogString equivalent of \c src. Defines a log4cxx::LogString variable \c var initialized with characters equivalent to the std::wstring \c src contents. @param var The name of the new log4cxx::LogString variable. @param src The std::wstring variable. */ #define LOG4CXX_DECODE_WCHAR(var, src) \ const LOG4CXX_NS::LogString& var = src #else /** Create a std::wstring equivalent of \c src. Defines a std::wstring variable \c var initialized with characters equivalent to the log4cxx::LogString \c src contents. @param var The name of the new std::wstring variable. @param src The log4cxx::LogString variable. */ #define LOG4CXX_ENCODE_WCHAR(var, src) \ std::wstring var; \ LOG4CXX_NS::helpers::Transcoder::encode(src, var) /** Create a log4cxx::LogString equivalent of \c src. Defines a log4cxx::LogString variable \c var initialized with characters equivalent to the std::wstring \c src contents. @param var The name of the new log4cxx::LogString variable. @param src The std::wstring variable. */ #define LOG4CXX_DECODE_WCHAR(var, src) \ LOG4CXX_NS::LogString var; \ LOG4CXX_NS::helpers::Transcoder::decode(src, var) #endif #if LOG4CXX_LOGCHAR_IS_UNICHAR /** Create a std::basic_string equivalent of \c src. Defines a std::basic_string variable \c var initialized with characters equivalent to the log4cxx::LogString \c src contents. @param var The name of the new std::basic_string variable. @param src The log4cxx::LogString variable. */ #define LOG4CXX_ENCODE_UNICHAR(var, src) \ const std::basic_string& var = src /** Create a log4cxx::LogString equivalent of \c src. Defines a log4cxx::LogString variable \c var initialized with characters equivalent to the std::basic_string \c src contents. @param var The name of the new log4cxx::LogString variable. @param src The std::basic_string variable. */ #define LOG4CXX_DECODE_UNICHAR(var, src) \ const LOG4CXX_NS::LogString& var = src #else /** Create a std::basic_string equivalent of \c src. Defines a std::basic_string variable \c var initialized with characters equivalent to the log4cxx::LogString \c src contents. @param var The name of the new std::basic_string variable. @param src The log4cxx::LogString variable. */ #define LOG4CXX_ENCODE_UNICHAR(var, src) \ std::basic_string var; \ LOG4CXX_NS::helpers::Transcoder::encode(src, var) /** Create a log4cxx::LogString equivalent of \c src. Defines a log4cxx::LogString variable \c var initialized with characters equivalent to the std::basic_string \c src contents. @param var The name of the new log4cxx::LogString variable. @param src The std::basic_string variable. */ #define LOG4CXX_DECODE_UNICHAR(var, src) \ LOG4CXX_NS::LogString var; \ LOG4CXX_NS::helpers::Transcoder::decode(src, var) #endif #endif //_LOG4CXX_HELPERS_TRANSCODER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/resourcebundle.h0000644000175100001770000000510514721727031025257 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_RESOURCE_BUNDLE_H #define _LOG4CXX_HELPERS_RESOURCE_BUNDLE_H #include namespace LOG4CXX_NS { namespace helpers { class Locale; class ResourceBundle; LOG4CXX_PTR_DEF(ResourceBundle); /** Resource bundles contain locale-specific objects */ class LOG4CXX_EXPORT ResourceBundle : public Object { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(ResourceBundle) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(ResourceBundle) END_LOG4CXX_CAST_MAP() /** Gets a string for the given key from this resource bundle or one of its parents. Calling this method is equivalent to calling @param key the key for the desired string @return the string for the given key @throw MissingResourceException - if no object for the given key can be found */ virtual LogString getString(const LogString& key) const = 0; /** Gets a resource bundle using the specified base name and locale @param baseName the base name of the resource bundle, a fully qualified class name or property filename @param locale the locale for which a resource bundle is desired */ static ResourceBundlePtr getBundle(const LogString& baseName, const Locale& locale); protected: /* Sets the parent bundle of this bundle. The parent bundle is searched by #getString when this bundle does not contain a particular resource. Parameters: parent - this bundle's parent bundle. */ inline void setParent(const ResourceBundlePtr& parent1) { this->parent = parent1; } /** The parent bundle of this bundle. The parent bundle is searched by #getString when this bundle does not contain a particular resource. */ LOG4CXX_DECLARE_PRIVATE_MEMBER(ResourceBundlePtr, parent) }; // class ResourceBundle } // namespace helpers } // namespace log4cxx #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/tchar.h0000644000175100001770000001626014721727031023343 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_TCHAR_H #define _LOG4CXX_HELPERS_TCHAR_H #error log4cxx/helpers/tchar.h is obsolete, see details following this line. /** * A short history of log4cxx's tchar.h * * The previous log4cxx/helpers/tchar.h contained macros that * attempted to replicate macros and functions defined by * the Microsoft SDK's tchar.h and related header files * such as _T() and TCHAR. * * When building apps using both log4cxx and Microsoft SDK's tchar.h, * these definitions could conflict and, for example, the code generated * by _T("Foo") would depend on the include order of the two * tchar.h's. * * The motivation of tchar.h in the Microsoft SDK was to * support presenting either a wide-char or multi-byte char * facade to a C API depending on the presence of * the _UNICODE or _MBCS preprocessor macros. When _UNICODE * was set then tchar was typedef'd as wchar_t and, for example, * the CreateProcess macro was defined to be CreateProcessW, If * _MBCS was defined, then tchar was typedef'd as char * and CreateProcess macro was defined to be CreateProcessA. * * In either case, the setting of _UNICODE or _MBCS * didn't affect the implementation of the operating system. * If you were running the Windows NT family, all the multi-byte * methods delegated to a wide-char implementation. * In the Windows 9x family, most wide-char methods delegated * to a multi-byte implementation. * * In practice, most Microsoft Windows executables were either * wide-char or multi-byte centric. However, they did not * have to be exclusively so. An application built with * _UNICODE, could still call multi-byte API functions, * they would just need to explicitly call CreateProcessA * instead of using the facade macro. An executable could * also use both a multi-byte centric and wide-char centric * DLL's since all the calls eventually hit the same * underlying implementation be it a wide-char on in * Windows NT or multi-char in Windows 9x. * * The use of log4cxx/helpers/tchar.h in log4cxx 0.9.7 was * undesirable because it made log4cxx either exclusively * wide-char or exclusively multi-byte and had to be consistant * with the character model of the calling executable. * This would make it extremely difficult to use * log4cxx when DLL's with different character models * where called by the same application. Since log4cxx * was C++, not C, function overloading could be * used instead of the CreateProcess et al macros * used in the Windows headers. * * In the rework before the 0.9.8, the following changes * were made to log4cxx: * * 1. All inclusions of log4cxx/helpers/tchar.h * and use of TCHAR, log4cxx::String and _T * were removed from log4cxx. * 2. log4cxx/logstring.h was added to define the * implementation character model using the log4cxx::logchar * and log4cxx::LogString typedefs and LOG4CXX_STR macro. * 3. Methods commonly used by calling applications were defined * in both wide-char and multi-byte and both pointer and string * forms with conversion to the implementation character * model delayed as long as possible. * 4. Use of Standard Template Library streams within * log4cxx was substantially reduced (but not totally * elminated). * 5. The LOG4CXX_DEBUG and similar macros were simplified * and now only take arguments that evaluate to * character pointers or strings and no longer take * the right hand side of an insertion operation: * * // This used to work, but no longer * LOG4CXX_DEBUG(logger, "foo" << i); * * If you extensively used this idiom, please consider * migrating to stream-like API defined in log4cxx/stream.h. * * 6. The LOG4CXX_DEBUG and similar use the LOG4CXX_LOCATION * macro to define the log statement location instead of * using __FILE__ and __LINE__. Logger::debug and * similar now take const LocationInfo& instead of * separate const char* and int arguments. This allows * class and method names to appear in location info. * 7. log4cxx include files no longer include config.h * or related files. config.h and related files * may be used by log4cxx implementation, but have * no effect on the exposed API. * * It is expected that the default implementation character * model will be wchar_t. However this may vary by platform * and may be changed based on feedback. * * Developers using log4cxx should seldom be concerned * with the internal character model of log4cxx unless * writing custom appenders or layouts. An application * should not be using log4cxx::logchar, log4cxx::LogString * or LOG4CXX_STR unless dealing with something that is * clearly a log4cxx internal. If you find something * defined as using or returning LogString that you * don't consider a log4cxx internal, please file a * bug report or post a message to one of the mailing lists. * * wchar_t literals should be preferred in log requests since * since they eliminate potential encoding confusion * when the development and deployment encodings are different. * * Migration strategies: * * If you followed the examples in the previous log4cxx versions, * you may have _T() macros littered through your code * and inclusions of this file. If you are on the Microsoft * platform, the simplest solution is to just include * the Platform SDK's tchar.h which would result your log * statements matching the character model of your application. * * If you targetting another platform and your only use of * _T() in related to log4cxx, then I would recommend replacing * all _T() with another macro (say MYAPP_LOGSTR()) * and defining that macro in a commonly included header file * or defining _T() in a commonly included header file. * * I would first try defining these macros as * * #define _T(str) L ## str * * If that results in too many compilation errors, then try: * * #define _T(str) str * * Using the first form will result in wchar_t literals which * will avoid potential encoding confusion and is expected * to result in slightly better performance when logging. * * Since the best choice for _T() depends on the application, * there is not a definition within log4cxx. * * Use encoding conversion macros A2T, W2T, et al should * not longer be necessary. If you are doing a lot of * work converting between encodings, you might consider * using the stream-like interface in log4cxx/stream.h * which defines insertion operators for multi-byte * strings in addition to exposing all the * insertion operations defined for * std::basic_ostream. * */ #endif //_LOG4CXX_HELPERS_TCHAR_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/charsetencoder.h0000644000175100001770000000673214721727031025236 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_CHARSETENCODER_H #define _LOG4CXX_HELPERS_CHARSETENCODER_H #include #include namespace LOG4CXX_NS { namespace helpers { class ByteBuffer; class CharsetEncoder; LOG4CXX_PTR_DEF(CharsetEncoder); /** * An engine to transform LogStrings into bytes * for the specific character set. */ class LOG4CXX_EXPORT CharsetEncoder : public Object { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(CharsetEncoder) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(CharsetEncoder) END_LOG4CXX_CAST_MAP() protected: /** * Protected constructor. */ CharsetEncoder(); public: /** * Destructor. */ virtual ~CharsetEncoder(); /** * Get encoder for default charset. */ static CharsetEncoderPtr getDefaultEncoder(); /** * Get encoder for specified character set. * @param charset the following values should be recognized: * "US-ASCII", "ISO-8859-1", "UTF-8", * "UTF-16BE", "UTF-16LE". * @return encoder. * @throws IllegalArgumentException if encoding is not recognized. */ static CharsetEncoderPtr getEncoder(const LogString& charset); /** * Get encoder for UTF-8. */ static CharsetEncoderPtr getUTF8Encoder(); /** * Encodes a string replacing unmappable * characters with escape sequences. * */ static void encode(CharsetEncoderPtr& enc, const LogString& src, LogString::const_iterator& iter, ByteBuffer& dst); /** * Encodes as many characters from the input string as possible * to the output buffer. * @param in input string * @param iter position in string to start. * @param out output buffer. * @return APR_SUCCESS unless a character can not be represented in * the encoding. */ virtual log4cxx_status_t encode(const LogString& in, LogString::const_iterator& iter, ByteBuffer& out) = 0; /** * Resets any internal state. */ virtual void reset(); /** * Flushes the encoder. */ virtual void flush(ByteBuffer& out); /** * Determines if the return value from encode indicates * an unconvertable character. */ inline static bool isError(log4cxx_status_t stat) { return (stat != 0); } /** * Is the data of \c src unchanged by \c enc. * */ static bool isTriviallyCopyable(const LogString& src, const CharsetEncoderPtr& enc); private: /** * Private copy constructor. */ CharsetEncoder(const CharsetEncoder&); /** * Private assignment operator. */ CharsetEncoder& operator=(const CharsetEncoder&); static CharsetEncoder* createDefaultEncoder(); }; } // namespace helpers } //namespace log4cxx #endif //_LOG4CXX_HELPERS_CHARSETENCODER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/classregistration.h0000644000175100001770000000247014721727031026000 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_CLASSREGISTRATION_H #define _LOG4CXX_HELPERS_CLASSREGISTRATION_H #include namespace LOG4CXX_NS { namespace helpers { class Class; class LOG4CXX_EXPORT ClassRegistration { public: typedef const Class& (*ClassAccessor)(); ClassRegistration(ClassAccessor classAccessor); private: ClassRegistration(const ClassRegistration&); ClassRegistration& operator=(const ClassRegistration&); }; } // namespace log4cxx } // namespace helper #endif //_LOG4CXX_HELPERS_CLASSREGISTRATION_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/charsetdecoder.h0000644000175100001770000000572714721727031025227 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_CHARSETDECODER_H #define _LOG4CXX_HELPERS_CHARSETDECODER_H #include namespace LOG4CXX_NS { namespace helpers { class CharsetDecoder; LOG4CXX_PTR_DEF(CharsetDecoder); class ByteBuffer; /** * An abstract engine to transform a sequences of bytes in a specific charset * into a LogString. */ class LOG4CXX_EXPORT CharsetDecoder : public Object { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(CharsetDecoder) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(CharsetDecoder) END_LOG4CXX_CAST_MAP() protected: /** * Protected constructor. */ CharsetDecoder(); public: /** * Destructor. */ virtual ~CharsetDecoder(); /** * Get decoder for default charset. */ static CharsetDecoderPtr getDefaultDecoder(); /** * Get decoder for specified character set. * @param charset the following values should be recognized: * "US-ASCII", "ISO-8859-1", "UTF-8", * "UTF-16BE", "UTF-16LE". * @return decoder * @throws IllegalArgumentException if charset is not recognized. */ static CharsetDecoderPtr getDecoder(const LogString& charset); /** * Get decoder for UTF-8. */ static CharsetDecoderPtr getUTF8Decoder(); /** * Get decoder for ISO-8859-1. */ static CharsetDecoderPtr getISOLatinDecoder(); /** * Decodes as many bytes as possible from the given * input buffer, writing the results to the given output string. * @param in input buffer. * @param out output string. * @return APR_SUCCESS if not encoding errors were found. */ virtual log4cxx_status_t decode(ByteBuffer& in, LogString& out) = 0; /** * Determins if status value indicates an invalid byte sequence. */ inline static bool isError(log4cxx_status_t stat) { return (stat != 0); } private: /** * Private copy constructor. */ CharsetDecoder(const CharsetDecoder&); /** * Private assignment operator. */ CharsetDecoder& operator=(const CharsetDecoder&); /** * Creates a new decoder for the default charset. */ static CharsetDecoder* createDefaultDecoder(); }; } // namespace helpers } //namespace log4cxx #endif //_LOG4CXX_HELPERS_CHARSETENCODER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/datagrampacket.h0000644000175100001770000000723314721727031025212 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_DATAGRAM_PACKET #define _LOG4CXX_HELPERS_DATAGRAM_PACKET #include #include namespace LOG4CXX_NS { namespace helpers { /** This class represents a datagram packet.

Datagram packets are used to implement a connectionless packet delivery service. Each message is routed from one machine to another based solely on information contained within that packet. Multiple packets sent from one machine to another might be routed differently, and might arrive in any order. */ class LOG4CXX_EXPORT DatagramPacket : public helpers::Object { private: LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(DatagramPacketPriv, m_priv) public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(DatagramPacket) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(DatagramPacket) END_LOG4CXX_CAST_MAP() /** Constructs a DatagramPacket for receiving packets of length length. */ DatagramPacket(void* buf, int length); /** Constructs a datagram packet for sending packets of length length to the specified port number on the specified host. */ DatagramPacket(void* buf, int length, InetAddressPtr address, int port); /** Constructs a DatagramPacket for receiving packets of length length, specifying an offset into the buffer. */ DatagramPacket(void* buf, int offset, int length); /** Constructs a datagram packet for sending packets of length length with offset offset to the specified port number on the specified host. */ DatagramPacket(void* buf, int offset, int length, InetAddressPtr address, int port); ~DatagramPacket(); /** Returns the IP address of the machine to which this datagram is being sent or from which the datagram was received. */ InetAddressPtr getAddress() const; /** Returns the data received or the data to be sent. */ void* getData() const; /** Returns the length of the data to be sent or the length of the data received. */ int getLength() const; /** Returns the offset of the data to be sent or the offset of the data received. */ int getOffset() const; /** Returns the port number on the remote host to which this datagram is being sent or from which the datagram was received. */ int getPort() const; void setAddress(InetAddressPtr address1); /** Set the data buffer for this packet. */ void setData(void* buf1); /** Set the data buffer for this packet. */ void setData(void* buf1, int offset1, int length1); /** Set the length for this packet. */ void setLength(int length1); void setPort(int port1); private: // // prevent copy and assignment statements DatagramPacket(const DatagramPacket&); DatagramPacket& operator=(const DatagramPacket&); }; // class DatagramPacket LOG4CXX_PTR_DEF(DatagramPacket); } // namespace helpers } // namespace log4cxx #endif // _LOG4CXX_HELPERS_DATAGRAM_PACKET apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/integer.h0000644000175100001770000000242214721727031023672 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_INTEGER_H #define _LOG4CXX_HELPERS_INTEGER_H #include namespace LOG4CXX_NS { namespace helpers { class LOG4CXX_EXPORT Integer : public Object { const int val; public: DECLARE_LOG4CXX_OBJECT(Integer) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(Integer) END_LOG4CXX_CAST_MAP() Integer(); Integer(int i); virtual ~Integer(); inline int intValue() const { return val; } }; LOG4CXX_PTR_DEF(Integer); } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/datagramsocket.h0000644000175100001770000000665414721727031025241 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_DATAGRAM_SOCKET_H #define _LOG4CXX_HELPERS_DATAGRAM_SOCKET_H #include #include #include #include namespace LOG4CXX_NS { namespace helpers { class DatagramSocket; LOG4CXX_PTR_DEF(DatagramSocket); LOG4CXX_UNIQUE_PTR_DEF(DatagramSocket); /** This class represents a socket for sending and receiving datagram packets.*/ class LOG4CXX_EXPORT DatagramSocket : public helpers::Object { protected: LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(DatagramSocketPriv, m_priv) DatagramSocket(LOG4CXX_PRIVATE_PTR(DatagramSocketPriv) priv); public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(DatagramSocket) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(DatagramSocket) END_LOG4CXX_CAST_MAP() /** ensure the socket is closed. */ virtual ~DatagramSocket(); /** Binds a datagram socket to a local port and address.*/ virtual void bind(int lport, InetAddressPtr laddress) = 0; /** Closes this datagram socket */ virtual void close(); /** Connects the socket to a remote address for this socket. */ virtual void connect(InetAddressPtr address, int port) = 0; /** Returns the address to which this socket is connected. */ InetAddressPtr getInetAddress() const; /** Gets the local address to which the socket is bound. */ InetAddressPtr getLocalAddress() const; /** Returns the port number on the local host to which this socket is bound. */ int getLocalPort() const; /** Returns the port for this socket */ int getPort() const; /** Returns the binding state of the socket. **/ bool isBound() const; /** Returns wether the socket is closed or not. */ virtual bool isClosed() const = 0; /** Returns the connection state of the socket. */ bool isConnected() const; /** Receives a datagram packet from this socket. */ virtual void receive(DatagramPacketPtr& p) = 0; /** Sends a datagram packet from this socket. */ virtual void send(DatagramPacketPtr& p) = 0; /** Constructs a datagram socket and binds it to any available port on the local host machine.*/ static DatagramSocketUniquePtr create(); /** Constructs a datagram socket and binds it to the specified port on the local host machine. */ static DatagramSocketUniquePtr create(int port); /** Creates a datagram socket, bound to the specified local address. */ static DatagramSocketUniquePtr create(int port, InetAddressPtr laddr); private: DatagramSocket(const DatagramSocket&); DatagramSocket& operator=(const DatagramSocket&); }; } // namespace helpers } // namespace log4cxx #endif //_LOG4CXX_HELPERS_DATAGRAM_SOCKET_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/cyclicbuffer.h0000644000175100001770000000512714721727031024702 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_CYCLICBUFFER_H #define _LOG4CXX_HELPERS_CYCLICBUFFER_H #include #include namespace LOG4CXX_NS { namespace helpers { /** CyclicBuffer is used by other appenders to hold instances of {@link log4cxx::spi::LoggingEvent LoggingEvent} for immediate or deferred display.

This buffer gives read access to any element in the buffer not just the first or last element. */ class LOG4CXX_EXPORT CyclicBuffer { private: LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(CyclicBufferPriv, m_priv) public: /** Instantiate a new CyclicBuffer of at most maxSize events. The maxSize argument must a positive integer. @param maxSize The maximum number of elements in the buffer. @throws IllegalArgumentException if maxSize is negative. */ CyclicBuffer(int maxSize); ~CyclicBuffer(); /** Add an event as the last event in the buffer. */ void add(const spi::LoggingEventPtr& event); /** Get the ith oldest event currently in the buffer. If i is outside the range 0 to the number of elements currently in the buffer, then null is returned. */ spi::LoggingEventPtr get(int i); int getMaxSize() const; /** Get the oldest (first) element in the buffer. The oldest element is removed from the buffer. */ spi::LoggingEventPtr get(); /** Get the number of elements in the buffer. This number is guaranteed to be in the range 0 to maxSize (inclusive). */ int length() const; /** Resize the cyclic buffer to newSize. @throws IllegalArgumentException if newSize is negative. */ void resize(int newSize); }; // class CyclicBuffer } //namespace helpers } //namespace log4cxx #endif //_LOG4CXX_HELPERS_CYCLICBUFFER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/strictmath.h0000644000175100001770000000263714721727031024427 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_STRICTMATH_H #define _LOG4CXX_HELPERS_STRICTMATH_H #include namespace LOG4CXX_NS { namespace helpers { /** The class StrictMath contains methods for performing basic numeric operations */ class StrictMath { public: template static inline const _type& minimum(const _type& a, const _type& b) { return (a < b) ? a : b; } template static inline const _type& maximum(const _type& a, const _type& b) { return (a > b) ? a : b; } }; // class StrictMath } // namespace helpers } // namespace log4cx #endif //_LOG4CXX_HELPERS_STRICTMATH_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/serversocket.h0000644000175100001770000000340114721727031024752 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_SERVER_SOCKET_H #define _LOG4CXX_HELPERS_SERVER_SOCKET_H #include #include namespace LOG4CXX_NS { namespace helpers { class ServerSocket; LOG4CXX_PTR_DEF(ServerSocket); LOG4CXX_UNIQUE_PTR_DEF(ServerSocket); class LOG4CXX_EXPORT ServerSocket { protected: LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(ServerSocketPrivate, m_priv) ServerSocket(LOG4CXX_PRIVATE_PTR(ServerSocketPrivate) priv); public: virtual ~ServerSocket(); /** Listens for a connection to be made to this socket and accepts it */ virtual SocketPtr accept() = 0; /** Closes this socket. */ virtual void close(); /** Retrive setting for SO_TIMEOUT. */ int getSoTimeout() const; /** Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. */ void setSoTimeout(int timeout); static ServerSocketUniquePtr create(int port); }; } // namespace helpers } // namespace log4cxx #endif //_LOG4CXX_HELPERS_SERVER_SOCKET_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/pool.h0000644000175100001770000000306414721727031023211 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_POOL_H #define _LOG4CXX_HELPERS_POOL_H #include #include extern "C" { struct apr_pool_t; } namespace LOG4CXX_NS { namespace helpers { class LOG4CXX_EXPORT Pool { public: Pool(); Pool(apr_pool_t* pool, bool release); ~Pool(); apr_pool_t* getAPRPool(); apr_pool_t* create(); void* palloc(size_t length); char* pstralloc(size_t length); char* itoa(int n); char* pstrndup(const char* s, size_t len); char* pstrdup(const char* s); char* pstrdup(const std::string&); protected: apr_pool_t* pool; const bool release; private: Pool(const LOG4CXX_NS::helpers::Pool&); Pool& operator=(const Pool&); void setPool(); }; } // namespace helpers } // namespace log4cxx #endif //_LOG4CXX_HELPERS_POOL_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/object.h0000644000175100001770000001317014721727031023505 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_OBJECT_H #define _LOG4CXX_HELPERS_OBJECT_H #include #include #include #include #define DECLARE_LOG4CXX_CLAZZ_OBJECT(object)\ public:\ class Clazz##object : public helpers::Class\ {\ public:\ Clazz##object() : helpers::Class() {}\ virtual ~Clazz##object() {}\ virtual LOG4CXX_NS::LogString getName() const { return LOG4CXX_STR(#object); } \ };\ static const helpers::Class& getStaticClass(); \ static const LOG4CXX_NS::helpers::ClassRegistration& registerClass(); #define DECLARE_ABSTRACT_LOG4CXX_OBJECT(object)\ DECLARE_LOG4CXX_CLAZZ_OBJECT(object)\ const helpers::Class& getClass() const override; #define DECLARE_LOG4CXX_OBJECT(object)\ public:\ class Clazz##object : public helpers::Class\ {\ public:\ Clazz##object() : helpers::Class() {}\ virtual ~Clazz##object() {}\ virtual LOG4CXX_NS::LogString getName() const { return LOG4CXX_STR(#object); } \ virtual object* newInstance() const\ {\ return new object();\ }\ };\ const helpers::Class& getClass() const override;\ static const helpers::Class& getStaticClass(); \ static const LOG4CXX_NS::helpers::ClassRegistration& registerClass(); #define DECLARE_LOG4CXX_OBJECT_WITH_CUSTOM_CLASS(object, class)\ public:\ const helpers::Class& getClass() const override;\ static const helpers::Class& getStaticClass();\ static const LOG4CXX_NS::helpers::ClassRegistration& registerClass(); #define IMPLEMENT_LOG4CXX_OBJECT(object)\ const ::LOG4CXX_NS::helpers::Class& object::getClass() const { return getStaticClass(); }\ const ::LOG4CXX_NS::helpers::Class& object::getStaticClass() { \ static ::LOG4CXX_NS::helpers::WideLife theClass; \ return theClass; \ } \ const LOG4CXX_NS::helpers::ClassRegistration& object::registerClass() { \ static ::LOG4CXX_NS::helpers::WideLife<::LOG4CXX_NS::helpers::ClassRegistration> classReg(object::getStaticClass); \ return classReg; \ }\ namespace LOG4CXX_NS { namespace classes { \ const ::LOG4CXX_NS::helpers::ClassRegistration& object##Registration = object::registerClass(); \ } } #define IMPLEMENT_LOG4CXX_OBJECT_WITH_CUSTOM_CLASS(object, class)\ const LOG4CXX_NS::helpers::Class& object::getClass() const { return getStaticClass(); }\ const LOG4CXX_NS::helpers::Class& object::getStaticClass() { \ static LOG4CXX_NS::helpers::WideLife theClass; \ return theClass; \ } \ const LOG4CXX_NS::helpers::ClassRegistration& object::registerClass() { \ static LOG4CXX_NS::helpers::WideLife classReg(object::getStaticClass); \ return classReg; \ }\ namespace LOG4CXX_NS { namespace classes { \ const LOG4CXX_NS::helpers::ClassRegistration& object##Registration = object::registerClass(); \ } } namespace LOG4CXX_NS { class AppenderSkeleton; class Logger; namespace helpers { class Pool; /** base class for java-like objects.*/ class LOG4CXX_EXPORT Object { public: virtual ~Object() {} virtual const helpers::Class& getClass() const = 0; virtual bool instanceof(const Class& clazz) const = 0; virtual const void* cast(const Class& clazz) const = 0; DECLARE_LOG4CXX_CLAZZ_OBJECT(Object) }; LOG4CXX_PTR_DEF(Object); } /** * Attempt to cast one Object to another kind of Object. * * On success, returns a new shared pointer that points at incoming. * On failure, returns an invalid shared pointer. */ template::value, bool = std::is_base_of::value> std::shared_ptr cast(const std::shared_ptr& incoming) { if(!incoming) { return std::shared_ptr(); } Ret* casted = reinterpret_cast(const_cast(incoming->cast(Ret::getStaticClass()))); if ( casted ) { return std::shared_ptr( incoming, casted ); } return std::shared_ptr(); } } #define BEGIN_LOG4CXX_CAST_MAP()\ const void * cast(const helpers::Class& clazz) const override\ {\ const void * object = 0;\ if (&clazz == &helpers::Object::getStaticClass()) return (const helpers::Object *)this; #define END_LOG4CXX_CAST_MAP()\ return object;\ }\ bool instanceof(const helpers::Class& clazz) const override\ { return cast(clazz) != 0; } #define LOG4CXX_CAST_ENTRY(Interface)\ if (&clazz == &Interface::getStaticClass()) return (const Interface *)this; #define LOG4CXX_CAST_ENTRY2(Interface, interface2)\ if (&clazz == &Interface::getStaticClass()) return (Interface *)(interface2 *)this; #define LOG4CXX_CAST_ENTRY_CHAIN(Interface)\ object = Interface::cast(clazz);\ if (object != 0) return object; #endif //_LOG4CXX_HELPERS_OBJECT_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/strftimedateformat.h0000644000175100001770000000335014721727031026142 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_STRFTIME_DATE_FORMAT_H #define _LOG4CXX_HELPERS_STRFTIME_DATE_FORMAT_H #include namespace LOG4CXX_NS { namespace helpers { /** Concrete class for formatting and parsing dates in a locale-sensitive manner. */ class LOG4CXX_EXPORT StrftimeDateFormat : public DateFormat { public: /** Constructs a DateFormat using the given pattern and the default time zone. @param pattern the pattern describing the date and time format */ StrftimeDateFormat(const LogString& pattern); ~StrftimeDateFormat(); virtual void format(LogString& s, log4cxx_time_t tm, LOG4CXX_NS::helpers::Pool& p) const; /** * Set time zone. * @param zone new time zone. */ void setTimeZone(const TimeZonePtr& zone); private: LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(StrftimeDateFormatPrivate, m_priv) }; } // namespace helpers } // namespace log4cxx #endif // _LOG4CXX_HELPERS_STRFTIME_DATE_FORMAT_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/loglog.h0000644000175100001770000000653514721727031023531 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_LOG_LOG_H #define _LOG4CXX_HELPERS_LOG_LOG_H #include #include #include #include namespace LOG4CXX_NS { namespace helpers { /** This class used to output log statements from within the log4cxx package.

Log4cxx components cannot make log4cxx logging calls. However, it is sometimes useful for the user to learn about what log4cxx is doing. You can enable log4cxx internal debug logging by calling the #setInternalDebugging method.

All LogLog messages are written to SystemErrWriter prepended with the string "log4cxx: ". */ class LOG4CXX_EXPORT LogLog { private: LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(LogLogPrivate, m_priv) friend WideLife; LogLog(); LogLog(const LogLog&); LogLog& operator=(const LogLog&); static LogLog& getInstance(); public: ~LogLog(); /** * Is internal debugging enabled? **/ static bool isDebugEnabled(); /** Use the value of \c enabled as the new internal debug logging state. */ static void setInternalDebugging(bool enabled); /** Output \c msg to SystemErrWriter if internal debug logging is enabled. */ static void debug(const LogString& msg); /** Output \c msg and ex.what() to SystemErrWriter if internal debug logging is enabled. */ static void debug(const LogString& msg, const std::exception& e); /** Output \c msg to SystemErrWriter unconditionally. */ static void error(const LogString& msg); /** Output \c msg and ex.what() to SystemErrWriter unconditionally. */ static void error(const LogString& msg, const std::exception& ex); /** Change quiet mode to \c newValue. In quiet mode LogLog generates strictly no output, not even for errors. @param newValue true for no output. */ static void setQuietMode(bool newValue); /** Output \c msg to SystemErrWriter unconditionally. */ static void warn(const LogString& msg); /** Output \c msg and ex.what() to SystemErrWriter unconditionally. */ static void warn(const LogString& msg, const std::exception& ex); private: static void emit(const LogString& msg); static void emit(const std::exception& ex); }; } // namespace helpers } // namespace log4cxx #define LOGLOG_DEBUG(log) { \ if (LogLog::isDebugEnabled()) \ LOG4CXX_NS::helpers::LogLog::debug(log) ; } #define LOGLOG_WARN(log) { \ LOG4CXX_NS::helpers::LogLog::warn(log) ; } #define LOGLOG_ERROR(log) { \ LOG4CXX_NS::helpers::LogLog::warn(log); } #endif //_LOG4CXX_HELPERS_LOG_LOG_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/properties.h0000644000175100001770000001421514721727031024434 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPER_PROPERTIES_H #define _LOG4CXX_HELPER_PROPERTIES_H #include #include #include #include #include #include namespace LOG4CXX_NS { namespace helpers { class LOG4CXX_EXPORT Properties { private: typedef std::map PropertyMap; PropertyMap* properties; Properties(const Properties&); Properties& operator=(const Properties&); public: /** * Create new instance. */ Properties(); /** * Destructor. */ ~Properties(); /** Reads a property list (key and element pairs) from the input stream. The stream is assumed to be using the ISO 8859-1 character encoding.

Every property occupies one line of the input stream. Each line is terminated by a line terminator (\\n or \\r or \\r\\n). Lines from the input stream are processed until end of file is reached on the input stream.

A line that contains only whitespace or whose first non-whitespace character is an ASCII # or ! is ignored (thus, # or ! indicate comment lines).

Every line other than a blank line or a comment line describes one property to be added to the table (except that if a line ends with \, then the following line, if it exists, is treated as a continuation line, as described below). The key consists of all the characters in the line starting with the first non-whitespace character and up to, but not including, the first ASCII =, :, or whitespace character. All of the key termination characters may be included in the key by preceding them with a \\. Any whitespace after the key is skipped; if the first non-whitespace character after the key is = or :, then it is ignored and any whitespace characters after it are also skipped. All remaining characters on the line become part of the associated element string. Within the element string, the ASCII escape sequences \\t, \\n, \\r, \\ , \\\", \\', \\ (a backslash and a space), and \\uxxxx are recognized and converted to single characters. Moreover, if the last character on the line is \\, then the next line is treated as a continuation of the current line; the \\ and line terminator are simply discarded, and any leading whitespace characters on the continuation line are also discarded and are not part of the element string.

As an example, each of the following four lines specifies the key "Truth" and the associated element value "Beauty":

		Truth = Beauty
		Truth:Beauty
		Truth         :Beauty
		
As another example, the following three lines specify a single property:
		fruits           apple, banana, pear, \
		          cantaloupe, watermelon, \
		          kiwi, mango
		
The key is "fruits" and the associated element is:
		"apple, banana, pear, cantaloupe, watermelon, kiwi, mango"
		
Note that a space appears before each \ so that a space will appear after each comma in the final result; the \, line terminator, and leading whitespace on the continuation line are merely discarded and are not replaced by one or more other characters.

As a third example, the line:

		cheeses
		
specifies that the key is "cheeses" and the associated element is the empty string. @param inStream the input stream. @throw IOException if an error occurred when reading from the input stream. */ void load(InputStreamPtr inStream); /** * Calls Properties::put. * @param key the key to be placed into this property list. * @param value the value corresponding to key. * @return the previous value of the specified key in this * property list, or an empty string if it did not have one. */ LogString setProperty(const LogString& key, const LogString& value); /** * Puts a property value into the collection. * @param key the key to be placed into this property list. * @param value the value corresponding to key. * @return the previous value of the specified key in this * property list, or an empty string if it did not have one. */ LogString put(const LogString& key, const LogString& value); /** * Calls Properties::get. * @param key the property key. * @return the value in this property list with the specified * key value or empty string. */ LogString getProperty(const LogString& key) const; /** * Gets a property value. * @param key the property key. * @return the value in this property list with the specified * key value or empty string. */ LogString get(const LogString& key) const; /** Returns an enumeration of all the keys in this property list, including distinct keys in the default property list if a key of the same name has not already been found from the main properties list. @return an array of all the keys in this property list, including the keys in the default property list. */ std::vector propertyNames() const; }; // class Properties } // namespace helpers } // namespace log4cxx #endif //_LOG4CXX_HELPER_PROPERTIES_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/fileinputstream.h0000644000175100001770000000531414721727031025453 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_FILEINPUTSTREAM_H #define _LOG4CXX_HELPERS_FILEINPUTSTREAM_H #include #include #include #include namespace LOG4CXX_NS { namespace helpers { /** * InputStream implemented on top of APR file IO. * */ class LOG4CXX_EXPORT FileInputStream : public InputStream { private: LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(FileInputStreamPrivate, m_priv) public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(FileInputStream) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(FileInputStream) LOG4CXX_CAST_ENTRY_CHAIN(InputStream) END_LOG4CXX_CAST_MAP() /** * Creates a FileInputStream by opening a connection to an actual * file, the file named by the path name name in the file system. * * @param filename The system-dependent file name. */ FileInputStream(const LogString& filename); FileInputStream(const logchar* filename); /** * Creates a FileInputStream by opening a connection to an actual * file, the file named by the File object file in the file system. * * @param aFile The file to be opened for reading. */ FileInputStream(const File& aFile); virtual ~FileInputStream(); /** * Closes this file input stream and releases any system * resources associated with the stream. */ void close() override; /** * Reads a sequence of bytes into the given buffer. * * @param buf The buffer into which bytes are to be transferred. * @return the total number of bytes read into the buffer, or -1 if there * is no more data because the end of the stream has been reached. */ int read(ByteBuffer& buf) override; private: FileInputStream(const FileInputStream&); FileInputStream& operator=(const FileInputStream&); void open(const LogString&); }; LOG4CXX_PTR_DEF(FileInputStream); } // namespace helpers } //namespace log4cxx #endif //_LOG4CXX_HELPERS_FILEINPUTSTREAM_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/system.h0000644000175100001770000000304414721727031023562 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_SYSTEM_H #define _LOG4CXX_HELPERS_SYSTEM_H #include #include namespace LOG4CXX_NS { namespace helpers { class Properties; /** The System class contains several useful class fields and methods. It cannot be instantiated. */ class LOG4CXX_EXPORT System { public: /** Gets the system property indicated by the specified key. @param key the name of the system property. @return the string value of the system property, or the default value if there is no property with that key. @throws IllegalArgumentException if key is empty. */ static LogString getProperty(const LogString& key); }; } // namespace helpers } // namespace log4cxx #endif //_LOG4CXX_HELPERS_SYSTEM_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/bytearrayinputstream.h0000644000175100001770000000452614721727031026542 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_BYTEARRAYINPUTSTREAM_H #define _LOG4CXX_HELPERS_BYTEARRAYINPUTSTREAM_H #include #include namespace LOG4CXX_NS { namespace helpers { LOG4CXX_LIST_DEF(ByteList, unsigned char); /** * InputStream implemented on top of a byte array. */ class LOG4CXX_EXPORT ByteArrayInputStream : public InputStream { private: LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(ByteArrayInputStreamPriv, m_priv) public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(ByteArrayInputStream) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(ByteArrayInputStream) LOG4CXX_CAST_ENTRY_CHAIN(InputStream) END_LOG4CXX_CAST_MAP() /** * Creates a ByteArrayInputStream. * * @param bytes array of bytes to copy into stream. */ ByteArrayInputStream(const ByteList& bytes); virtual ~ByteArrayInputStream(); /** * Closes this file input stream and releases any system * resources associated with the stream. */ void close() override; /** * Reads a sequence of bytes into the given buffer. * * @param buf The buffer into which bytes are to be transferred. * @return the total number of bytes read into the buffer, or -1 if there * is no more data because the end of the stream has been reached. */ int read(ByteBuffer& buf) override; private: ByteArrayInputStream(const ByteArrayInputStream&); ByteArrayInputStream& operator=(const ByteArrayInputStream&); }; LOG4CXX_PTR_DEF(ByteArrayInputStream); } // namespace helpers } //namespace log4cxx #endif //_LOG4CXX_HELPERS_BYTEARRAYINPUTSTREAM_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/inputstream.h0000644000175100001770000000371014721727031024611 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_INPUTSTREAM_H #define _LOG4CXX_HELPERS_INPUTSTREAM_H #include namespace LOG4CXX_NS { namespace helpers { class ByteBuffer; /** * Abstract class for reading from character streams. * */ class LOG4CXX_EXPORT InputStream : public Object { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(InputStream) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(InputStream) END_LOG4CXX_CAST_MAP() protected: InputStream(); virtual ~InputStream(); public: /** * Reads a sequence of bytes into the given buffer. * * @param dst The buffer into which bytes are to be transferred. * @return the total number of bytes read into the buffer, or -1 if there * is no more data because the end of the stream has been reached. */ virtual int read(ByteBuffer& dst) = 0; /** * Closes this input stream and releases any system * resources associated with the stream. */ virtual void close() = 0; private: InputStream(const InputStream&); InputStream& operator=(const InputStream&); }; LOG4CXX_PTR_DEF(InputStream); } // namespace helpers } //namespace log4cxx #endif //_LOG4CXX_HELPERS_INPUTSTREAM_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/reader.h0000644000175100001770000000340114721727031023475 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_READER_H #define _LOG4CXX_HELPERS_READER_H #include namespace LOG4CXX_NS { namespace helpers { /** * Abstract class for reading from character streams. * */ class LOG4CXX_EXPORT Reader : public Object { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(Reader) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(Reader) END_LOG4CXX_CAST_MAP() protected: /** * Creates a new character-stream reader. */ Reader(); virtual ~Reader(); public: /** * Closes the stream. * @param p The memory pool associated with the reader. */ virtual void close(Pool& p) = 0; /** * @return The complete stream contents as a LogString. * @param p The memory pool associated with the reader. */ virtual LogString read(Pool& p) = 0; private: Reader(const Reader&); Reader& operator=(const Reader&); }; LOG4CXX_PTR_DEF(Reader); } // namespace helpers } //namespace log4cxx #endif //_LOG4CXX_HELPERS_READER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/socketoutputstream.h0000644000175100001770000000361314721727031026225 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_SOCKET_OUTPUT_STREAM_H #define _LOG4CXX_HELPERS_SOCKET_OUTPUT_STREAM_H #include #include #include namespace LOG4CXX_NS { namespace helpers { LOG4CXX_LIST_DEF(ByteList, unsigned char); class LOG4CXX_EXPORT SocketOutputStream : public OutputStream { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(SocketOutputStream) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(SocketOutputStream) LOG4CXX_CAST_ENTRY_CHAIN(OutputStream) END_LOG4CXX_CAST_MAP() SocketOutputStream(const SocketPtr& socket); ~SocketOutputStream(); void close(Pool& p) override; void flush(Pool& p) override; void write(ByteBuffer& buf, Pool& p) override; private: LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(SocketOutputStreamPrivate, m_priv) // // prevent copy and assignment statements SocketOutputStream(const SocketOutputStream&); SocketOutputStream& operator=(const SocketOutputStream&); }; LOG4CXX_PTR_DEF(SocketOutputStream); } // namespace helpers } // namespace log4cxx #endif // _LOG4CXX_HELPERS_SOCKET_OUTPUT_STREAM_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/stringtokenizer.h0000644000175100001770000000301014721727031025470 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_STRING_TOKENIZER_H #define _LOG4CXX_HELPERS_STRING_TOKENIZER_H #include #include namespace LOG4CXX_NS { namespace helpers { class LOG4CXX_EXPORT StringTokenizer { public: StringTokenizer(const LogString& str, const LogString& delim); ~StringTokenizer(); bool hasMoreTokens() const; LogString nextToken(); private: // prevent copy and assignment statements StringTokenizer(const StringTokenizer&); StringTokenizer& operator=(const StringTokenizer&); LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(StringTokenizerPrivate, m_priv) }; // class StringTokenizer } // namespace helpers; } // namespace log4cxx; #endif //_LOG4CXX_HELPERS_STRING_TOKENIZER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/relativetimedateformat.h0000644000175100001770000000273714721727031027007 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_RELATIVE_TIME_DATE_FORMAT_H #define _LOG4CXX_HELPERS_RELATIVE_TIME_DATE_FORMAT_H #include namespace LOG4CXX_NS { namespace helpers { /** Formats a date by printing the number of milliseconds elapsed since the start of the application. This is the fastest printing DateFormat in the package. */ class LOG4CXX_EXPORT RelativeTimeDateFormat : public DateFormat { public: RelativeTimeDateFormat(); virtual void format(LogString& s, log4cxx_time_t tm, LOG4CXX_NS::helpers::Pool& p) const; private: log4cxx_time_t startTime; }; } // namespace helpers } // namespace log4cxx #endif // _LOG4CXX_HELPERS_RELATIVE_TIME_DATE_FORMAT_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/dateformat.h0000644000175100001770000000474114721727031024371 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_DATE_FORMAT_H #define _LOG4CXX_HELPERS_DATE_FORMAT_H #include namespace LOG4CXX_NS { namespace helpers { /** * DateFormat is an abstract class for date/time formatting * patterned after java.text.DateFormat. */ class LOG4CXX_EXPORT DateFormat : public Object { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(DateFormat) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(DateFormat) END_LOG4CXX_CAST_MAP() /** * Destructor */ virtual ~DateFormat(); /** * Formats an log4cxx_time_t into a date/time string. * @param s string to which the date/time string is appended. * @param tm date to be formatted. * @param p memory pool used during formatting. */ virtual void format(LogString& s, log4cxx_time_t tm, LOG4CXX_NS::helpers::Pool& p) const = 0; /** * Sets the time zone. * @param zone the given new time zone. */ virtual void setTimeZone(const TimeZonePtr& zone); /** * Format an integer consistent with the format method. * @param s string to which the numeric string is appended. * @param n integer value. * @param p memory pool used during formatting. * @remarks This method is used by CachedDateFormat to * format the milliseconds. */ virtual void numberFormat(LogString& s, int n, LOG4CXX_NS::helpers::Pool& p) const; protected: /** * Constructor. */ DateFormat(); private: /** * Copy constructor definition to prevent copying. */ DateFormat(const DateFormat&); /** * Assignment definition to prevent assignment. */ DateFormat& operator=(const DateFormat&); }; LOG4CXX_PTR_DEF(DateFormat); } // namespace helpers } // namespace log4cxx #endif //_LOG4CXX_HELPERS_DATE_FORMAT_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/filewatchdog.h0000644000175100001770000000443314721727031024701 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_FILEWATCHDOG_H #define _LOG4CXX_HELPERS_FILEWATCHDOG_H #include #include #include #include #include #include #include namespace LOG4CXX_NS { namespace helpers { /** Check every now and then that a certain file has not changed. If it has, then call the #doOnChange method. */ class LOG4CXX_EXPORT FileWatchdog { public: virtual ~FileWatchdog(); /** The default delay between every file modification check, set to 60 seconds. */ static long DEFAULT_DELAY /*= 60000 ms*/; protected: FileWatchdog(const File& filename); virtual void doOnChange() = 0; void checkAndConfigure(); const File& file(); public: /** Use \c delay as the number of milliseconds to wait between each check for file changes. */ void setDelay(long delay); /** Create a thread that periodically checks for a file change after first calling doOnChange() on the current thread. */ void start(); /** Stop the thread that periodically checks for a file change. */ void stop(); /** Is the thread that periodically checks for a file change running? */ bool is_active(); private: void run(); bool is_interrupted(); FileWatchdog(const FileWatchdog&); FileWatchdog& operator=(const FileWatchdog&); LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(FileWatchdogPrivate, m_priv) }; } // namespace helpers } // namespace log4cxx #endif // _LOG4CXX_HELPERS_FILEWATCHDOG_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/date.h0000644000175100001770000000416714721727031023162 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_DATE_H #define _LOG4CXX_HELPERS_DATE_H #include #include #include namespace LOG4CXX_NS { namespace helpers { /** * Simple transcoder for converting between * external char and wchar_t strings and * internal strings. * */ class LOG4CXX_EXPORT Date : public Object { const log4cxx_time_t time; public: DECLARE_LOG4CXX_OBJECT(Date) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(Date) END_LOG4CXX_CAST_MAP() Date(); Date(log4cxx_time_t time); virtual ~Date(); inline log4cxx_time_t getTime() const { return time; } /** * Get start of next second */ log4cxx_time_t getNextSecond() const; static log4cxx_time_t getMicrosecondsPerDay(); static log4cxx_time_t getMicrosecondsPerSecond(); static log4cxx_time_t getCurrentTimeStd(); static log4cxx_time_t currentTime(); /** * A function that will return the current time(in microseconds) when called */ typedef std::function GetCurrentTimeFn; /** * Set the function that is used to get the current time. * This is used only for testing purposes and should never be called * under normal circumstances. * * @param fn */ static void setGetCurrentTimeFunction(GetCurrentTimeFn fn); }; LOG4CXX_PTR_DEF(Date); } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/outputstreamwriter.h0000644000175100001770000000400214721727031026242 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_OUTPUTSTREAMWRITER_H #define _LOG4CXX_HELPERS_OUTPUTSTREAMWRITER_H #include #include #include namespace LOG4CXX_NS { namespace helpers { /** * Abstract class for writing to character streams. */ class LOG4CXX_EXPORT OutputStreamWriter : public Writer { private: LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(OutputStreamWriterPrivate, m_priv) public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(OutputStreamWriter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(OutputStreamWriter) LOG4CXX_CAST_ENTRY_CHAIN(Writer) END_LOG4CXX_CAST_MAP() OutputStreamWriter(OutputStreamPtr& out); OutputStreamWriter(OutputStreamPtr& out, CharsetEncoderPtr& enc); ~OutputStreamWriter(); void close(Pool& p) override; void flush(Pool& p) override; void write(const LogString& str, Pool& p) override; LogString getEncoding() const; OutputStreamPtr getOutputStreamPtr() const; private: OutputStreamWriter(const OutputStreamWriter&); OutputStreamWriter& operator=(const OutputStreamWriter&); }; LOG4CXX_PTR_DEF(OutputStreamWriter); } // namespace helpers } //namespace log4cxx #endif //_LOG4CXX_HELPERS_OUTPUTSTREAMWRITER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/iso8601dateformat.h0000644000175100001770000000277614721727031025431 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_ISO_8601_DATE_FORMAT_H #define _LOG4CXX_HELPERS_ISO_8601_DATE_FORMAT_H #include namespace LOG4CXX_NS { namespace helpers { /** Formats a date in the format yyyy-MM-dd HH:mm:ss,SSS for example "1999-11-27 15:49:37,459".

Refer to the summary of the International Standard Date and Time Notation for more information on this format. */ class LOG4CXX_EXPORT ISO8601DateFormat : public SimpleDateFormat { public: ISO8601DateFormat() : SimpleDateFormat(LOG4CXX_STR("yyyy-MM-dd HH:mm:ss,SSS")) {} }; } // namespace helpers } // namespace log4cxx #endif // _LOG4CXX_HELPERS_ISO_8601_DATE_FORMAT_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/systemerrwriter.h0000644000175100001770000000326514721727031025535 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_SYSTEMERRWRITER_H #define _LOG4CXX_HELPERS_SYSTEMERRWRITER_H #include namespace LOG4CXX_NS { namespace helpers { /** * Sends output to stderr. */ class LOG4CXX_EXPORT SystemErrWriter : public Writer { public: DECLARE_LOG4CXX_OBJECT(SystemErrWriter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(SystemErrWriter) LOG4CXX_CAST_ENTRY_CHAIN(Writer) END_LOG4CXX_CAST_MAP() SystemErrWriter(); virtual ~SystemErrWriter(); void close(Pool& p) override; void flush(Pool& p) override; void write(const LogString& str, Pool& p) override; static void write(const LogString& str); static void flush(); private: SystemErrWriter(const SystemErrWriter&); SystemErrWriter& operator=(const SystemErrWriter&); static bool isWide(); }; } // namespace helpers } //namespace log4cxx #endif //_LOG4CXX_HELPERS_SYSTEMERRWRITER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/threadspecificdata.h0000644000175100001770000000633314721727031026051 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_THREAD_SPECIFIC_DATA_H #define _LOG4CXX_HELPERS_THREAD_SPECIFIC_DATA_H #include #include namespace LOG4CXX_NS { namespace helpers { /** * This class contains all the thread-specific * data in use by log4cxx. */ class LOG4CXX_EXPORT ThreadSpecificData { public: ThreadSpecificData(); ThreadSpecificData(ThreadSpecificData&& other); ~ThreadSpecificData(); /** * Gets current thread specific data. * @return a pointer that is non-null prior to application exit. */ static ThreadSpecificData* getCurrentData(); /** * Remove current thread data from APR if the diagnostic context is empty. */ void recycle(); /** * Add the \c key \c val pair to the mapped diagnostic context of the current thread */ static void put(const LogString& key, const LogString& val); /** * Add \c val to the nested diagnostic context of the current thread */ static void push(const LogString& val); /** * Use \c stack as the nested diagnostic context of the current thread */ static void inherit(const NDC::Stack& stack); /** * The nested diagnostic context of the current thread */ NDC::Stack& getStack(); /** * The mapped diagnostic context of the current thread */ MDC::Map& getMap(); /** * A character outpur stream only assessable to the current thread */ template static std::basic_ostringstream& getStringStream() { return getStream(T()); } /** * The names assigned to the current thread */ struct NamePair { LogString idString; LogString threadName; }; using NamePairPtr = std::shared_ptr; /** * A reference counted pointer to the names of the current thread. * * String references will remain valid * for the lifetime of this pointer (i.e. even after thread termination). */ static NamePairPtr getNames(); private: #if !LOG4CXX_LOGCHAR_IS_UNICHAR && !LOG4CXX_LOGCHAR_IS_WCHAR static std::basic_ostringstream& getStream(const logchar&); #endif #if LOG4CXX_WCHAR_T_API || LOG4CXX_LOGCHAR_IS_WCHAR static std::basic_ostringstream& getStream(const wchar_t&); #endif #if LOG4CXX_UNICHAR_API || LOG4CXX_LOGCHAR_IS_UNICHAR static std::basic_ostringstream& getStream(const UniChar&); #endif LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(ThreadSpecificDataPrivate, m_priv) }; } // namespace helpers } // namespace log4cxx #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/transform.h0000644000175100001770000000403014721727031024245 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_TRANSFORM_H #define _LOG4CXX_HELPERS_TRANSFORM_H #include namespace LOG4CXX_NS { namespace helpers { /** Utility class for transforming strings. */ class LOG4CXX_EXPORT Transform { public: /** * Add \c input, which may contain HTML tags * (ie, <b>, <table>, etc) to \c buf * while replacing any '<' and '>' characters * with respective predefined entity references. * * @param buf output stream where to write the modified string. * @param input The text to be converted. * */ static void appendEscapingTags( LogString& buf, const LogString& input); /** * Add \c input to \c buf while ensuring embeded CDEnd strings (]]>) * are handled properly within the message, NDC and throwable tag text. * * @param buf output stream holding the XML data to this point. The * initial CDStart () of the CDATA * section are the responsibility of the calling method. * @param input The String that is inserted into an existing CDATA * Section within buf. */ static void appendEscapingCDATA( LogString& buf, const LogString& input); }; // class Transform } // namespace helpers } //namespace log4cxx #endif // _LOG4CXX_HELPERS_TRANSFORM_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/threadutility.h0000644000175100001770000001047114721727031025133 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_THREADUTILITY_H #define _LOG4CXX_THREADUTILITY_H #include #include #include #include "log4cxx/logstring.h" #include "widelife.h" namespace LOG4CXX_NS { namespace helpers { /** * A function that will be called before a thread is started. This can * be used to (for example) block all of the signals in the thread, so * that when the thread is created it will have a correct signal mask. */ typedef std::function ThreadStartPre; /** * Called when a new thread has started. This can be used to set * parameters for the thread in a platform-specific manner. * * @param threadName The name of the thread * @param threadId The ID of the thread as reported by std::thread::get_id * @param nativeHandle The native handle of the thread, as reported by * std::thread::native_handle */ typedef std::function ThreadStarted; /** * Called after a thread has started. This can be used to (for example) * unblock the signals in the thread. */ typedef std::function ThreadStartPost; enum class ThreadConfigurationType { NoConfiguration, BlockSignalsOnly, NameThreadOnly, BlockSignalsAndNameThread, }; class ThreadUtility; LOG4CXX_PTR_DEF(ThreadUtility); class LOG4CXX_EXPORT ThreadUtility { private: friend class LOG4CXX_NS::helpers::WideLife; ThreadUtility(); LOG4CXX_NS::helpers::ThreadStartPre preStartFunction(); LOG4CXX_NS::helpers::ThreadStarted threadStartedFunction(); LOG4CXX_NS::helpers::ThreadStartPost postStartFunction(); LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(priv_data, m_priv) public: ~ThreadUtility(); static ThreadUtility* instance(); /** * Utility method for configuring the ThreadUtility in a standard * configuration. */ static void configure( ThreadConfigurationType type ); /** * Configure the thread functions that log4cxx will use. * Note that setting any of these parameters to nullptr is valid, * and simply results in the callback not being called. */ void configureFuncs( ThreadStartPre pre_start, ThreadStarted started, ThreadStartPost post_start ); /** * A pre-start thread function that blocks signals to the new thread * (if the system has pthreads). If the system does not have pthreads, * does nothing. */ void preThreadBlockSignals(); /** * A thread_started function that names the thread using the appropriate * system call. */ void threadStartedNameThread(LogString threadName, std::thread::id thread_id, std::thread::native_handle_type native_handle); /** * A post-start thread function that unblocks signals that preThreadBlockSignals * blocked before starting the thread. If the system does not have pthreads, * does nothing. */ void postThreadUnblockSignals(); /** * Start a thread */ template std::thread createThread(LogString name, Function&& f, Args&& ... args) { LOG4CXX_NS::helpers::ThreadStartPre pre_start = preStartFunction(); LOG4CXX_NS::helpers::ThreadStarted thread_start = threadStartedFunction(); LOG4CXX_NS::helpers::ThreadStartPost post_start = postStartFunction(); if ( pre_start ) { pre_start(); } std::thread t( f, args... ); if ( thread_start ) { thread_start( name, t.get_id(), t.native_handle() ); } if ( post_start ) { post_start(); } return t; } }; } /* namespace helpers */ } /* namespace log4cxx */ #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/optional.h0000644000175100001770000000463214721727031024067 0ustar runnerdocker/* * 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. */ #ifndef LOG4CXX_OPTIONAL_HDR_ #define LOG4CXX_OPTIONAL_HDR_ #ifdef __has_include // Check if __has_include is present # if __has_include() // Check for a standard version # include # if defined(__cpp_lib_optional) // C++ >= 17 namespace LOG4CXX_NS { template< class T > using Optional = std::optional; } #define LOG4CXX_HAS_STD_OPTIONAL 1 # endif # elif __has_include() // Check for an experimental version # include namespace LOG4CXX_NS { template< class T > using Optional = std::experimental::optional; } #define LOG4CXX_HAS_STD_OPTIONAL 1 # elif __has_include() // Try with an external library # include namespace LOG4CXX_NS { template< class T > using Optional = boost::optional; } #define LOG4CXX_HAS_STD_OPTIONAL 1 # else // Not found at all #define LOG4CXX_HAS_STD_OPTIONAL 0 # endif #endif #if !LOG4CXX_HAS_STD_OPTIONAL // Implement a minimal Optional? namespace LOG4CXX_NS { template< class T > class Optional : private std::pair { using BaseType = std::pair; public: Optional() : BaseType(false, T()) {} Optional& operator=(const T& value) { this->first = true; this->second = value; return *this; } constexpr explicit operator bool() const noexcept { return this->first; } constexpr bool has_value() const noexcept { return this->first; } constexpr const T& value() const noexcept { return this->second; } }; } // namespace LOG4CXX_NS #endif #endif // LOG4CXX_OPTIONAL_HDR_ apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/exception.h0000644000175100001770000002235014721727031024235 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_EXCEPTION_H #define _LOG4CXX_HELPERS_EXCEPTION_H #include #include #include #ifdef _MSC_VER #pragma warning ( push ) #pragma warning (disable : 4275) // ::std::exception needs to have dll-interface #endif namespace LOG4CXX_NS { namespace helpers { /** The class Exception and its subclasses indicate conditions that a reasonable application might want to catch. */ class LOG4CXX_EXPORT Exception : public ::std::exception { public: Exception(const char* msg); Exception(const LogString& msg); Exception(const Exception& src); Exception& operator=(const Exception& src); const char* what() const throw(); private: enum { MSG_SIZE = 128 }; char msg[MSG_SIZE + 1]; }; // class Exception /** RuntimeException is the parent class of those exceptions that can be thrown during the normal operation of the process. */ class LOG4CXX_EXPORT RuntimeException : public Exception { public: RuntimeException(log4cxx_status_t stat); RuntimeException(const LogString& msg); RuntimeException(const RuntimeException& msg); RuntimeException& operator=(const RuntimeException& src); private: static LogString formatMessage(log4cxx_status_t stat); }; // class RuntimeException /** Thrown when an application attempts to use null in a case where an object is required. */ class LOG4CXX_EXPORT NullPointerException : public RuntimeException { public: NullPointerException(const LogString& msg); NullPointerException(const NullPointerException& msg); NullPointerException& operator=(const NullPointerException& src); }; // class NullPointerException /** Thrown to indicate that a method has been passed an illegal or inappropriate argument.*/ class LOG4CXX_EXPORT IllegalArgumentException : public RuntimeException { public: IllegalArgumentException(const LogString& msg); IllegalArgumentException(const IllegalArgumentException&); IllegalArgumentException& operator=(const IllegalArgumentException&); }; // class IllegalArgumentException /** Signals that an I/O exception of some sort has occurred. This class is the general class of exceptions produced by failed or interrupted I/O operations. */ class LOG4CXX_EXPORT IOException : public Exception { public: IOException(); IOException(log4cxx_status_t stat); IOException(const LogString& msg); IOException(const LogString& type, log4cxx_status_t stat); IOException(const IOException& src); IOException& operator=(const IOException&); private: static LogString formatMessage(log4cxx_status_t stat); static LogString formatMessage(const LogString& type, log4cxx_status_t stat); }; class LOG4CXX_EXPORT MissingResourceException : public Exception { public: MissingResourceException(const LogString& key); MissingResourceException(const MissingResourceException& src); MissingResourceException& operator=(const MissingResourceException&); private: static LogString formatMessage(const LogString& key); }; class LOG4CXX_EXPORT PoolException : public Exception { public: PoolException(log4cxx_status_t stat); PoolException(const PoolException& src); PoolException& operator=(const PoolException&); private: static LogString formatMessage(log4cxx_status_t stat); }; class LOG4CXX_EXPORT InterruptedException : public Exception { public: InterruptedException(); InterruptedException(log4cxx_status_t stat); InterruptedException(const InterruptedException& src); InterruptedException& operator=(const InterruptedException&); private: static LogString formatMessage(log4cxx_status_t stat); }; class LOG4CXX_EXPORT ThreadException : public Exception { public: ThreadException(log4cxx_status_t stat); ThreadException(const LogString& msg); ThreadException(const ThreadException& src); ThreadException& operator=(const ThreadException&); private: static LogString formatMessage(log4cxx_status_t stat); }; class LOG4CXX_EXPORT TranscoderException : public Exception { public: TranscoderException(log4cxx_status_t stat); TranscoderException(const TranscoderException& src); TranscoderException& operator=(const TranscoderException&); private: static LogString formatMessage(log4cxx_status_t stat); }; class LOG4CXX_EXPORT IllegalMonitorStateException : public Exception { public: IllegalMonitorStateException(const LogString& msg); IllegalMonitorStateException(const IllegalMonitorStateException& msg); IllegalMonitorStateException& operator=(const IllegalMonitorStateException& msg); }; /** Thrown when an application tries to create an instance of a class using the newInstance method in class Class, but the specified class object cannot be instantiated because it is an interface or is an abstract class. */ class LOG4CXX_EXPORT InstantiationException : public Exception { public: InstantiationException(const LogString& msg); InstantiationException(const InstantiationException& msg); InstantiationException& operator=(const InstantiationException& msg); }; /** Thrown when an application tries to load in a class through its string name but no definition for the class with the specified name could be found. */ class LOG4CXX_EXPORT ClassNotFoundException : public Exception { public: ClassNotFoundException(const LogString& className); ClassNotFoundException(const ClassNotFoundException& msg); ClassNotFoundException& operator=(const ClassNotFoundException& msg); private: static LogString formatMessage(const LogString& className); }; class NoSuchElementException : public Exception { public: NoSuchElementException(); NoSuchElementException(const NoSuchElementException&); NoSuchElementException& operator=(const NoSuchElementException&); }; class IllegalStateException : public Exception { public: IllegalStateException(); IllegalStateException(const IllegalStateException&); IllegalStateException& operator=(const IllegalStateException&); }; /** Thrown to indicate that there is an error in the underlying protocol, such as a TCP error. */ class LOG4CXX_EXPORT SocketException : public IOException { public: SocketException(const LogString& msg); SocketException(log4cxx_status_t status); SocketException(const SocketException&); SocketException& operator=(const SocketException&); }; /** Signals that an error occurred while attempting to connect a socket to a remote address and port. Typically, the connection was refused remotely (e.g., no process is listening on the remote address/port). */ class LOG4CXX_EXPORT ConnectException : public SocketException { public: ConnectException(log4cxx_status_t status); ConnectException(const ConnectException& src); ConnectException& operator=(const ConnectException&); }; class LOG4CXX_EXPORT ClosedChannelException : public SocketException { public: ClosedChannelException(); ClosedChannelException(const ClosedChannelException& src); ClosedChannelException& operator=(const ClosedChannelException&); }; /** Signals that an error occurred while attempting to bind a socket to a local address and port. Typically, the port is in use, or the requested local address could not be assigned. */ class LOG4CXX_EXPORT BindException : public SocketException { public: BindException(log4cxx_status_t status); BindException(const BindException&); BindException& operator=(const BindException&); }; /** Signals that an I/O operation has been interrupted. An InterruptedIOException is thrown to indicate that an input or output transfer has been terminated because the thread performing it was interrupted. The field bytesTransferred indicates how many bytes were successfully transferred before the interruption occurred. */ class LOG4CXX_EXPORT InterruptedIOException : public IOException { public: InterruptedIOException(const LogString& msg); InterruptedIOException(const InterruptedIOException&); InterruptedIOException& operator=(const InterruptedIOException&); }; /** Signals that an I/O operation has been interrupted. An InterruptedIOException is thrown to indicate that an input or output transfer has been terminated because the thread performing it was interrupted. The field bytesTransferred indicates how many bytes were successfully transferred before the interruption occurred. */ class LOG4CXX_EXPORT SocketTimeoutException : public InterruptedIOException { public: SocketTimeoutException(); SocketTimeoutException(const SocketTimeoutException&); SocketTimeoutException& operator=(const SocketTimeoutException&); }; } // namespace helpers } // namespace log4cxx #if defined(_MSC_VER) #pragma warning (pop) #endif #endif // _LOG4CXX_HELPERS_EXCEPTION_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/cacheddateformat.h0000644000175100001770000001307514721727031025521 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_CACHED_DATE_FORMAT_H #define _LOG4CXX_HELPERS_CACHED_DATE_FORMAT_H #include namespace LOG4CXX_NS { namespace pattern { class LOG4CXX_EXPORT CachedDateFormat : public LOG4CXX_NS::helpers::DateFormat { public: enum { /* * Constant used to represent that there was no change * observed when changing the millisecond count. */ NO_MILLISECONDS = -2, /* * Constant used to represent that there was an * observed change, but was an expected change. */ UNRECOGNIZED_MILLISECONDS = -1 }; private: /** * Supported digit set. If the wrapped DateFormat uses * a different unit set, the millisecond pattern * will not be recognized and duplicate requests * will use the cache. */ static const logchar digits[]; /** * First magic number (in microseconds) used to detect * the millisecond position. */ static const int magic1; /** * Expected representation of first magic number in milliseconds. */ static const logchar magicString1[]; /** * Second magic number (in microseconds) used to detect * the millisecond position. */ static const int magic2; /** * Expected representation of second magic number in milliseconds. */ static const logchar magicString2[]; /** * Expected representation of 0 milliseconds. */ static const logchar zeroString[]; LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(CachedDateFormatPriv, m_priv) public: /** * Creates a new CachedDateFormat object. * @param dateFormat Date format, may not be null. * @param expiration maximum cached range in microseconds. * If the dateFormat is known to be incompatible with the * caching algorithm, use a value of 0 to totally disable * caching or 1 to only use cache for duplicate requests. */ CachedDateFormat(const LOG4CXX_NS::helpers::DateFormatPtr& dateFormat, int expiration); ~CachedDateFormat(); /** * Finds start of millisecond field in formatted time. * @param time long time, must be integral number of seconds * @param formatted String corresponding formatted string * @param formatter DateFormat date format * @param pool pool. * @return int position in string of first digit of milliseconds, * -1 indicates no millisecond field, -2 indicates unrecognized * field (likely RelativeTimeDateFormat) */ static int findMillisecondStart( log4cxx_time_t time, const LogString& formatted, const LOG4CXX_NS::helpers::DateFormatPtr& formatter, LOG4CXX_NS::helpers::Pool& pool); /** * Formats a Date into a date/time string. * * @param date the date to format. * @param sbuf the string buffer to write to. * @param p memory pool. */ virtual void format(LogString& sbuf, log4cxx_time_t date, LOG4CXX_NS::helpers::Pool& p) const; private: /** * Formats a count of milliseconds (0-999) into a numeric representation. * @param millis Millisecond coun between 0 and 999. * @buf String buffer, may not be null. * @offset Starting position in buffer, the length of the * buffer must be at least offset + 3. */ static void millisecondFormat(int millis, LogString& buf, int offset); public: /** * Set timezone. * * @remarks Setting the timezone using getCalendar().setTimeZone() * will likely cause caching to misbehave. * @param zone TimeZone new timezone */ virtual void setTimeZone(const LOG4CXX_NS::helpers::TimeZonePtr& zone); /** * Format an integer consistent with the format method. * @param s string to which the numeric string is appended. * @param n integer value. * @param p memory pool used during formatting. */ virtual void numberFormat(LogString& s, int n, LOG4CXX_NS::helpers::Pool& p) const; /** * Gets maximum cache validity for the specified SimpleDateTime * conversion pattern. * @param pattern conversion pattern, may not be null. * @returns Duration in microseconds from an integral second * that the cache will return consistent results. */ static int getMaximumCacheValidity(const LogString& pattern); private: CachedDateFormat(const CachedDateFormat&); CachedDateFormat& operator=(const CachedDateFormat&); /** * Tests if two string regions are equal. * @param target target string. * @param toffset character position in target to start comparison. * @param other other string. * @param ooffset character position in other to start comparison. * @param len length of region. * @return true if regions are equal. */ static bool regionMatches( const LogString& target, size_t toffset, const LogString& other, size_t ooffset, size_t len); }; } // namespace helpers } // namespace log4cxx #endif // _LOG4CXX_HELPERS_SIMPLE_DATE_FORMAT_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/inputstreamreader.h0000644000175100001770000000547514721727031026006 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_INPUTSTREAMREADER_H #define _LOG4CXX_HELPERS_INPUTSTREAMREADER_H #include #include #include // Instantiate template pointer types passed as parameters LOG4CXX_INSTANTIATE_EXPORTED_PTR(LOG4CXX_NS::helpers::InputStream); LOG4CXX_INSTANTIATE_EXPORTED_PTR(LOG4CXX_NS::helpers::CharsetDecoder); namespace LOG4CXX_NS { namespace helpers { /** * Class for reading from character streams. * Decorates a byte based InputStream and provides appropriate * conversion to characters. */ class LOG4CXX_EXPORT InputStreamReader : public Reader { private: LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(InputStreamReaderPrivate, m_priv) public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(InputStreamReader) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(InputStreamReader) LOG4CXX_CAST_ENTRY_CHAIN(Reader) END_LOG4CXX_CAST_MAP() /** * Creates an InputStreamReader that uses the default charset. * * @param in The input stream to decorate. */ InputStreamReader(const InputStreamPtr& in); /** * Creates an InputStreamReader that uses the given charset decoder. * * @param in The input stream to decorate. * @param enc The charset decoder to use for the conversion. */ InputStreamReader(const InputStreamPtr& in, const CharsetDecoderPtr& enc); ~InputStreamReader(); /** * Closes the stream. * * @param p The memory pool associated with the reader. */ void close(Pool& p) override; /** * @return The complete stream contents as a LogString. * @param p The memory pool associated with the reader. */ LogString read(Pool& p) override; /** * @return The name of the character encoding being used by this stream. */ LogString getEncoding() const; private: InputStreamReader(const InputStreamReader&); InputStreamReader& operator=(const InputStreamReader&); }; LOG4CXX_PTR_DEF(InputStreamReader); } // namespace helpers } //namespace log4cxx #endif //_LOG4CXX_HELPERS_INPUTSTREAMREADER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/propertyresourcebundle.h0000644000175100001770000000374414721727031027073 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_PROPERTY_RESOURCE_BUNDLE_H #define _LOG4CXX_HELPERS_PROPERTY_RESOURCE_BUNDLE_H #include #include #include namespace LOG4CXX_NS { namespace helpers { /** PropertyResourceBundle is a concrete subclass of ResourceBundle that manages resources for a locale using a set of static strings from a property file. */ class LOG4CXX_EXPORT PropertyResourceBundle : public ResourceBundle { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(PropertyResourceBundle) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(PropertyResourceBundle) LOG4CXX_CAST_ENTRY_CHAIN(ResourceBundle) END_LOG4CXX_CAST_MAP() /** Creates a property resource bundle. @param inStream property file to read from. @throw IOException if an error occurred when reading from the input stream. */ PropertyResourceBundle(InputStreamPtr inStream); LogString getString(const LogString& key) const override; protected: Properties properties; }; // class PropertyResourceBundle LOG4CXX_PTR_DEF(PropertyResourceBundle); } // namespace helpers } // namespace log4cxx #endif // _LOG4CXX_HELPERS_PROPERTY_RESOURCE_BUNDLE_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/writer.h0000644000175100001770000000310214721727031023545 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_WRITER_H #define _LOG4CXX_HELPERS_WRITER_H #include #include namespace LOG4CXX_NS { namespace helpers { /** * Abstract class for writing to character streams. */ class LOG4CXX_EXPORT Writer : public Object { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(Writer) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(Writer) END_LOG4CXX_CAST_MAP() protected: Writer(); virtual ~Writer(); public: virtual void close(Pool& p) = 0; virtual void flush(Pool& p) = 0; virtual void write(const LogString& str, Pool& p) = 0; private: Writer(const Writer&); Writer& operator=(const Writer&); }; LOG4CXX_PTR_DEF(Writer); } // namespace helpers } //namespace log4cxx #endif //_LOG4CXX_HELPERS_WRITER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/simpledateformat.h0000644000175100001770000000571614721727031025606 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_SIMPLE_DATE_FORMAT_H #define _LOG4CXX_HELPERS_SIMPLE_DATE_FORMAT_H #include #include #include #include using std::locale; namespace LOG4CXX_NS { namespace helpers { namespace SimpleDateFormatImpl { class PatternToken; } LOG4CXX_LIST_DEF(PatternTokenList, LOG4CXX_NS::helpers::SimpleDateFormatImpl::PatternToken*); /** * Concrete class for converting and formatting a date/time * in a locale-sensitive manner. * * Specifier | Date/time component * --------- | --------------------- * G | era * y | year * M | month number * MMM | abbreviated month name * MMMM | full month name * w | week in year * W | week in month * D | day in year * d | day in month * EEE | abbreviated day name * EEEE | full day name * a | AM or PM * H | hour 0 - 23 * k | hour 1 - 24 * K | hour 0 - 11 * h | hour 1 - 12 * m | minute * s | second * S | millisecond * z | time zone identifier * Z | RFC822 time zone */ class LOG4CXX_EXPORT SimpleDateFormat : public DateFormat { public: /** * A time converter and formatter using \c pattern and the default std::locale. * * @param pattern the specifiers describing the date and time format */ SimpleDateFormat(const LogString& pattern); /** * A time converter and formatter using \c pattern and \c locale. * * @param pattern the specifiers describing the date and time format * @param locale the user-preferred set of immutable facets */ SimpleDateFormat(const LogString& pattern, const std::locale* locale); ~SimpleDateFormat(); virtual void format(LogString& s, log4cxx_time_t tm, LOG4CXX_NS::helpers::Pool& p) const; /** * Set time zone. * @param zone new time zone. */ void setTimeZone(const TimeZonePtr& zone); private: LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(SimpleDateFormatPrivate, m_priv) static void addToken(const logchar spec, const int repeat, const std::locale* locale, PatternTokenList& pattern); static void parsePattern(const LogString& spec, const std::locale* locale, PatternTokenList& pattern); }; } // namespace helpers } // namespace log4cxx #endif // _LOG4CXX_HELPERS_SIMPLE_DATE_FORMAT_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/absolutetimedateformat.h0000644000175100001770000000251214721727031027001 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_ABSOLUTE_TIME_DATE_FORMAT_H #define _LOG4CXX_HELPERS_ABSOLUTE_TIME_DATE_FORMAT_H #include namespace LOG4CXX_NS { namespace helpers { /** Formats a date in the format HH:mm:ss,SSS for example, "15:49:37,459". */ class LOG4CXX_EXPORT AbsoluteTimeDateFormat : public SimpleDateFormat { public: AbsoluteTimeDateFormat() : SimpleDateFormat(LOG4CXX_STR("HH:mm:ss,SSS")) {} }; } // namespace helpers } // namespace log4cxx #endif // _LOG4CXX_HELPERS_ABSOLUTE_TIME_DATE_FORMAT_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/class.h0000644000175100001770000000314514721727031023345 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_CLASS_H #define _LOG4CXX_HELPERS_CLASS_H #include #include namespace LOG4CXX_NS { namespace helpers { class Object; class LOG4CXX_EXPORT Class { public: virtual ~Class(); virtual Object* newInstance() const; #if LOG4CXX_ABI_VERSION <= 15 [[ deprecated( "Use getName() instead" ) ]] LogString toString() const; #endif virtual LogString getName() const = 0; static const Class& forName(const LogString& className); static bool registerClass(const Class& newClass); protected: Class(); private: Class(const Class&); Class& operator=(const Class&); typedef std::map ClassMap; static ClassMap& getRegistry(); static void registerClasses(); }; } // namespace helpers } // namespace log4cxx #endif //_LOG4CXX_HELPERS_CLASS_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/socket.h0000644000175100001770000000441314721727031023527 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_SOCKET_H #define _LOG4CXX_HELPERS_SOCKET_H #include #include namespace LOG4CXX_NS { namespace helpers { class ByteBuffer; class Socket; LOG4CXX_PTR_DEF(Socket); LOG4CXX_UNIQUE_PTR_DEF(Socket); /**

This class implements client sockets (also called just "sockets"). A socket is an endpoint for communication between two machines.

The actual work of the socket is performed by an instance of the SocketImpl class. An application, by changing the socket factory that creates the socket implementation, can configure itself to create sockets appropriate to the local firewall. */ class LOG4CXX_EXPORT Socket : public helpers::Object { protected: LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(SocketPrivate, m_priv) Socket(LOG4CXX_PRIVATE_PTR(SocketPrivate) priv); public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(Socket) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(Socket) END_LOG4CXX_CAST_MAP() virtual ~Socket(); virtual size_t write(ByteBuffer&) = 0; /** Closes this socket. */ virtual void close() = 0; /** Returns the value of this socket's address field. */ InetAddressPtr getInetAddress() const; /** Returns the value of this socket's port field. */ int getPort() const; static SocketUniquePtr create(InetAddressPtr& address, int port); private: Socket(const Socket&); Socket& operator=(const Socket&); }; } // namespace helpers } // namespace log4cxx #endif // _LOG4CXX_HELPERS_SOCKET_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/systemoutwriter.h0000644000175100001770000000325414721727031025552 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_SYSTEMOUTWRITER_H #define _LOG4CXX_HELPERS_SYSTEMOUTWRITER_H #include namespace LOG4CXX_NS { namespace helpers { /** * Sends output to stdout. */ class LOG4CXX_EXPORT SystemOutWriter : public Writer { public: DECLARE_LOG4CXX_OBJECT(SystemOutWriter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(SystemOutWriter) LOG4CXX_CAST_ENTRY_CHAIN(Writer) END_LOG4CXX_CAST_MAP() SystemOutWriter(); ~SystemOutWriter(); void close(Pool& p) override; void flush(Pool& p) override; void write(const LogString& str, Pool& p) override; static void write(const LogString& str); static void flush(); private: SystemOutWriter(const SystemOutWriter&); SystemOutWriter& operator=(const SystemOutWriter&); static bool isWide(); }; } // namespace helpers } //namespace log4cxx #endif //_LOG4CXX_HELPERS_SYSTEMOUTWRITER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/timezone.h0000644000175100001770000000342314721727031024071 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_TIMEZONE_H #define _LOG4CXX_HELPERS_TIMEZONE_H #include #include struct apr_time_exp_t; namespace LOG4CXX_NS { namespace helpers { class TimeZone; LOG4CXX_PTR_DEF(TimeZone); class LOG4CXX_EXPORT TimeZone : public helpers::Object { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(TimeZone) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(TimeZone) END_LOG4CXX_CAST_MAP() static const TimeZonePtr& getDefault(); static const TimeZonePtr& getGMT(); static const TimeZonePtr getTimeZone(const LogString& ID); const LogString getID() const { return id; } /** * Expand an APR time into the human readable * components for this timezone. */ virtual log4cxx_status_t explode(apr_time_exp_t* result, log4cxx_time_t input) const = 0; protected: TimeZone(const LogString& ID); virtual ~TimeZone(); LOG4CXX_DECLARE_PRIVATE_MEMBER(LogString, id) }; } } #endif //_LOG4CXX_HELPERS_TIMEZONE_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/bytebuffer.h0000644000175100001770000000316314721727031024375 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_BYTEBUFFER_H #define _LOG4CXX_HELPERS_BYTEBUFFER_H #include #include namespace LOG4CXX_NS { namespace helpers { /** * A byte buffer. */ class LOG4CXX_EXPORT ByteBuffer { private: LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(ByteBufferPriv, m_priv) public: ByteBuffer(char* data, size_t capacity); ~ByteBuffer(); void clear(); void flip(); char* data(); const char* data() const; char* current(); const char* current() const; size_t limit() const; void limit(size_t newLimit); size_t position() const; size_t remaining() const; void position(size_t newPosition); bool put(char byte); private: ByteBuffer(const ByteBuffer&); ByteBuffer& operator=(const ByteBuffer&); }; } // namespace helpers } //namespace log4cxx #endif //_LOG4CXX_HELPERS_BYTEBUFFER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/fileoutputstream.h0000644000175100001770000000405214721727031025652 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_FILEOUTPUTSTREAM_H #define _LOG4CXX_HELPERS_FILEOUTPUTSTREAM_H #include #include #include namespace LOG4CXX_NS { namespace helpers { /** * OutputStream implemented on top of APR file IO. */ class LOG4CXX_EXPORT FileOutputStream : public OutputStream { private: LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(FileOutputStreamPrivate, m_priv) public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(FileOutputStream) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(FileOutputStream) LOG4CXX_CAST_ENTRY_CHAIN(OutputStream) END_LOG4CXX_CAST_MAP() FileOutputStream(const LogString& filename, bool append = false); FileOutputStream(const logchar* filename, bool append = false); virtual ~FileOutputStream(); void close(Pool& p) override; void flush(Pool& p) override; void write(ByteBuffer& buf, Pool& p) override; apr_file_t* getFilePtr() const; private: FileOutputStream(const FileOutputStream&); FileOutputStream& operator=(const FileOutputStream&); static apr_file_t* open(const LogString& fn, bool append, LOG4CXX_NS::helpers::Pool& p); }; LOG4CXX_PTR_DEF(FileOutputStream); } // namespace helpers } //namespace log4cxx #endif //_LOG4CXX_HELPERS_FILEOUTPUTSTREAM_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/onlyonceerrorhandler.h0000644000175100001770000000667314721727031026507 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_ONLY_ONCE_ERROR_HANDLER_H #define _LOG4CXX_HELPERS_ONLY_ONCE_ERROR_HANDLER_H #include #include namespace LOG4CXX_NS { namespace helpers { /** The OnlyOnceErrorHandler implements log4cxx's default error handling policy which consists of emitting a message for the first error in an appender and ignoring all following errors.

The error message is printed on System.err.

This policy aims at protecting an otherwise working application from being flooded with error messages when logging fails */ class LOG4CXX_EXPORT OnlyOnceErrorHandler : public virtual spi::ErrorHandler, public virtual Object { private: LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(OnlyOnceErrorHandlerPrivate, m_priv) public: DECLARE_LOG4CXX_OBJECT(OnlyOnceErrorHandler) BEGIN_LOG4CXX_CAST_MAP() #if 15 < LOG4CXX_ABI_VERSION LOG4CXX_CAST_ENTRY(OnlyOnceErrorHandler) LOG4CXX_CAST_ENTRY_CHAIN(spi::ErrorHandler) #else LOG4CXX_CAST_ENTRY(spi::OptionHandler) LOG4CXX_CAST_ENTRY(spi::ErrorHandler) #endif END_LOG4CXX_CAST_MAP() OnlyOnceErrorHandler(); ~OnlyOnceErrorHandler(); /** Does not do anything. */ void setLogger(const LoggerPtr& logger) override; /** \copybrief spi::OptionHandler::activateOptions() No action is performed in this implementation. */ void activateOptions(helpers::Pool& p) override; /** \copybrief spi::OptionHandler::setOption() Supported options | Supported values | Default value -------------- | ---------------- | --------------- - | - | - */ void setOption(const LogString& option, const LogString& value) override; /** Prints the message and the stack trace of the exception on System.err. */ void error(const LogString& message, const std::exception& e, int errorCode) const override; /** Prints the message and the stack trace of the exception on System.err. */ void error(const LogString& message, const std::exception& e, int errorCode, const spi::LoggingEventPtr& event) const override; /** Print a the error message passed as parameter on System.err. */ void error(const LogString& message) const override; /** Does not do anything. */ void setAppender(const AppenderPtr& appender) override; /** Does not do anything. */ void setBackupAppender(const AppenderPtr& appender) override; /** Has an error been reported? */ #if 15 < LOG4CXX_ABI_VERSION bool errorReported() const override; #else bool errorReported() const; #endif }; } // namespace helpers } // namespace log4cxx #endif //_LOG4CXX_HELPERS_ONLY_ONCE_ERROR_HANDLER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/bufferedwriter.h0000644000175100001770000000342614721727031025261 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_BUFFEREDWRITER_H #define _LOG4CXX_HELPERS_BUFFEREDWRITER_H #include namespace LOG4CXX_NS { namespace helpers { /** * Writes text to a character-output stream buffering * requests to increase efficiency. */ class LOG4CXX_EXPORT BufferedWriter : public Writer { private: LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(BufferedWriterPriv, m_priv) public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(BufferedWriter) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(BufferedWriter) LOG4CXX_CAST_ENTRY_CHAIN(Writer) END_LOG4CXX_CAST_MAP() BufferedWriter(WriterPtr& out); BufferedWriter(WriterPtr& out, size_t sz); virtual ~BufferedWriter(); void close(Pool& p) override; void flush(Pool& p) override; void write(const LogString& str, Pool& p) override; private: BufferedWriter(const BufferedWriter&); BufferedWriter& operator=(const BufferedWriter&); }; } // namespace helpers } //namespace log4cxx #endif //_LOG4CXX_HELPERS_BUFFEREDWRITER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/messagebuffer.h0000644000175100001770000006017414721727031025063 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_MESSAGE_BUFFER_H #define _LOG4CXX_MESSAGE_BUFFER_H #include #include #include namespace LOG4CXX_NS { namespace helpers { typedef std::ios_base& (*ios_base_manip)(std::ios_base&); /** * This class is used by the LOG4CXX_INFO and similar * macros to support insertion operators in the message parameter. * The class is not intended for use outside of that context. */ class LOG4CXX_EXPORT CharMessageBuffer { public: /** * Creates a new instance. */ CharMessageBuffer(); /** * Destructor. */ ~CharMessageBuffer(); /** * Appends string to buffer. * @param msg string append. * @return this buffer. */ CharMessageBuffer& operator<<(const std::basic_string& msg); /** * Appends string to buffer. * @param msg string to append. * @return this buffer. */ CharMessageBuffer& operator<<(const char* msg); /** * Appends string to buffer. * @param msg string to append. * @return this buffer. */ CharMessageBuffer& operator<<(char* msg); /** * Appends character to buffer. * @param msg character to append. * @return this buffer. */ CharMessageBuffer& operator<<(const char msg); #if LOG4CXX_CFSTRING_API /** * Appends a string into the buffer and * fixes the buffer to use char characters. * @param msg message to append. * @return encapsulated CharMessageBuffer. */ CharMessageBuffer& operator<<(const CFStringRef& msg); #endif /** * Insertion operator for STL manipulators such as std::fixed. * @param manip manipulator. * @return encapsulated STL stream. */ std::ostream& operator<<(ios_base_manip manip); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ std::ostream& operator<<(bool val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ std::ostream& operator<<(short val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ std::ostream& operator<<(int val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ std::ostream& operator<<(unsigned int val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ std::ostream& operator<<(long val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ std::ostream& operator<<(unsigned long val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ std::ostream& operator<<(float val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ std::ostream& operator<<(double val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ std::ostream& operator<<(long double val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ std::ostream& operator<<(void* val); /** * Cast to ostream. */ operator std::basic_ostream& (); /** * Remove the constructed string. * @param os used only to signal that * the embedded stream was used. */ std::basic_string extract_str(std::basic_ostream& os); /** * Remove the constructed string. * @param buf used only to signal that * the embedded stream was not used. */ std::basic_string extract_str(CharMessageBuffer& buf); /** * Get content of buffer. * @param os used only to signal that * the embedded stream was used. */ const std::basic_string& str(std::basic_ostream& os); /** * Get content of buffer. * @param buf used only to signal that * the embedded stream was not used. */ const std::basic_string& str(CharMessageBuffer& buf); /** * Returns true if buffer has an encapsulated STL stream. * @return true if STL stream was created. */ bool hasStream() const; private: /** * Prevent use of default copy constructor. */ CharMessageBuffer(const CharMessageBuffer&); /** * Prevent use of default assignment operator. */ CharMessageBuffer& operator=(const CharMessageBuffer&); LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(CharMessageBufferPrivate, m_priv) }; template std::basic_ostream& operator<<(CharMessageBuffer& os, const V& val) { return ((std::basic_ostream&) os) << val; } #if LOG4CXX_UNICHAR_API || LOG4CXX_LOGCHAR_IS_UNICHAR /** * This class is designed to support insertion operations * in the message argument to the LOG4CXX_INFO and similar * macros and is not designed for general purpose use. */ class LOG4CXX_EXPORT UniCharMessageBuffer { public: /** * Creates a new instance. */ UniCharMessageBuffer(); /** * Destructor. */ ~UniCharMessageBuffer(); typedef std::basic_ostream uostream; /** * Appends string to buffer. * @param msg string append. * @return this buffer. */ UniCharMessageBuffer& operator<<(const std::basic_string& msg); /** * Appends string to buffer. * @param msg string to append. * @return this buffer. */ UniCharMessageBuffer& operator<<(const UniChar* msg); /** * Appends string to buffer. * @param msg string to append. * @return this buffer. */ UniCharMessageBuffer& operator<<(UniChar* msg); /** * Appends character to buffer. * @param msg character to append. * @return this buffer. */ UniCharMessageBuffer& operator<<(const UniChar msg); #if LOG4CXX_CFSTRING_API /** * Appends a string into the buffer and * fixes the buffer to use char characters. * @param msg message to append. * @return encapsulated CharMessageBuffer. */ UniCharMessageBuffer& operator<<(const CFStringRef& msg); #endif /** * Insertion operator for STL manipulators such as std::fixed. * @param manip manipulator. * @return encapsulated STL stream. */ uostream& operator<<(ios_base_manip manip); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ uostream& operator<<(bool val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ uostream& operator<<(short val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ uostream& operator<<(int val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ uostream& operator<<(unsigned int val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ uostream& operator<<(long val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ uostream& operator<<(unsigned long val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ uostream& operator<<(float val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ uostream& operator<<(double val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ uostream& operator<<(long double val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ uostream& operator<<(void* val); /** * Cast to ostream. */ operator uostream& (); /** * Remove the constructed string. * @param os used only to signal that * the embedded stream was used. */ std::basic_string extract_str(uostream& os); /** * Remove the constructed string. * @param buf used only to signal that * the embedded stream was not used. */ std::basic_string extract_str(UniCharMessageBuffer& buf); /** * Get content of buffer. * @param os used only to signal that * the embedded stream was used. */ const std::basic_string& str(uostream& os); /** * Get content of buffer. * @param buf used only to signal that * the embedded stream was not used. */ const std::basic_string& str(UniCharMessageBuffer& buf); /** * Returns true if buffer has an encapsulated STL stream. * @return true if STL stream was created. */ bool hasStream() const; private: /** * Prevent use of default copy constructor. */ UniCharMessageBuffer(const UniCharMessageBuffer&); /** * Prevent use of default assignment operator. */ UniCharMessageBuffer& operator=(const UniCharMessageBuffer&); LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(UniCharMessageBufferPrivate, m_priv) }; template UniCharMessageBuffer::uostream& operator<<(UniCharMessageBuffer& os, const V& val) { return ((UniCharMessageBuffer::uostream&) os) << val; } #endif #if LOG4CXX_WCHAR_T_API /** * This class is designed to support insertion operations * in the message argument to the LOG4CXX_INFO and similar * macros and is not designed for general purpose use. */ class LOG4CXX_EXPORT WideMessageBuffer { public: /** * Creates a new instance. */ WideMessageBuffer(); /** * Destructor. */ ~WideMessageBuffer(); /** * Appends string to buffer. * @param msg string append. * @return this buffer. */ WideMessageBuffer& operator<<(const std::basic_string& msg); /** * Appends string to buffer. * @param msg string to append. * @return this buffer. */ WideMessageBuffer& operator<<(const wchar_t* msg); /** * Appends string to buffer. * @param msg string to append. * @return this buffer. */ WideMessageBuffer& operator<<(wchar_t* msg); /** * Appends character to buffer. * @param msg character to append. * @return this buffer. */ WideMessageBuffer& operator<<(const wchar_t msg); /** * Insertion operator for STL manipulators such as std::fixed. * @param manip manipulator. * @return encapsulated STL stream. */ std::basic_ostream& operator<<(ios_base_manip manip); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ std::basic_ostream& operator<<(bool val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ std::basic_ostream& operator<<(short val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ std::basic_ostream& operator<<(int val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ std::basic_ostream& operator<<(unsigned int val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ std::basic_ostream& operator<<(long val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ std::basic_ostream& operator<<(unsigned long val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ std::basic_ostream& operator<<(float val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ std::basic_ostream& operator<<(double val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ std::basic_ostream& operator<<(long double val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ std::basic_ostream& operator<<(void* val); /** * Cast to ostream. */ operator std::basic_ostream& (); /** * Remove the constructed string. * @param os used only to signal that * the embedded stream was used. */ std::basic_string extract_str(std::basic_ostream& os); /** * Remove the constructed string. * @param buf used only to signal that * the embedded stream was not used. */ std::basic_string extract_str(WideMessageBuffer& buf); /** * Get content of buffer. * @param os used only to signal that * the embedded stream was used. */ const std::basic_string& str(std::basic_ostream& os); /** * Get content of buffer. * @param buf used only to signal that * the embedded stream was not used. */ const std::basic_string& str(WideMessageBuffer& buf); /** * Returns true if buffer has an encapsulated STL stream. * @return true if STL stream was created. */ bool hasStream() const; private: /** * Prevent use of default copy constructor. */ WideMessageBuffer(const WideMessageBuffer&); /** * Prevent use of default assignment operator. */ WideMessageBuffer& operator=(const WideMessageBuffer&); LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(WideMessageBufferPrivate, m_priv) }; template std::basic_ostream& operator<<(WideMessageBuffer& os, const V& val) { return ((std::basic_ostream&) os) << val; } /** * This class is used by the LOG4CXX_INFO and similar * macros to support insertion operators in the message parameter. * The class is not intended for use outside of that context. */ class LOG4CXX_EXPORT MessageBuffer { public: /** * Creates a new instance. */ MessageBuffer(); /** * Destructor. */ ~MessageBuffer(); /** * Cast to ostream. */ operator std::ostream& (); /** * Appends a string into the buffer and * fixes the buffer to use char characters. * @param msg message to append. * @return encapsulated CharMessageBuffer. */ CharMessageBuffer& operator<<(const std::string& msg); /** * Appends a string into the buffer and * fixes the buffer to use char characters. * @param msg message to append. * @return encapsulated CharMessageBuffer. */ CharMessageBuffer& operator<<(const char* msg); /** * Appends a string into the buffer and * fixes the buffer to use char characters. * @param msg message to append. * @return encapsulated CharMessageBuffer. */ CharMessageBuffer& operator<<(char* msg); /** * Appends a string into the buffer and * fixes the buffer to use char characters. * @param msg message to append. * @return encapsulated CharMessageBuffer. */ CharMessageBuffer& operator<<(const char msg); /** * Remove the constructed string. * @param buf used only to signal * the character type and that * the embedded stream was not used. */ std::string extract_str(CharMessageBuffer& buf); /** * Remove the constructed string. * @param os used only to signal * the character type and that * the embedded stream was used. */ std::string extract_str(std::ostream& os); /** * Get content of buffer. * @param buf used only to signal * the character type and that * the embedded stream was not used. */ const std::string& str(CharMessageBuffer& buf); /** * Get content of buffer. * @param os used only to signal * the character type and that * the embedded stream was used. */ const std::string& str(std::ostream& os); /** * Appends a string into the buffer and * fixes the buffer to use char characters. * @param msg message to append. * @return encapsulated CharMessageBuffer. */ WideMessageBuffer& operator<<(const std::wstring& msg); /** * Appends a string into the buffer and * fixes the buffer to use char characters. * @param msg message to append. * @return encapsulated CharMessageBuffer. */ WideMessageBuffer& operator<<(const wchar_t* msg); /** * Appends a string into the buffer and * fixes the buffer to use char characters. * @param msg message to append. * @return encapsulated CharMessageBuffer. */ WideMessageBuffer& operator<<(wchar_t* msg); /** * Appends a string into the buffer and * fixes the buffer to use char characters. * @param msg message to append. * @return encapsulated CharMessageBuffer. */ WideMessageBuffer& operator<<(const wchar_t msg); #if LOG4CXX_UNICHAR_API /** * Appends a string into the buffer and * fixes the buffer to use char characters. * @param msg message to append. * @return encapsulated CharMessageBuffer. */ UniCharMessageBuffer& operator<<(const std::basic_string& msg); /** * Appends a string into the buffer and * fixes the buffer to use char characters. * @param msg message to append. * @return encapsulated CharMessageBuffer. */ UniCharMessageBuffer& operator<<(const UniChar* msg); /** * Appends a string into the buffer and * fixes the buffer to use char characters. * @param msg message to append. * @return encapsulated CharMessageBuffer. */ UniCharMessageBuffer& operator<<(UniChar* msg); /** * Appends a string into the buffer and * fixes the buffer to use char characters. * @param msg message to append. * @return encapsulated CharMessageBuffer. */ UniCharMessageBuffer& operator<<(const UniChar msg); /** * Remove the constructed string. * @param buf used only to signal that * the embedded stream was not used. */ std::basic_string extract_str(UniCharMessageBuffer& buf); /** * Remove the constructed string. * @param os used only to signal that * the embedded stream was not used. */ std::basic_string extract_str(std::basic_ostream& os); #endif #if LOG4CXX_UNICHAR_API && LOG4CXX_CFSTRING_API /** * Appends a string into the buffer and * fixes the buffer to use char characters. * @param msg message to append. * @return encapsulated CharMessageBuffer. */ UniCharMessageBuffer& operator<<(const CFStringRef& msg); #elif LOG4CXX_CFSTRING_API /** * Appends a string into the buffer and * fixes the buffer to use char characters. * @param msg message to append. * @return encapsulated CharMessageBuffer. */ CharMessageBuffer& operator<<(const CFStringRef& msg); #endif /** * Insertion operator for STL manipulators such as std::fixed. * @param manip manipulator. * @return encapsulated STL stream. */ std::ostream& operator<<(ios_base_manip manip); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ std::ostream& operator<<(bool val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ std::ostream& operator<<(short val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ std::ostream& operator<<(int val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ std::ostream& operator<<(unsigned int val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ std::ostream& operator<<(long val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ std::ostream& operator<<(unsigned long val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ std::ostream& operator<<(float val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ std::ostream& operator<<(double val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ std::ostream& operator<<(long double val); /** * Insertion operator for built-in type. * @param val build in type. * @return encapsulated STL stream. */ std::ostream& operator<<(void* val); /** * Remove the constructed string. * @param buf used only to signal * the character type and that * the embedded stream was not used. */ std::wstring extract_str(WideMessageBuffer& buf); /** * Remove the constructed string. * @param os used only to signal * the character type and that * the embedded stream was used. */ std::wstring extract_str(std::basic_ostream& os); /** * Get content of buffer. * @param buf used only to signal * the character type and that * the embedded stream was not used. */ const std::wstring& str(WideMessageBuffer& buf); /** * Get content of buffer. * @param os used only to signal * the character type and that * the embedded stream was used. */ const std::wstring& str(std::basic_ostream& os); #if LOG4CXX_UNICHAR_API /** * Get content of buffer. * @param buf used only to signal * the character type and that * the embedded stream was not used. */ const std::basic_string& str(UniCharMessageBuffer& buf); /** * Get content of buffer. * @param os used only to signal * the character type and that * the embedded stream was used. */ const std::basic_string& str(UniCharMessageBuffer::uostream& os); #endif /** * Returns true if buffer has an encapsulated STL stream. * @return true if STL stream was created. */ bool hasStream() const; private: /** * Prevent use of default copy constructor. */ MessageBuffer(const MessageBuffer&); /** * Prevent use of default assignment operator. */ MessageBuffer& operator=(const MessageBuffer&); LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(MessageBufferPrivate, m_priv) }; template std::ostream& operator<<(MessageBuffer& os, const V& val) { return ((std::ostream&) os) << val; } #if LOG4CXX_LOGCHAR_IS_UTF8 typedef CharMessageBuffer LogCharMessageBuffer; #endif #if LOG4CXX_LOGCHAR_IS_WCHAR typedef WideMessageBuffer LogCharMessageBuffer; #endif #if LOG4CXX_LOGCHAR_IS_UNICHAR typedef UniCharMessageBuffer LogCharMessageBuffer; #endif #else // !LOG4CXX_WCHAR_T_API typedef CharMessageBuffer MessageBuffer; typedef CharMessageBuffer LogCharMessageBuffer; #endif // !LOG4CXX_WCHAR_T_API } } #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/loader.h0000644000175100001770000000246514721727031023512 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_LOADER_H #define _LOG4CXX_HELPERS_LOADER_H #include #include #include #include namespace LOG4CXX_NS { namespace helpers { class Class; class LOG4CXX_EXPORT Loader { public: static const Class& loadClass(const LogString& clazz); static InputStreamPtr getResourceAsStream( const LogString& name); }; } // namespace helpers } // namespace log4cxx #endif //_LOG4CXX_HELPERS_LOADER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/syslogwriter.h0000644000175100001770000000274514721727031025022 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_SYSLOG_WRITER_H #define _LOG4CXX_SYSLOG_WRITER_H #include #include #include namespace LOG4CXX_NS { namespace helpers { /** SyslogWriter is a wrapper around the DatagramSocket class it writes text to the specified host on the port 514 (UNIX syslog) */ class LOG4CXX_EXPORT SyslogWriter { public: #define SYSLOG_PORT 514 SyslogWriter(const LogString& syslogHost, int syslogHostPort = SYSLOG_PORT); ~SyslogWriter(); void write(const LogString& string); private: LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(SyslogWriterPrivate, m_priv) }; } // namespace helpers } // namespace log4cxx #endif apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/bytearrayoutputstream.h0000644000175100001770000000365014721727031026740 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_BYTEARRAYOUTPUTSTREAM_H #define _LOG4CXX_HELPERS_BYTEARRAYOUTPUTSTREAM_H #include #include namespace LOG4CXX_NS { namespace helpers { class Pool; LOG4CXX_LIST_DEF(ByteList, unsigned char); /** * OutputStream implemented on top of std::vector */ class LOG4CXX_EXPORT ByteArrayOutputStream : public OutputStream { private: LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(ByteArrayOutputStreamPriv, m_priv) public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(ByteArrayOutputStream) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(ByteArrayOutputStream) LOG4CXX_CAST_ENTRY_CHAIN(OutputStream) END_LOG4CXX_CAST_MAP() ByteArrayOutputStream(); virtual ~ByteArrayOutputStream(); void close(Pool& p) override; void flush(Pool& p) override; void write(ByteBuffer& buf, Pool& p) override; ByteList toByteArray() const; private: ByteArrayOutputStream(const ByteArrayOutputStream&); ByteArrayOutputStream& operator=(const ByteArrayOutputStream&); }; LOG4CXX_PTR_DEF(ByteArrayOutputStream); } // namespace helpers } //namespace log4cxx #endif //_LOG4CXX_HELPERS_BYTEARRAYOUTPUTSTREAM_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/locale.h0000644000175100001770000000303714721727031023477 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_LOCALE_H #define _LOG4CXX_HELPERS_LOCALE_H #include #include namespace LOG4CXX_NS { namespace helpers { class LOG4CXX_EXPORT Locale { public: Locale(const LogString& language); Locale(const LogString& language, const LogString& country); Locale(const LogString& language, const LogString& country, const LogString& variant); ~Locale(); const LogString& getLanguage() const; const LogString& getCountry() const; const LogString& getVariant() const; protected: Locale(const Locale&); Locale& operator=(const Locale&); LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(LocalePrivate, m_priv) }; // class Locale } // namespace helpers } // namespace log4cxx #endif // _LOG4CXX_HELPERS_LOCALE_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/xml.h0000644000175100001770000000647514721727031023051 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_XML_H #define _LOG4CXX_HELPERS_XML_H #include #include #include namespace LOG4CXX_NS { class File; namespace helpers { class XMLDOMNode; typedef std::shared_ptr XMLDOMNodePtr; class XMLDOMDocument; typedef std::shared_ptr XMLDOMDocumentPtr; class XMLDOMNodeList; typedef std::shared_ptr XMLDOMNodeListPtr; class LOG4CXX_EXPORT DOMException : public RuntimeException { public: DOMException() : RuntimeException(LOG4CXX_STR("DOM exception")) {} }; /** The XMLDOMNode interface is the primary datatype for the entire Document Object Model. */ class LOG4CXX_EXPORT XMLDOMNode : virtual public Object { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(XMLDOMNode) enum XMLDOMNodeType { NOT_IMPLEMENTED_NODE = 0, ELEMENT_NODE = 1, DOCUMENT_NODE = 9 }; virtual XMLDOMNodeListPtr getChildNodes() = 0; virtual XMLDOMNodeType getNodeType() = 0; virtual XMLDOMDocumentPtr getOwnerDocument() = 0; }; LOG4CXX_PTR_DEF(XMLDOMNode); /** The XMLDOMElement interface represents an element in an XML document */ class LOG4CXX_EXPORT XMLDOMElement : virtual public XMLDOMNode { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(XMLDOMElement) virtual LogString getTagName() = 0; virtual LogString getAttribute(const LogString& name) = 0; }; LOG4CXX_PTR_DEF(XMLDOMElement); /** The XMLDOMDocument interface represents an entire XML document. Conceptually, it is the root of the document tree, and provides the primary access to the document's data. */ class LOG4CXX_EXPORT XMLDOMDocument : virtual public XMLDOMNode { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(XMLDOMDocument) virtual void load(const File& fileName) = 0; virtual XMLDOMElementPtr getDocumentElement() = 0; virtual XMLDOMElementPtr getElementById(const LogString& tagName, const LogString& elementId) = 0; }; LOG4CXX_PTR_DEF(XMLDOMDocument); /** The XMLDOMNodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. XMLDOMNodeList objects in the DOM are live. The items in the XMLDOMNodeList are accessible via an integral index, starting from 0. */ class LOG4CXX_EXPORT XMLDOMNodeList : virtual public Object { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(XMLDOMNodeList) virtual int getLength() = 0; virtual XMLDOMNodePtr item(int index) = 0; }; LOG4CXX_PTR_DEF(XMLDOMNodeList); } // namespace helpers } // namespace log4cxx #endif // _LOG4CXX_HELPERS_XML_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/threadlocal.h0000644000175100001770000000416414721727031024524 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_THREAD_LOCAL_H #define _LOG4CXX_HELPERS_THREAD_LOCAL_H #include #include #if !defined(LOG4CXX_THREAD_FUNC) #if defined(_WIN32) #define LOG4CXX_THREAD_FUNC __stdcall #else #define LOG4CXX_THREAD_FUNC #endif #endif extern "C" { struct apr_threadkey_t; } namespace LOG4CXX_NS { namespace helpers { /** * This class provides thread-local variables. This class is similar in function * to java.lang.ThreadLocal. */ class LOG4CXX_EXPORT ThreadLocal { public: /** * Create new instance. */ ThreadLocal(); /** * Destructor. */ ~ThreadLocal(); /** * Sets the value in the current thread's copy of this thread-local variable. * @param priv new value. */ void set(void* priv); /** * Returns the value in the current thread's copy of this thread-local variable. * @return value of thread-local variable for the current thread. */ void* get(); private: /** * Prevent use of default copy constructor. */ ThreadLocal(const ThreadLocal&); /** * Prevent use of default assignment operator. */ ThreadLocal& operator=(const ThreadLocal&); static apr_threadkey_t* create(Pool& p); Pool p; apr_threadkey_t* key; }; } // namespace helpers } // namespace log4cxx #endif //_LOG4CXX_HELPERS_THREAD_LOCAL_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/aprinitializer.h0000644000175100001770000000575114721727031025273 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_APRINITIALIZER_H #define _LOG4CXX_HELPERS_APRINITIALIZER_H #ifndef LOG4CXX #error "aprinitializer.h should only be included by log4cxx implementation" #endif #include #include #include #include extern "C" { struct apr_threadkey_t; struct apr_pool_t; } #include #include namespace LOG4CXX_NS { namespace helpers { class FileWatchdog; class APRInitializer { public: #if LOG4CXX_ABI_VERSION <= 15 static log4cxx_time_t initialize(); #endif static apr_pool_t* getRootPool(); static log4cxx_time_t getStartTime(); static apr_threadkey_t* getTlsKey(); static bool isDestructed; /** * Register a FileWatchdog for deletion prior to termination. * FileWatchdog must be * allocated on heap and not deleted elsewhere. */ static void registerCleanup(FileWatchdog* watchdog); static void unregisterCleanup(FileWatchdog* watchdog); static void unregisterAll(); /** * Store a single instance type ObjectPtr for deletion prior to termination */ template static void setUnique(const std::shared_ptr& pObject) { getInstance().addObject(typeid(T).hash_code(), pObject); } /** * Fetch or add a single instance type ObjectPtr for deletion prior to termination */ template static std::shared_ptr getOrAddUnique(std::function creator) { return cast(getInstance().findOrAddObject(typeid(T).hash_code(), creator)); } private: // Constructors friend class helpers::WideLife; APRInitializer(); APRInitializer(const APRInitializer&) = delete; APRInitializer& operator=(const APRInitializer&) = delete; private: // Modifiers void addObject(size_t key, const ObjectPtr& pObject); const ObjectPtr& findOrAddObject(size_t key, std::function creator); void stopWatchDogs(); private: // Attributes LOG4CXX_DECLARE_PRIVATE_MEMBER_PTR(APRInitializerPrivate, m_priv) private: // Class methods static APRInitializer& getInstance(); public: // Destructor ~APRInitializer(); }; } // namespace helpers } // namespace log4cxx #endif //_LOG4CXX_HELPERS_APRINITIALIZER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/stringhelper.h0000644000175100001770000000377514721727031024757 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_STRING_HELPER_H #define _LOG4CXX_HELPERS_STRING_HELPER_H #include #include namespace LOG4CXX_NS { namespace helpers { class Pool; /** String manipulation routines */ class LOG4CXX_EXPORT StringHelper { public: static LogString trim(const LogString& s); static bool startsWith(const LogString& s, const LogString& suffix); static bool endsWith(const LogString& s, const LogString& suffix); static bool equalsIgnoreCase(const LogString& s1, const logchar* upper, const logchar* lower); static bool equalsIgnoreCase(const LogString& s1, const LogString& upper, const LogString& lower); static int toInt(const LogString& s); static int64_t toInt64(const LogString& s); static void toString(int i, LOG4CXX_NS::helpers::Pool& pool, LogString& dst); static void toString(int64_t i, LOG4CXX_NS::helpers::Pool& pool, LogString& dst); static void toString(size_t i, LOG4CXX_NS::helpers::Pool& pool, LogString& dst); static void toString(bool val, LogString& dst); static LogString toLowerCase(const LogString& s); static LogString format(const LogString& pattern, const std::vector& params); }; } } #endif //_LOG4CXX_HELPERS_STRING_HELPER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/helpers/outputstream.h0000644000175100001770000000316314721727031025014 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_HELPERS_OUTPUTSTREAM_H #define _LOG4CXX_HELPERS_OUTPUTSTREAM_H #include namespace LOG4CXX_NS { namespace helpers { class ByteBuffer; /** * Abstract class for writing to character streams. */ class LOG4CXX_EXPORT OutputStream : public Object { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(OutputStream) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(OutputStream) END_LOG4CXX_CAST_MAP() protected: OutputStream(); virtual ~OutputStream(); public: virtual void close(Pool& p) = 0; virtual void flush(Pool& p) = 0; virtual void write(ByteBuffer& buf, Pool& p) = 0; private: OutputStream(const OutputStream&); OutputStream& operator=(const OutputStream&); }; LOG4CXX_PTR_DEF(OutputStream); } // namespace helpers } //namespace log4cxx #endif //_LOG4CXX_HELPERS_OUTPUTSTREAM_H apache-log4cxx-1.3.1/src/main/include/log4cxx/writerappender.h0000644000175100001770000001347014721727031023633 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_WRITER_APPENDER_H #define _LOG4CXX_WRITER_APPENDER_H #include #include #include namespace LOG4CXX_NS { namespace helpers { class Transcoder; } /** WriterAppender appends log events to a standard output stream */ class LOG4CXX_EXPORT WriterAppender : public AppenderSkeleton { protected: struct WriterAppenderPriv; public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(WriterAppender) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(WriterAppender) LOG4CXX_CAST_ENTRY_CHAIN(AppenderSkeleton) END_LOG4CXX_CAST_MAP() /** This default constructor does nothing.*/ WriterAppender(); protected: WriterAppender(const LayoutPtr& layout, LOG4CXX_NS::helpers::WriterPtr& writer); WriterAppender(const LayoutPtr& layout); WriterAppender(std::unique_ptr priv); public: ~WriterAppender(); /** Derived appenders should override this method if option structure requires it. */ void activateOptions(helpers::Pool& pool) override; /** If the ImmediateFlush option is set to true, the appender will flush at the end of each write. This is the default behavior. If the option is set to false, then the underlying stream can defer writing to physical medium to a later time.

Avoiding the flush operation at the end of each append results in a performance gain of 10 to 20 percent. However, there is safety tradeoff involved in skipping flushing. Indeed, when flushing is skipped, then it is likely that the last few log events will not be recorded on disk when the application exits. This is a high price to pay even for a 20% performance gain. */ void setImmediateFlush(bool value); /** Returns value of the ImmediateFlush option. */ bool getImmediateFlush() const; /** This method is called by the AppenderSkeleton#doAppend method.

If the output stream exists and is writable then write a log statement to the output stream. Otherwise, write a single warning message to stderr.

The format of the output will depend on this appender's layout. */ void append(const spi::LoggingEventPtr& event, helpers::Pool& p) override; protected: /** This method determines if there is a sense in attempting to append.

It checks whether there is a set output target and also if there is a set layout. If these checks fail, then the boolean value false is returned. */ virtual bool checkEntryConditions() const; public: /** Close this appender instance. The underlying stream or writer is also closed.

Closed appenders cannot be reused. */ void close() override; protected: /** * Close the underlying {@link log4cxx::helpers::Writer}. * */ void closeWriter(); /** 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. */ virtual helpers::WriterPtr createWriter(helpers::OutputStreamPtr& os); public: /** The current encoding value. \sa setOption */ LogString getEncoding() const; /** Set the encoding to \c value. \sa setOption */ void setEncoding(const LogString& value); /** \copybrief AppenderSkeleton::setOption() Supported options | Supported values | Default value -------------- | ---------------- | --------------- Encoding | C,UTF-8,UTF-16,UTF-16BE,UTF-16LE,646,US-ASCII,ISO646-US,ANSI_X3.4-1968,ISO-8859-1,ISO-LATIN-1 | UTF-8 \sa AppenderSkeleton::setOption() */ void setOption(const LogString& option, const LogString& value) override; /**

Send log output to \c writer which must be open and be writable.

The helpers::Writer will be closed when the appender instance is closed. WARNING: Logging to an unopened Writer will fail. @param writer An already opened Writer. */ void setWriter(const LOG4CXX_NS::helpers::WriterPtr& writer); const LOG4CXX_NS::helpers::WriterPtr getWriter() const; bool requiresLayout() const override; protected: /** Actual writing occurs here. */ virtual void subAppend(const spi::LoggingEventPtr& event, LOG4CXX_NS::helpers::Pool& p); /** Write a footer as produced by the embedded layout's Layout#appendFooter method. */ virtual void writeFooter(LOG4CXX_NS::helpers::Pool& p); /** Write a header as produced by the embedded layout's Layout#appendHeader method. */ virtual void writeHeader(LOG4CXX_NS::helpers::Pool& p); /** * Set the writer. Mutex must already be held. */ void setWriterInternal(const LOG4CXX_NS::helpers::WriterPtr& writer); private: // // prevent copy and assignment WriterAppender(const WriterAppender&); WriterAppender& operator=(const WriterAppender&); }; LOG4CXX_PTR_DEF(WriterAppender); } //namespace log4cxx #endif //_LOG4CXX_WRITER_APPENDER_H apache-log4cxx-1.3.1/src/main/include/log4cxx/nt/0000755000175100001770000000000014721727031021043 5ustar runnerdockerapache-log4cxx-1.3.1/src/main/include/log4cxx/nt/outputdebugstringappender.h0000644000175100001770000000300314721727031026525 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_NT_OUTPUTDEBUGSTRING_APPENDER_HEADER_ #define _LOG4CXX_NT_OUTPUTDEBUGSTRING_APPENDER_HEADER_ #include namespace LOG4CXX_NS { namespace nt { class LOG4CXX_EXPORT OutputDebugStringAppender : public AppenderSkeleton { public: DECLARE_LOG4CXX_OBJECT(OutputDebugStringAppender) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(OutputDebugStringAppender) LOG4CXX_CAST_ENTRY_CHAIN(AppenderSkeleton) END_LOG4CXX_CAST_MAP() OutputDebugStringAppender(); bool requiresLayout() const override { return true; } void close() override {} void append(const spi::LoggingEventPtr& event, helpers::Pool& p) override; }; } } #endif //_LOG4CXX_NT_OUTPUTDEBUGSTRING_APPENDER_HEADER_ apache-log4cxx-1.3.1/src/main/include/log4cxx/nt/nteventlogappender.h0000644000175100001770000000717714721727031025134 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_NT_EVENT_LOG_APPENDER_HEADER_ #define _LOG4CXX_NT_EVENT_LOG_APPENDER_HEADER_ #include namespace LOG4CXX_NS { namespace nt { /** * Appends log events to NT EventLog. */ class LOG4CXX_EXPORT NTEventLogAppender : public AppenderSkeleton { public: DECLARE_LOG4CXX_OBJECT(NTEventLogAppender) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(NTEventLogAppender) LOG4CXX_CAST_ENTRY_CHAIN(AppenderSkeleton) END_LOG4CXX_CAST_MAP() NTEventLogAppender(); NTEventLogAppender(const LogString& server, const LogString& log, const LogString& source, const LayoutPtr& layout); virtual ~NTEventLogAppender(); /** \copybrief AppenderSkeleton::activateOptions() Calls RegisterEventSource. */ void activateOptions(helpers::Pool& p) override; void close() override; /** \copybrief AppenderSkeleton::setOption() Supported options | Supported values | Default value -------------- | ---------------- | --------------- Server | (\ref winapi "1") | NULL Source | (\ref winapi "1") | - Log | (\ref eventLog "2") | Application \anchor winapi (1) Passed to the Win32 API method RegisterEventSource. \anchor eventLog (2) An event log name. \sa AppenderSkeleton::setOption() */ void setOption(const LogString& option, const LogString& value) override; /** * The SocketAppender does not use a layout. Hence, this method * returns false. * */ bool requiresLayout() const override { return true; } void setSource(const LogString& source); const LogString& getSource() const; void setLog(const LogString& log); const LogString& getLog() const; void setServer(const LogString& server); const LogString& getServer() const; protected: // // these typedef are proxies for the real Win32 definitions // and need to be cast to the global definitions before // use with a Win32 API call typedef void SID; typedef void* HANDLE; void append(const spi::LoggingEventPtr& event, helpers::Pool& p) override; static unsigned short getEventType(const spi::LoggingEventPtr& event); static unsigned short getEventCategory(const spi::LoggingEventPtr& event); /* * Add this source with appropriate configuration keys to the registry. */ void addRegistryInfo(); struct NTEventLogAppenderPrivate; static LogString getErrorString(const LogString& function); private: NTEventLogAppender(const NTEventLogAppender&); NTEventLogAppender& operator=(const NTEventLogAppender&); }; // class NTEventLogAppender LOG4CXX_PTR_DEF(NTEventLogAppender); } // namespace nt } // namespace log4cxx #endif //_LOG4CXX_NT_EVENT_LOG_APPENDER_HEADER_ apache-log4cxx-1.3.1/src/main/include/log4cxx/nt/EventLogCategories.mc0000644000175100001770000000201614721727031025114 0ustar runnerdocker; ; 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. ; MessageId=0x0001 Language=English Fatal . MessageId=0x0002 Language=English Error . MessageId=0x0003 Language=English Warn . MessageId=0x0004 Language=English Info . MessageId=0x0005 Language=English Debug . MessageId=0x1000 Language=English %1 . apache-log4cxx-1.3.1/src/main/include/log4cxx/logstring.h0000644000175100001770000000413114721727031022602 0ustar runnerdocker/* * 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. */ #ifndef _LOG4CXX_STRING_H #define _LOG4CXX_STRING_H #include #include #if (LOG4CXX_LOGCHAR_IS_WCHAR + LOG4CXX_LOGCHAR_IS_UTF8 + LOG4CXX_LOGCHAR_IS_UNICHAR)>1 #error only one of LOG4CXX_LOGCHAR_IS_WCHAR, LOG4CXX_LOGCHAR_IS_UTF8 or LOG4CXX_LOGCHAR_IS_UNICHAR may be true #endif #if LOG4CXX_CFSTRING_API extern "C" { typedef const struct __CFString* CFStringRef; } #endif namespace LOG4CXX_NS { #if LOG4CXX_LOGCHAR_IS_UNICHAR || LOG4CXX_UNICHAR_API typedef unsigned short UniChar; #endif #if LOG4CXX_LOGCHAR_IS_WCHAR typedef wchar_t logchar; #define LOG4CXX_STR(str) L ## str #endif #if LOG4CXX_LOGCHAR_IS_UTF8 typedef char logchar; #if LOG4CXX_CHARSET_EBCDIC #define LOG4CXX_STR(str) LOG4CXX_NS::helpers::Transcoder::decode(str) #else #define LOG4CXX_STR(str) str #endif #endif #if LOG4CXX_LOGCHAR_IS_UNICHAR typedef UniChar logchar; #define LOG4CXX_STR(str) LOG4CXX_NS::helpers::Transcoder::decode(str) #endif typedef std::basic_string LogString; } #if !defined(LOG4CXX_EOL) #if defined(_WIN32) #define LOG4CXX_EOL LOG4CXX_STR("\x0D\x0A") #else #define LOG4CXX_EOL LOG4CXX_STR("\x0A") #endif #endif #if LOG4CXX_LOGCHAR_IS_UNICHAR || (LOG4CXX_LOGCHAR_IS_UTF8 || LOG4CXX_CHARSET_EBCDIC) #include #endif #endif //_LOG4CXX_STRING_H apache-log4cxx-1.3.1/src/main/resources/0000755000175100001770000000000014721727031017421 5ustar runnerdockerapache-log4cxx-1.3.1/src/main/resources/MSG00001.bin0000644000175100001770000000024414721727031021122 0ustar runnerdockerTrace Debug Info Warn Error Fatal %1 apache-log4cxx-1.3.1/src/main/resources/log4cxx.rc0000644000175100001770000000776114721727031021352 0ustar runnerdocker// // 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. // // // Message file include // LANGUAGE 0x9,0x1 1 11 MSG00001.bin // Microsoft Visual C++ generated resource script. // #include "windows.h" #define APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 2 resource. // //#include "afxres.h" ///////////////////////////////////////////////////////////////////////////// #undef APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // English (U.S.) resources #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) #ifdef _WIN32 LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US #pragma code_page(1252) #endif //_WIN32 #ifdef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // TEXTINCLUDE // 1 TEXTINCLUDE BEGIN "resource.h\0" END 2 TEXTINCLUDE BEGIN "#include ""afxres.h""\r\n" "\0" END 3 TEXTINCLUDE BEGIN "\r\n" "\0" END #endif // APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // Version // #include VS_VERSION_INFO VERSIONINFO FILEVERSION INFO_FILE_VERSION_LIST PRODUCTVERSION INFO_PRODUCT_VERSION_LIST FILEFLAGSMASK 0x17L #ifdef _DEBUG FILEFLAGS 0x1L #else FILEFLAGS 0x0L #endif FILEOS 0x4L FILETYPE 0x2L FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN VALUE "CompanyName", "Apache Software Foundation" VALUE "FileDescription", "Apache log4cxx" VALUE "FileVersion", INFO_FILE_VERSION_STRING VALUE "InternalName", "log4cxx" VALUE "LegalCopyright", "Licensed to the Apache Software Foundation (ASF) under one or more\ncontributor license agreements. See the NOTICE file distributed with\nthis work for additional information regarding copyright ownership.\nThe ASF licenses this file to You under the Apache License, Version 2.0\n(the ""License""); you may not use this file except in compliance with\nthe License. You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an ""AS IS"" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License." VALUE "OriginalFilename", "log4cxx.dll" VALUE "ProductName", "Apache log4cxx" VALUE "ProductVersion", INFO_PRODUCT_VERSION_STRING END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END #endif // English (U.S.) resources ///////////////////////////////////////////////////////////////////////////// #ifndef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 3 resource. // ///////////////////////////////////////////////////////////////////////////// #endif // not APSTUDIO_INVOKED apache-log4cxx-1.3.1/src/main/resources/CMakeLists.txt0000644000175100001770000000155614721727031022170 0ustar runnerdocker# # 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. # # Configure if(MSVC) target_sources(log4cxx PRIVATE ../resources/log4cxx.rc ) endif() apache-log4cxx-1.3.1/src/main/resources/EventLogCategories.mc0000644000175100001770000000203214721727031023470 0ustar runnerdocker; ; 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. ; MessageId=1 Language=English Trace . MessageId=2 Language=English Debug . MessageId=3 Language=English Info . MessageId=4 Language=English Warn . MessageId=5 Language=English Error . MessageId=6 Language=English Fatal . MessageId=0x1000 Language=English %1 . apache-log4cxx-1.3.1/src/main/mock-apple/0000755000175100001770000000000014721727031017437 5ustar runnerdockerapache-log4cxx-1.3.1/src/main/mock-apple/CoreFoundation/0000755000175100001770000000000014721727031022356 5ustar runnerdockerapache-log4cxx-1.3.1/src/main/mock-apple/CoreFoundation/CFString.h0000644000175100001770000000165314721727031024213 0ustar runnerdocker/* Mocked CFString.h */ #include #if !defined(__COREFOUNDATION_CFSTRING__) #define __COREFOUNDATION_CFSTRING__ 1 extern "C" { typedef unsigned short UniChar; typedef long CFIndex; typedef struct __CFRange { CFIndex location; CFIndex length; } CFRange; typedef const struct __CFString* CFStringRef; typedef const struct __CFAllocator* CFAllocatorRef; typedef uint32_t CFStringEncoding; CFRange CFRangeMake(CFIndex loc, CFIndex len); CFIndex CFStringGetLength(CFStringRef theString); void CFStringGetCharacters(CFStringRef theString, CFRange range, UniChar *buffer); CFStringRef CFStringCreateWithCharacters(CFAllocatorRef alloc, const UniChar *chars, CFIndex numChars); CFStringRef CFStringCreateWithCString(CFAllocatorRef alloc, const char *cStr, CFStringEncoding encoding); #define kCFAllocatorDefault 0 #define CFSTR(cStr) CFStringCreateWithCString(kCFAllocatorDefault, cStr, 0) } #endif /* ! __COREFOUNDATION_CFSTRING__ */ apache-log4cxx-1.3.1/src/main/mock-apple/CFString.cpp0000644000175100001770000000330514721727031021623 0ustar runnerdocker/* Mocked CFString implementation */ #include "CoreFoundation/CFString.h" #include #include #include namespace { int throw_out_of_mem(int status) { throw std::bad_alloc(); return status; } apr_pool_t* getStringPool() { struct cfstring_pool { apr_pool_t* ptr = 0; cfstring_pool() { apr_pool_create_core_ex(&ptr, throw_out_of_mem, NULL); } ~cfstring_pool() { apr_pool_destroy(ptr); } }; static LOG4CXX_NS::helpers::WideLife pool; return pool.ptr; } } // namespace extern "C" { CFRange CFRangeMake(CFIndex loc, CFIndex len) { CFRange result; result.location = loc; result.length = len; return result; } CFIndex CFStringGetLength(CFStringRef theString) { UniChar* data = (UniChar*)theString; CFIndex result = 0; while (data[result]) ++result; return result; } void CFStringGetCharacters(CFStringRef theString, CFRange range, UniChar *buffer) { UniChar* data = (UniChar*)theString; CFIndex index = 0; while (index < range.length) { *buffer = data[range.location + index]; ++index; ++buffer; } } CFStringRef CFStringCreateWithCharacters(CFAllocatorRef alloc, const UniChar *chars, CFIndex numChars) { UniChar* result = (UniChar*)apr_palloc(getStringPool(), (numChars + 1) * sizeof(UniChar)); result[numChars] = 0; for (UniChar* p = result; 0 < numChars; --numChars) *p++ = *chars++; return (CFStringRef)result; } CFStringRef CFStringCreateWithCString(CFAllocatorRef alloc, const char *cStr, CFStringEncoding encoding) { UniChar* result = (UniChar*)apr_palloc(getStringPool(), (strlen(cStr) + 1) * sizeof(UniChar)); for (UniChar *p = result; *p++ = *cStr++;) ; return (CFStringRef)result; } } // extern "C" apache-log4cxx-1.3.1/src/main/mock-apple/CMakeLists.txt0000644000175100001770000000232614721727031022202 0ustar runnerdocker# # 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. # # Build the MockCoreFoundation library add_library(MockCoreFoundation STATIC CFString.cpp) target_compile_definitions(MockCoreFoundation PRIVATE ${APR_COMPILE_DEFINITIONS}) target_include_directories(MockCoreFoundation INTERFACE PRIVATE ${APR_INCLUDE_DIR}) # Add to log4cxx as a dependency target_link_libraries(log4cxx PRIVATE MockCoreFoundation) target_include_directories(log4cxx INTERFACE PRIVATE $) apache-log4cxx-1.3.1/src/main/CMakeLists.txt0000644000175100001770000000262714721727031020156 0ustar runnerdocker# # 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. # add_subdirectory(include) add_subdirectory(cpp) add_subdirectory(cpp-qt) add_subdirectory(resources) # setup include directories include(GNUInstallDirs) target_include_directories(log4cxx PUBLIC $ $ ) if(LOG4CXX_CFSTRING) if(APPLE) target_link_libraries(log4cxx PUBLIC "-framework CoreFoundation") else() add_subdirectory(mock-apple) endif() endif() if(LOG4CXX_QT_SUPPORT) target_include_directories(log4cxx-qt PUBLIC $ ) endif(LOG4CXX_QT_SUPPORT) apache-log4cxx-1.3.1/src/main/cpp/0000755000175100001770000000000014721727031016171 5ustar runnerdockerapache-log4cxx-1.3.1/src/main/cpp/filedatepatternconverter.cpp0000644000175100001770000000260114721727031023777 0ustar runnerdocker/* * 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. */ #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::pattern; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; PatternConverterPtr FileDatePatternConverter::newInstance( const std::vector& options) { if (options.size() == 0) { std::vector altOptions; altOptions.push_back(LOG4CXX_STR("yyyy-MM-dd")); return DatePatternConverter::newInstance(altOptions); } return DatePatternConverter::newInstance(options); } apache-log4cxx-1.3.1/src/main/cpp/classregistration.cpp0000644000175100001770000000210014721727031022426 0ustar runnerdocker/* * 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. */ #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; ClassRegistration::ClassRegistration(ClassAccessor accessor) { Class::registerClass((*accessor)()); } apache-log4cxx-1.3.1/src/main/cpp/outputstream.cpp0000644000175100001770000000206114721727031021450 0ustar runnerdocker/* * 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. */ #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(OutputStream) OutputStream::OutputStream() { } OutputStream::~OutputStream() { } apache-log4cxx-1.3.1/src/main/cpp/zipcompressaction.cpp0000644000175100001770000000773514721727031022465 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::rolling; using namespace LOG4CXX_NS::helpers; #define priv static_cast(m_priv.get()) struct ZipCompressAction::ZipCompressActionPrivate : public ActionPrivate { ZipCompressActionPrivate( const File& toRename, const File& renameTo, bool deleteSource): source(toRename), destination(renameTo), deleteSource(deleteSource) {} const File source; const File destination; bool deleteSource; bool throwIOExceptionOnForkFailure = true; }; IMPLEMENT_LOG4CXX_OBJECT(ZipCompressAction) ZipCompressAction::ZipCompressAction(const File& src, const File& dest, bool del) : Action(std::make_unique( src, dest, del)) { } bool ZipCompressAction::execute(LOG4CXX_NS::helpers::Pool& p) const { if (!priv->source.exists(p)) { return false; } apr_pool_t* aprpool = p.getAPRPool(); apr_procattr_t* attr; apr_status_t stat = apr_procattr_create(&attr, aprpool); if (stat != APR_SUCCESS) { throw IOException(stat); } stat = apr_procattr_io_set(attr, APR_NO_PIPE, APR_NO_PIPE, APR_FULL_BLOCK); if (stat != APR_SUCCESS) { throw IOException(stat); } stat = apr_procattr_cmdtype_set(attr, APR_PROGRAM_PATH); if (stat != APR_SUCCESS) { throw IOException(stat); } // // redirect the child's error stream to this processes' error stream // apr_file_t* child_err; stat = apr_file_open_stderr(&child_err, aprpool); if (stat == APR_SUCCESS) { stat = apr_procattr_child_err_set(attr, child_err, NULL); if (stat != APR_SUCCESS) { throw IOException(stat); } } const char** args = (const char**) apr_palloc(aprpool, 5 * sizeof(*args)); int i = 0; args[i++] = "zip"; args[i++] = "-q"; args[i++] = Transcoder::encode(priv->destination.getPath(), p); args[i++] = Transcoder::encode(priv->source.getPath(), p); args[i++] = NULL; if (priv->destination.exists(p)) { priv->destination.deleteFile(p); } apr_proc_t pid; stat = apr_proc_create(&pid, "zip", args, NULL, attr, aprpool); if (stat != APR_SUCCESS) { LogLog::warn(LOG4CXX_STR("Failed to fork zip during log rotation; leaving log file uncompressed")); if (priv->throwIOExceptionOnForkFailure) throw IOException(LOG4CXX_STR("zip"), stat); /* If we fail here (to create the zip child process), * skip the compression and consider the rotation to be * otherwise successful. The caller has already rotated * the log file (`source` here refers to the * uncompressed, rotated path, and `destination` the * same path with `.zip` appended). Remove the empty * destination file and leave source as-is. */ return true; } int exitCode; apr_proc_wait(&pid, &exitCode, NULL, APR_WAIT); if (exitCode != APR_SUCCESS) { throw IOException(exitCode); } if (priv->deleteSource) { priv->source.deleteFile(p); } return true; } void ZipCompressAction::setThrowIOExceptionOnForkFailure(bool throwIO){ priv->throwIOExceptionOnForkFailure = throwIO; } apache-log4cxx-1.3.1/src/main/cpp/logmanager.cpp0000644000175100001770000001334314721727031021015 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(DefaultRepositorySelector) void* LogManager::guard = 0; RepositorySelectorPtr LogManager::getRepositorySelector() { auto result = APRInitializer::getOrAddUnique( []() -> ObjectPtr { LoggerRepositoryPtr hierarchy = Hierarchy::create(); return std::make_shared(hierarchy); } ); return result; } void LogManager::setRepositorySelector(spi::RepositorySelectorPtr selector, void* guard1) { if ((LogManager::guard != 0) && (LogManager::guard != guard1)) { throw IllegalArgumentException(LOG4CXX_STR("Attempted to reset the LoggerFactory without possessing the guard.")); } if (selector == 0) { throw IllegalArgumentException(LOG4CXX_STR("RepositorySelector must be non-null.")); } LogManager::guard = guard1; APRInitializer::setUnique(selector); } LoggerRepositoryPtr LogManager::getLoggerRepository() { return getRepositorySelector()->getLoggerRepository(); } LoggerPtr LogManager::getRootLogger() { // Delegate the actual manufacturing of the logger to the logger repository. auto r = getLoggerRepository(); r->ensureIsConfigured(std::bind(DefaultConfigurator::configure, r)); return r->getRootLogger(); } /** Retrieve the appropriate Logger instance. */ LoggerPtr LogManager::getLoggerLS(const LogString& name) { auto r = getLoggerRepository(); r->ensureIsConfigured(std::bind(DefaultConfigurator::configure, r)); return r->getLogger(name); } /** Retrieve the appropriate Logger instance. */ LoggerPtr LogManager::getLoggerLS(const LogString& name, const spi::LoggerFactoryPtr& factory) { // Delegate the actual manufacturing of the logger to the logger repository. auto r = getLoggerRepository(); r->ensureIsConfigured(std::bind(DefaultConfigurator::configure, r)); return r->getLogger(name, factory); } LoggerPtr LogManager::getLogger(const std::string& name) { LOG4CXX_DECODE_CHAR(n, name); return getLoggerLS(n); } LoggerPtr LogManager::getLogger(const std::string& name, const spi::LoggerFactoryPtr& factory) { LOG4CXX_DECODE_CHAR(n, name); return getLoggerLS(n, factory); } LoggerPtr LogManager::exists(const std::string& name) { LOG4CXX_DECODE_CHAR(n, name); return existsLS(n); } #if LOG4CXX_WCHAR_T_API LoggerPtr LogManager::getLogger(const std::wstring& name) { LOG4CXX_DECODE_WCHAR(n, name); return getLoggerLS(n); } LoggerPtr LogManager::getLogger(const std::wstring& name, const spi::LoggerFactoryPtr& factory) { LOG4CXX_DECODE_WCHAR(n, name); return getLoggerLS(n, factory); } LoggerPtr LogManager::exists(const std::wstring& name) { LOG4CXX_DECODE_WCHAR(n, name); return existsLS(n); } #endif #if LOG4CXX_UNICHAR_API LoggerPtr LogManager::getLogger(const std::basic_string& name) { LOG4CXX_DECODE_UNICHAR(n, name); return getLoggerLS(n); } LoggerPtr LogManager::getLogger(const std::basic_string& name, const spi::LoggerFactoryPtr& factory) { LOG4CXX_DECODE_UNICHAR(n, name); return getLoggerLS(n, factory); } LoggerPtr LogManager::exists(const std::basic_string& name) { LOG4CXX_DECODE_UNICHAR(n, name); return existsLS(n); } #endif #if LOG4CXX_CFSTRING_API LoggerPtr LogManager::getLogger(const CFStringRef& name) { LOG4CXX_DECODE_CFSTRING(n, name); return getLoggerLS(n); } LoggerPtr LogManager::getLogger(const CFStringRef& name, const spi::LoggerFactoryPtr& factory) { LOG4CXX_DECODE_CFSTRING(n, name); return getLoggerLS(n, factory); } LoggerPtr LogManager::exists(const CFStringRef& name) { LOG4CXX_DECODE_CFSTRING(n, name); return existsLS(n); } #endif LoggerPtr LogManager::existsLS(const LogString& name) { return getLoggerRepository()->exists(name); } LoggerList LogManager::getCurrentLoggers() { return getLoggerRepository()->getCurrentLoggers(); } void LogManager::shutdown() { APRInitializer::unregisterAll(); getLoggerRepository()->shutdown(); } void LogManager::resetConfiguration() { getLoggerRepository()->resetConfiguration(); } bool LogManager::removeLogger(const LogString& name, bool ifNotUsed) { #if LOG4CXX_ABI_VERSION <= 15 bool result = false; if (auto r = dynamic_cast(getLoggerRepository().get())) result = r->removeLogger(name, ifNotUsed); return result; #else return getLoggerRepository()->removeLogger(name, ifNotUsed); #endif } apache-log4cxx-1.3.1/src/main/cpp/timezone.cpp0000644000175100001770000001435214721727031020534 0ustar runnerdocker/* * 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. */ #define __STDC_CONSTANT_MACROS #include #include #include #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT( TimeZone ) namespace LOG4CXX_NS { namespace helpers { namespace TimeZoneImpl { /** Time zone object that represents GMT. */ class GMTTimeZone : public TimeZone { public: /** Class factory. */ static const TimeZonePtr& getInstance() { static WideLife tz = std::make_shared(); return tz; } /** Explode time to human readable form. */ log4cxx_status_t explode( apr_time_exp_t* result, log4cxx_time_t input ) const { apr_status_t stat; // APR 1.1 and early mishandles microseconds on dates // before 1970, APR bug 32520 if (LOG4CXX_UNLIKELY(input < 0 && apr_time_usec(input) < 0)) { apr_time_t floorTime = (apr_time_sec(input) - 1) * APR_USEC_PER_SEC; stat = apr_time_exp_gmt(result, floorTime); result->tm_usec = (int) (input - floorTime); } else { stat = apr_time_exp_gmt( result, input ); } return stat; } GMTTimeZone() : TimeZone( LOG4CXX_STR("GMT") ) { } }; /** Time zone object that represents GMT. */ class LocalTimeZone : public TimeZone { public: /** Class factory. */ static const TimeZonePtr& getInstance() { static WideLife tz = std::make_shared(); return tz; } /** Explode time to human readable form. */ log4cxx_status_t explode( apr_time_exp_t* result, log4cxx_time_t input ) const { apr_status_t stat; // APR 1.1 and early mishandles microseconds on dates // before 1970, APR bug 32520 if (LOG4CXX_UNLIKELY(input < 0 && apr_time_usec(input) < 0)) { apr_time_t floorTime = (apr_time_sec(input) - 1) * APR_USEC_PER_SEC; stat = apr_time_exp_lt(result, floorTime); result->tm_usec = (int) (input - floorTime); } else { stat = apr_time_exp_lt( result, input ); } return stat; } LocalTimeZone() : TimeZone( getTimeZoneName() ) { } private: static const LogString getTimeZoneName() { const int MAX_TZ_LENGTH = 255; char tzName[MAX_TZ_LENGTH]; apr_size_t tzLength; apr_time_exp_t tm; apr_time_exp_lt(&tm, 0); apr_strftime(tzName, &tzLength, MAX_TZ_LENGTH, "%Z", &tm); if (tzLength == 0) { apr_strftime(tzName, &tzLength, MAX_TZ_LENGTH, "%z", &tm); } tzName[tzLength] = 0; LogString retval; LOG4CXX_NS::helpers::Transcoder::decode(tzName, retval); return retval; } }; /** Time zone object that represents a fixed offset from GMT. */ class FixedTimeZone : public TimeZone { public: FixedTimeZone( const LogString& name, apr_int32_t offset1 ) : TimeZone( name ), offset( offset1 ) { } /** Explode time to human readable form. */ log4cxx_status_t explode( apr_time_exp_t* result, log4cxx_time_t input ) const { apr_status_t stat; // APR 1.1 and early mishandles microseconds on dates // before 1970, APR bug 32520 if (LOG4CXX_UNLIKELY(input < 0 && apr_time_usec(input) < 0)) { apr_time_t floorTime = (apr_time_sec(input) - 1) * APR_USEC_PER_SEC; stat = apr_time_exp_tz(result, floorTime, offset); result->tm_usec = (int) (input - floorTime); } else { stat = apr_time_exp_tz( result, input, offset ); } return stat; } private: const apr_int32_t offset; }; } } } TimeZone::TimeZone( const LogString& id1 ) : id( id1 ) { } TimeZone::~TimeZone() { } const TimeZonePtr& TimeZone::getDefault() { return LOG4CXX_NS::helpers::TimeZoneImpl::LocalTimeZone::getInstance(); } const TimeZonePtr& TimeZone::getGMT() { return LOG4CXX_NS::helpers::TimeZoneImpl::GMTTimeZone::getInstance(); } const TimeZonePtr TimeZone::getTimeZone( const LogString& id ) { const logchar gmt[] = { 0x47, 0x4D, 0x54, 0 }; if ( id == gmt ) { return LOG4CXX_NS::helpers::TimeZoneImpl::GMTTimeZone::getInstance(); } if ( id.length() >= 5 && id.substr( 0, 3 ) == gmt ) { int hours = 0; int minutes = 0; int sign = 1; if (id[3] == 0x2D /* '-' */) { sign = -1; } LogString off( id.substr( 4 ) ); if ( id.length() >= 7 ) { size_t colonPos = off.find( 0x3A /* ':' */); if ( colonPos == LogString::npos ) { minutes = StringHelper::toInt(off.substr(off.length() - 2)); hours = StringHelper::toInt(off.substr(0, off.length() - 2)); } else { minutes = StringHelper::toInt(off.substr(colonPos + 1)); hours = StringHelper::toInt(off.substr(0, colonPos)); } } else { hours = StringHelper::toInt(off); } LogString s(gmt); Pool p; LogString hh; StringHelper::toString(hours, p, hh); if (sign > 0) { s.append(1, (logchar) 0x2B /* '+' */); } else { s.append(1, (logchar) 0x2D /* '-' */); } if (hh.length() == 1) { s.append(1, (logchar) 0x30 /* '0' */); } s.append(hh); s.append(1, (logchar) 0x3A /*' :' */); LogString mm; StringHelper::toString(minutes, p, mm); if (mm.length() == 1) { s.append(1, (logchar) 0x30 /* '0' */); } s.append(mm); apr_int32_t offset = sign * (hours * 3600 + minutes * 60); return std::make_shared( s, offset ); } const TimeZonePtr& ltz = getDefault(); if ( ltz->getID() == id ) { return ltz; } return getGMT(); } apache-log4cxx-1.3.1/src/main/cpp/integerpatternconverter.cpp0000644000175100001770000000324514721727031023664 0ustar runnerdocker/* * 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. */ #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::pattern; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(IntegerPatternConverter) IntegerPatternConverter::IntegerPatternConverter() : PatternConverter(LOG4CXX_STR("Integer"), LOG4CXX_STR("integer")) { } PatternConverterPtr IntegerPatternConverter::newInstance( const std::vector& /* options */) { static WideLife instance = std::make_shared(); return instance; } void IntegerPatternConverter::format( const ObjectPtr& obj, LogString& toAppendTo, Pool& p) const { IntegerPtr i = LOG4CXX_NS::cast(obj); if (i != NULL) { StringHelper::toString(i->intValue(), p, toAppendTo); } } apache-log4cxx-1.3.1/src/main/cpp/defaultloggerfactory.cpp0000644000175100001770000000247114721727031023115 0ustar runnerdocker/* * 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. */ #if LOG4CXX_ABI_VERSION <= 15 #include #else #include #endif using namespace LOG4CXX_NS; using namespace spi; #if LOG4CXX_ABI_VERSION <= 15 IMPLEMENT_LOG4CXX_OBJECT(DefaultLoggerFactory) LoggerPtr DefaultLoggerFactory::makeNewLoggerInstance( helpers::Pool& pool, const LogString& name) const { return std::make_shared(name); } #endif LoggerPtr LoggerFactory::makeNewLoggerInstance(const LogString& name) const { return std::make_shared(name); } apache-log4cxx-1.3.1/src/main/cpp/datagrampacket.cpp0000644000175100001770000000746714721727031021663 0ustar runnerdocker/* * 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. */ #include #include using namespace LOG4CXX_NS::helpers; struct DatagramPacket::DatagramPacketPriv { DatagramPacketPriv(void* buf1, int length1) : buf(buf1), offset(0), length(length1), address(), port(0) { } DatagramPacketPriv(void* buf1, int length1, InetAddressPtr address1, int port1) : buf(buf1), offset(0), length(length1), address(address1), port(port1) { } DatagramPacketPriv(void* buf1, int offset1, int length1) : buf(buf1), offset(offset1), length(length1), address(), port(0) { } DatagramPacketPriv(void* buf1, int offset1, int length1, InetAddressPtr address1, int port1) : buf(buf1), offset(offset1), length(length1), address(address1), port(port1) { } /** the data for this packet. */ void* buf; /** The offset of the data for this packet. */ int offset; /** The length of the data for this packet. */ int length; /** The IP address for this packet. */ InetAddressPtr address; /** The UDP port number of the remote host. */ int port; }; IMPLEMENT_LOG4CXX_OBJECT(DatagramPacket) /** Constructs a DatagramPacket for receiving packets of length length. */ DatagramPacket::DatagramPacket(void* buf1, int length1) : m_priv(std::make_unique(buf1, length1)) { } /** Constructs a datagram packet for sending packets of length length/ to the specified port number on the specified host. */ DatagramPacket::DatagramPacket(void* buf1, int length1, InetAddressPtr address1, int port1) : m_priv(std::make_unique(buf1, length1, address1, port1)) { } /** Constructs a DatagramPacket for receiving packets of length length, specifying an offset into the buffer. */ DatagramPacket::DatagramPacket(void* buf1, int offset1, int length1) : m_priv(std::make_unique(buf1, offset1, length1)) { } /** Constructs a datagram packet for sending packets of length length with offset offset to the specified port number on the specified host. */ DatagramPacket::DatagramPacket(void* buf1, int offset1, int length1, InetAddressPtr address1, int port1) : m_priv(std::make_unique(buf1, offset1, length1, address1, port1)) { } DatagramPacket::~DatagramPacket() { } InetAddressPtr DatagramPacket::getAddress() const { return m_priv->address; } void* DatagramPacket::getData() const { return m_priv->buf; } int DatagramPacket::getLength() const { return m_priv->length; } int DatagramPacket::getOffset() const { return m_priv->offset; } int DatagramPacket::getPort() const { return m_priv->port; } void DatagramPacket::setAddress(InetAddressPtr address1) { m_priv->address = address1; } void DatagramPacket::setData(void* buf1) { m_priv->buf = buf1; } void DatagramPacket::setData(void* buf1, int offset1, int length1) { m_priv->buf = buf1; m_priv->offset = offset1; m_priv->length = length1; } void DatagramPacket::setLength(int length1) { m_priv->length = length1; } void DatagramPacket::setPort(int port1) { m_priv->port = port1; } apache-log4cxx-1.3.1/src/main/cpp/stringmatchfilter.cpp0000644000175100001770000000563114721727031022433 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::filter; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; #define priv static_cast(m_priv.get()) struct StringMatchFilter::StringMatchFilterPrivate : public FilterPrivate { StringMatchFilterPrivate() : FilterPrivate(), acceptOnMatch(true), stringToMatch() {} bool acceptOnMatch; LogString stringToMatch; }; IMPLEMENT_LOG4CXX_OBJECT(StringMatchFilter) StringMatchFilter::StringMatchFilter() : Filter(std::make_unique()) { } StringMatchFilter::~StringMatchFilter() {} void StringMatchFilter::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("STRINGTOMATCH"), LOG4CXX_STR("stringtomatch"))) { priv->stringToMatch = value; } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("ACCEPTONMATCH"), LOG4CXX_STR("acceptonmatch"))) { priv->acceptOnMatch = OptionConverter::toBoolean(value, priv->acceptOnMatch); } } Filter::FilterDecision StringMatchFilter::decide( const LOG4CXX_NS::spi::LoggingEventPtr& event) const { const LogString& msg = event->getRenderedMessage(); if (msg.empty() || priv->stringToMatch.empty()) { return Filter::NEUTRAL; } if ( msg.find(priv->stringToMatch) == LogString::npos ) { return Filter::NEUTRAL; } else { // we've got a match if (priv->acceptOnMatch) { return Filter::ACCEPT; } else { return Filter::DENY; } } } void StringMatchFilter::setStringToMatch(const LogString& stringToMatch1) { priv->stringToMatch.assign(stringToMatch1); } const LogString& StringMatchFilter::getStringToMatch() const { return priv->stringToMatch; } void StringMatchFilter::setAcceptOnMatch(bool acceptOnMatch1) { priv->acceptOnMatch = acceptOnMatch1; } bool StringMatchFilter::getAcceptOnMatch() const { return priv->acceptOnMatch; } apache-log4cxx-1.3.1/src/main/cpp/defaultrepositoryselector.cpp0000644000175100001770000000261214721727031024223 0ustar runnerdocker/* * 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. */ #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; struct DefaultRepositorySelector::DefaultRepositorySelectorPrivate { LoggerRepositoryPtr repository; }; DefaultRepositorySelector::DefaultRepositorySelector(const LoggerRepositoryPtr repository1) : m_priv(std::make_unique()) { m_priv->repository = repository1; } DefaultRepositorySelector::~DefaultRepositorySelector() {} LoggerRepositoryPtr DefaultRepositorySelector::getLoggerRepository() { return m_priv->repository; } apache-log4cxx-1.3.1/src/main/cpp/reader.cpp0000644000175100001770000000173414721727031020144 0ustar runnerdocker/* * 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. */ #include #include using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(Reader) Reader::Reader() { } Reader::~Reader() { } apache-log4cxx-1.3.1/src/main/cpp/fileinputstream.cpp0000644000175100001770000000566614721727031022125 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; struct FileInputStream::FileInputStreamPrivate { FileInputStreamPrivate() : fileptr(nullptr) {} Pool pool; apr_file_t* fileptr; }; IMPLEMENT_LOG4CXX_OBJECT(FileInputStream) FileInputStream::FileInputStream(const LogString& filename) : m_priv(std::make_unique()) { open(filename); } FileInputStream::FileInputStream(const logchar* filename) : m_priv(std::make_unique()) { LogString fn(filename); open(fn); } void FileInputStream::open(const LogString& filename) { apr_fileperms_t perm = APR_OS_DEFAULT; apr_int32_t flags = APR_READ; apr_status_t stat = File().setPath(filename).open(&m_priv->fileptr, flags, perm, m_priv->pool); if (stat != APR_SUCCESS) { throw IOException(filename, stat); } } FileInputStream::FileInputStream(const File& aFile) : m_priv(std::make_unique()) { apr_fileperms_t perm = APR_OS_DEFAULT; apr_int32_t flags = APR_READ; apr_status_t stat = aFile.open(&m_priv->fileptr, flags, perm, m_priv->pool); if (stat != APR_SUCCESS) { throw IOException(aFile.getName(), stat); } } FileInputStream::~FileInputStream() { if (m_priv->fileptr != NULL && !APRInitializer::isDestructed) { apr_file_close(m_priv->fileptr); } } void FileInputStream::close() { apr_status_t stat = apr_file_close(m_priv->fileptr); if (stat == APR_SUCCESS) { m_priv->fileptr = NULL; } else { throw IOException(stat); } } int FileInputStream::read(ByteBuffer& buf) { apr_size_t bytesRead = buf.remaining(); apr_status_t stat = apr_file_read(m_priv->fileptr, buf.current(), &bytesRead); int retval = -1; if (!APR_STATUS_IS_EOF(stat)) { if (stat != APR_SUCCESS) { throw IOException(stat); } buf.position(buf.position() + bytesRead); retval = (int)bytesRead; } return retval; } apache-log4cxx-1.3.1/src/main/cpp/threadlocal.cpp0000644000175100001770000000331114721727031021155 0ustar runnerdocker/* * 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. */ #include "log4cxx/helpers/threadlocal.h" #include "apr_thread_proc.h" #include "log4cxx/helpers/exception.h" using namespace LOG4CXX_NS::helpers; using namespace LOG4CXX_NS; apr_threadkey_t* ThreadLocal::create(Pool& p) { apr_threadkey_t* key = 0; #if APR_HAS_THREADS apr_status_t stat = apr_threadkey_private_create(&key, 0, p.getAPRPool()); if (stat != APR_SUCCESS) { throw RuntimeException(stat); } #endif return key; } ThreadLocal::ThreadLocal() : p(), key(create(p)) { } ThreadLocal::~ThreadLocal() { } void ThreadLocal::set(void* priv) { #if APR_HAS_THREADS apr_status_t stat = apr_threadkey_private_set(priv, key); if (stat != APR_SUCCESS) { throw RuntimeException(stat); } #endif } void* ThreadLocal::get() { void* retval = 0; #if APR_HAS_THREADS apr_status_t stat = apr_threadkey_private_get(&retval, key); if (stat != APR_SUCCESS) { throw RuntimeException(stat); } #endif return retval; } apache-log4cxx-1.3.1/src/main/cpp/dateformat.cpp0000644000175100001770000000233014721727031021021 0ustar runnerdocker/* * 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. */ #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(DateFormat) DateFormat::~DateFormat() {} void DateFormat::setTimeZone(const TimeZonePtr&) {} void DateFormat::numberFormat(LogString& s, int n, Pool& p) const { StringHelper::toString(n, p, s); } DateFormat::DateFormat() {} apache-log4cxx-1.3.1/src/main/cpp/threadspecificdata.cpp0000644000175100001770000001725214721727031022513 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; struct ThreadSpecificData::ThreadSpecificDataPrivate{ ThreadSpecificDataPrivate() : pNamePair(std::make_shared()) { setThreadIdName(); setThreadUserName(); } NDC::Stack ndcStack; MDC::Map mdcMap; std::shared_ptr pNamePair; #if !LOG4CXX_LOGCHAR_IS_UNICHAR && !LOG4CXX_LOGCHAR_IS_WCHAR std::basic_ostringstream logchar_stringstream; #endif #if LOG4CXX_WCHAR_T_API || LOG4CXX_LOGCHAR_IS_WCHAR std::basic_ostringstream wchar_stringstream; #endif #if LOG4CXX_UNICHAR_API || LOG4CXX_LOGCHAR_IS_UNICHAR std::basic_ostringstream unichar_stringstream; #endif void setThreadIdName(); void setThreadUserName(); }; /* Generate an identifier for the current thread */ void ThreadSpecificData::ThreadSpecificDataPrivate::setThreadIdName() { #if LOG4CXX_HAS_PTHREAD_SELF && !(defined(_WIN32) && defined(_LIBCPP_VERSION)) // pthread_t encoded in HEX takes needs as many characters // as two times the size of the type, plus an additional null byte. auto threadId = pthread_self(); char result[sizeof(pthread_t) * 3 + 10]; apr_snprintf(result, sizeof(result), LOG4CXX_APR_THREAD_FMTSPEC, (void*) &threadId); this->pNamePair->idString = Transcoder::decode(result); #elif defined(_WIN32) char result[20]; apr_snprintf(result, sizeof(result), LOG4CXX_WIN32_THREAD_FMTSPEC, GetCurrentThreadId()); this->pNamePair->idString = Transcoder::decode(result); #else std::stringstream ss; ss << std::hex << "0x" << std::this_thread::get_id(); this->pNamePair->idString = Transcoder::decode(ss.str().c_str()); #endif } /* * Get the user-specified name of the current thread (on a per-platform basis). * This is set using a method such as pthread_setname_np on POSIX * systems or SetThreadDescription on Windows. */ void ThreadSpecificData::ThreadSpecificDataPrivate::setThreadUserName() { #if LOG4CXX_HAS_PTHREAD_GETNAME && !(defined(_WIN32) && defined(_LIBCPP_VERSION)) char result[16]; pthread_t current_thread = pthread_self(); if (pthread_getname_np(current_thread, result, sizeof(result)) < 0 || 0 == result[0]) this->pNamePair->threadName = this->pNamePair->idString; else this->pNamePair->threadName = Transcoder::decode(result); #elif defined(_WIN32) typedef HRESULT (WINAPI *TGetThreadDescription)(HANDLE, PWSTR*); static struct initialiser { HMODULE hKernelBase; TGetThreadDescription GetThreadDescription; initialiser() : hKernelBase(GetModuleHandleA("KernelBase.dll")) , GetThreadDescription(nullptr) { if (hKernelBase) GetThreadDescription = reinterpret_cast(GetProcAddress(hKernelBase, "GetThreadDescription")); } } win32func; if (win32func.GetThreadDescription) { PWSTR result = 0; HRESULT hr = win32func.GetThreadDescription(GetCurrentThread(), &result); if (SUCCEEDED(hr) && result) { std::wstring wresult = result; LOG4CXX_DECODE_WCHAR(decoded, wresult); LocalFree(result); this->pNamePair->threadName = decoded; } } if (this->pNamePair->threadName.empty()) this->pNamePair->threadName = this->pNamePair->idString; #else this->pNamePair->threadName = this->pNamePair->idString; #endif } ThreadSpecificData::ThreadSpecificData() : m_priv(std::make_unique()) { } ThreadSpecificData::ThreadSpecificData(ThreadSpecificData&& other) : m_priv(std::move(other.m_priv)) { } ThreadSpecificData::~ThreadSpecificData() { m_priv.reset(); } NDC::Stack& ThreadSpecificData::getStack() { return m_priv->ndcStack; } MDC::Map& ThreadSpecificData::getMap() { return m_priv->mdcMap; } auto ThreadSpecificData::getNames() -> NamePairPtr { auto p = getCurrentData(); return p ? p->m_priv->pNamePair : std::make_shared(); } #if !LOG4CXX_LOGCHAR_IS_UNICHAR && !LOG4CXX_LOGCHAR_IS_WCHAR std::basic_ostringstream& ThreadSpecificData::getStream(const logchar&) { return getCurrentData()->m_priv->logchar_stringstream; } #endif #if LOG4CXX_WCHAR_T_API || LOG4CXX_LOGCHAR_IS_WCHAR std::basic_ostringstream& ThreadSpecificData::getStream(const wchar_t&) { return getCurrentData()->m_priv->wchar_stringstream; } #endif #if LOG4CXX_UNICHAR_API || LOG4CXX_LOGCHAR_IS_UNICHAR std::basic_ostringstream& ThreadSpecificData::getStream(const UniChar&) { return getCurrentData()->m_priv->unichar_stringstream; } #endif ThreadSpecificData* ThreadSpecificData::getCurrentData() { #if LOG4CXX_HAS_THREAD_LOCAL thread_local ThreadSpecificData data; return data.m_priv ? &data : NULL; #elif APR_HAS_THREADS void* pData = NULL; if (APR_SUCCESS == apr_threadkey_private_get(&pData, APRInitializer::getTlsKey()) && !pData) { pData = new ThreadSpecificData(); if (APR_SUCCESS != apr_threadkey_private_set(pData, APRInitializer::getTlsKey())) { delete (ThreadSpecificData*)pData; pData = NULL; } } if (pData) return (ThreadSpecificData*) pData; #endif // Fallback implementation that is not expected to be used using TaggedData = std::pair; static std::list thread_id_map; static std::mutex mutex; std::lock_guard lock(mutex); auto threadId = std::this_thread::get_id(); auto pThreadId = std::find_if(thread_id_map.begin(), thread_id_map.end() , [threadId](const TaggedData& item) { return threadId == item.first; }); if (thread_id_map.end() == pThreadId) pThreadId = thread_id_map.emplace(thread_id_map.begin(), threadId, ThreadSpecificData()); return &pThreadId->second; } void ThreadSpecificData::recycle() { #if !LOG4CXX_HAS_THREAD_LOCAL && APR_HAS_THREADS if (m_priv->ndcStack.empty() && m_priv->mdcMap.empty()) { void* pData = NULL; if (APR_SUCCESS == apr_threadkey_private_get(&pData, APRInitializer::getTlsKey()) && pData == this && APR_SUCCESS == apr_threadkey_private_set(0, APRInitializer::getTlsKey())) delete this; } #endif } void ThreadSpecificData::put(const LogString& key, const LogString& val) { if (auto p = getCurrentData()) p->getMap()[key] = val; } void ThreadSpecificData::push(const LogString& val) { auto p = getCurrentData(); if (!p) return; NDC::Stack& stack = p->getStack(); if (stack.empty()) { stack.push(NDC::DiagnosticContext(val, val)); } else { LogString fullMessage(stack.top().second); fullMessage.append(1, (logchar) 0x20); fullMessage.append(val); stack.push(NDC::DiagnosticContext(val, fullMessage)); } } void ThreadSpecificData::inherit(const NDC::Stack& src) { if (auto p = getCurrentData()) p->getStack() = src; } apache-log4cxx-1.3.1/src/main/cpp/fixedwindowrollingpolicy.cpp0000644000175100001770000002216714721727031024043 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::rolling; using namespace LOG4CXX_NS::helpers; using namespace LOG4CXX_NS::pattern; #define priv static_cast(m_priv.get()) struct FixedWindowRollingPolicy::FixedWindowRollingPolicyPrivate : public RollingPolicyBasePrivate { FixedWindowRollingPolicyPrivate() : RollingPolicyBasePrivate(), minIndex(1), maxIndex(7), explicitActiveFile(false) {} int minIndex; int maxIndex; bool explicitActiveFile; bool throwIOExceptionOnForkFailure = true; }; IMPLEMENT_LOG4CXX_OBJECT(FixedWindowRollingPolicy) FixedWindowRollingPolicy::FixedWindowRollingPolicy() : RollingPolicyBase (std::make_unique()) { } FixedWindowRollingPolicy::~FixedWindowRollingPolicy(){} void FixedWindowRollingPolicy::setMaxIndex(int maxIndex1) { priv->maxIndex = maxIndex1; } void FixedWindowRollingPolicy::setMinIndex(int minIndex1) { priv->minIndex = minIndex1; } void FixedWindowRollingPolicy::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("MININDEX"), LOG4CXX_STR("minindex"))) { priv->minIndex = OptionConverter::toInt(value, 1); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("MAXINDEX"), LOG4CXX_STR("maxindex"))) { priv->maxIndex = OptionConverter::toInt(value, 7); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("THROWIOEXCEPTIONONFORKFAILURE"), LOG4CXX_STR("throwioexceptiononforkfailure"))) { priv->throwIOExceptionOnForkFailure = OptionConverter::toBoolean(value, true); } else { RollingPolicyBase::setOption(option, value); } } /** * {@inheritDoc} */ void FixedWindowRollingPolicy::activateOptions(Pool& p) { RollingPolicyBase::activateOptions(p); if (priv->maxIndex < priv->minIndex) { LogLog::warn( LOG4CXX_STR("MaxIndex cannot be smaller than MinIndex.")); priv->maxIndex = priv->minIndex; } if ((priv->maxIndex - priv->minIndex) > MAX_WINDOW_SIZE) { LogLog::warn(LOG4CXX_STR("Large window sizes are not allowed.")); priv->maxIndex = priv->minIndex + MAX_WINDOW_SIZE; } PatternConverterPtr itc = getIntegerPatternConverter(); if (itc == NULL) { throw IllegalStateException(); } } /** * {@inheritDoc} */ RolloverDescriptionPtr FixedWindowRollingPolicy::initialize( const LogString& currentActiveFile, const bool append, Pool& pool) { LogString newActiveFile(currentActiveFile); priv->explicitActiveFile = false; if (currentActiveFile.length() > 0) { priv->explicitActiveFile = true; newActiveFile = currentActiveFile; } if (!priv->explicitActiveFile) { LogString buf; ObjectPtr obj = std::make_shared(priv->minIndex); formatFileName(obj, buf, pool); newActiveFile = buf; } ActionPtr noAction; return std::make_shared(newActiveFile, append, noAction, noAction); } /** * {@inheritDoc} */ RolloverDescriptionPtr FixedWindowRollingPolicy::rollover( const LogString& currentActiveFile, const bool append, Pool& pool) { RolloverDescriptionPtr desc; if (priv->maxIndex < 0) { return desc; } int purgeStart = priv->minIndex; if (!priv->explicitActiveFile) { purgeStart++; } if (!purge(purgeStart, priv->maxIndex, pool)) { return desc; } LogString buf; ObjectPtr obj = std::make_shared(purgeStart); formatFileName(obj, buf, pool); LogString renameTo(buf); LogString compressedName(renameTo); ActionPtr compressAction ; if(getCreateIntermediateDirectories()){ File compressedFile(compressedName); File compressedParent (compressedFile.getParent(pool)); compressedParent.mkdirs(pool); } if (StringHelper::endsWith(renameTo, LOG4CXX_STR(".gz"))) { renameTo.resize(renameTo.size() - 3); GZCompressActionPtr comp = std::make_shared( File().setPath(renameTo), File().setPath(compressedName), true); comp->setThrowIOExceptionOnForkFailure(priv->throwIOExceptionOnForkFailure); compressAction = comp; } else if (StringHelper::endsWith(renameTo, LOG4CXX_STR(".zip"))) { renameTo.resize(renameTo.size() - 4); ZipCompressActionPtr comp = std::make_shared( File().setPath(renameTo), File().setPath(compressedName), true); comp->setThrowIOExceptionOnForkFailure(priv->throwIOExceptionOnForkFailure); compressAction = comp; } auto renameAction = std::make_shared( File().setPath(currentActiveFile), File().setPath(renameTo), false); desc = std::make_shared( currentActiveFile, append, renameAction, compressAction); return desc; } /** * Get index of oldest log file to be retained. * @return index of oldest log file. */ int FixedWindowRollingPolicy::getMaxIndex() const { return priv->maxIndex; } /** * Get index of most recent log file. * @return index of oldest log file. */ int FixedWindowRollingPolicy::getMinIndex() const { return priv->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. */ bool FixedWindowRollingPolicy::purge(int lowIndex, int highIndex, Pool& p) const { int suffixLength = 0; std::vector renames; LogString buf; ObjectPtr obj = std::make_shared(lowIndex); formatFileName(obj, buf, p); LogString lowFilename(buf); if (lowFilename.compare(lowFilename.length() - 3, 3, LOG4CXX_STR(".gz")) == 0) { suffixLength = 3; } else if (lowFilename.compare(lowFilename.length() - 4, 4, LOG4CXX_STR(".zip")) == 0) { suffixLength = 4; } for (int i = lowIndex; i <= highIndex; i++) { File toRenameCompressed; toRenameCompressed.setPath(lowFilename); File toRenameBase; toRenameBase.setPath(lowFilename.substr(0, lowFilename.length() - suffixLength)); File* toRename = &toRenameCompressed; bool isBase = false; bool exists = toRenameCompressed.exists(p); if (suffixLength > 0) { if (exists) { if (toRenameBase.exists(p)) { toRenameBase.deleteFile(p); } } else { toRename = &toRenameBase; exists = toRenameBase.exists(p); isBase = true; } } if (exists) { // // if at upper index then // attempt to delete last file // if that fails then abandon purge if (i == highIndex) { if (!toRename->deleteFile(p)) { return false; } break; } // // if intermediate index // add a rename action to the list buf.erase(buf.begin(), buf.end()); obj = std::make_shared(i + 1); formatFileName(obj, buf, p); LogString highFilename(buf); LogString renameTo(highFilename); if (isBase) { renameTo = highFilename.substr(0, highFilename.length() - suffixLength); } renames.push_back(std::make_shared(*toRename, File().setPath(renameTo), true)); lowFilename = highFilename; } else { break; } } // // work renames backwards // for (std::vector::reverse_iterator iter = renames.rbegin(); iter != renames.rend(); iter++) { try { if (!(*iter)->execute(p)) { return false; } } catch (std::exception&) { LogLog::warn(LOG4CXX_STR("Exception during purge in RollingFileAppender")); return false; } } return true; } #define RULES_PUT(spec, cls) \ specs.insert(PatternMap::value_type(LogString(LOG4CXX_STR(spec)), (PatternConstructor) cls ::newInstance)) LOG4CXX_NS::pattern::PatternMap FixedWindowRollingPolicy::getFormatSpecifiers() const { PatternMap specs; RULES_PUT("i", IntegerPatternConverter); RULES_PUT("index", IntegerPatternConverter); return specs; } apache-log4cxx-1.3.1/src/main/cpp/fileappender.cpp0000644000175100001770000002153614721727031021342 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; using namespace LOG4CXX_NS::spi; IMPLEMENT_LOG4CXX_OBJECT(FileAppender) #define _priv static_cast(m_priv.get()) FileAppender::FileAppender() : WriterAppender (std::make_unique()) { } FileAppender::FileAppender ( const LayoutPtr& layout1 , const LogString& fileName1 , bool append1 , bool bufferedIO1 , int bufferSize1 ) : WriterAppender(std::make_unique(layout1, fileName1, append1, bufferedIO1, bufferSize1)) { Pool p; activateOptions(p); } FileAppender::FileAppender ( const LayoutPtr& layout1 , const LogString& fileName1 , bool append1 ) : WriterAppender(std::make_unique(layout1, fileName1, append1, false)) { Pool p; activateOptions(p); } FileAppender::FileAppender(const LayoutPtr& layout1, const LogString& fileName1) : WriterAppender(std::make_unique(layout1, fileName1)) { Pool p; activateOptions(p); } FileAppender::FileAppender(std::unique_ptr priv) : WriterAppender (std::move(priv)) { } FileAppender::~FileAppender() { finalize(); } void FileAppender::setAppend(bool fileAppend1) { std::lock_guard lock(_priv->mutex); _priv->fileAppend = fileAppend1; } void FileAppender::setFile(const LogString& file) { std::lock_guard lock(_priv->mutex); setFileInternal(file); } void FileAppender::setFileInternal(const LogString& file) { _priv->fileName = file; } void FileAppender::setBufferedIO(bool bufferedIO1) { std::lock_guard lock(_priv->mutex); _priv->bufferedIO = bufferedIO1; if (bufferedIO1) { setImmediateFlush(false); } } void FileAppender::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("FILE"), LOG4CXX_STR("file")) || StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("FILENAME"), LOG4CXX_STR("filename"))) { std::lock_guard lock(_priv->mutex); _priv->fileName = stripDuplicateBackslashes(value); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("APPEND"), LOG4CXX_STR("append"))) { std::lock_guard lock(_priv->mutex); _priv->fileAppend = OptionConverter::toBoolean(value, true); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("BUFFEREDIO"), LOG4CXX_STR("bufferedio"))) { std::lock_guard lock(_priv->mutex); _priv->bufferedIO = OptionConverter::toBoolean(value, false); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("IMMEDIATEFLUSH"), LOG4CXX_STR("immediateflush"))) { std::lock_guard lock(_priv->mutex); _priv->bufferedIO = !OptionConverter::toBoolean(value, false); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("BUFFERSIZE"), LOG4CXX_STR("buffersize"))) { std::lock_guard lock(_priv->mutex); _priv->bufferSize = OptionConverter::toFileSize(value, 8 * 1024); } else { WriterAppender::setOption(option, value); } } void FileAppender::activateOptions(Pool& p) { std::lock_guard lock(_priv->mutex); activateOptionsInternal(p); } void FileAppender::activateOptionsInternal(Pool& p) { int errors = 0; if (!_priv->fileName.empty()) { try { setFileInternal(_priv->fileName, _priv->fileAppend, _priv->bufferedIO, _priv->bufferSize, p); } catch (IOException& e) { errors++; LogString msg(LOG4CXX_STR("setFile(")); msg.append(_priv->fileName); msg.append(1, (logchar) 0x2C /* ',' */); StringHelper::toString(_priv->fileAppend, msg); msg.append(LOG4CXX_STR(") call failed.")); _priv->errorHandler->error(msg, e, ErrorCode::FILE_OPEN_FAILURE); } } else { errors++; LogLog::error(LogString(LOG4CXX_STR("File option not set for appender [")) + _priv->name + LOG4CXX_STR("].")); LogLog::warn(LOG4CXX_STR("Are you using FileAppender instead of ConsoleAppender?")); } if (errors == 0) { WriterAppender::activateOptions(p); } } /** * Replaces double backslashes (except the leading doubles of UNC's) * with single backslashes for compatibility with existing path * specifications that were working around use of * OptionConverter::convertSpecialChars in XML configuration files. * * @param src source string * @return modified string * * */ LogString FileAppender::stripDuplicateBackslashes(const LogString& src) { logchar backslash = 0x5C; // '\\' LogString::size_type i = src.find_last_of(backslash); if (i != LogString::npos) { LogString tmp(src); for (; i != LogString::npos && i > 0; i = tmp.find_last_of(backslash, i - 1)) { // // if the preceding character is a slash then // remove the preceding character // and continue processing if (tmp[i - 1] == backslash) { tmp.erase(i, 1); i--; if (i == 0) { break; } } else { // // if there an odd number of slashes // the string wasn't trying to work around // OptionConverter::convertSpecialChars return src; } } return tmp; } return src; } /**

Sets and opens the file where the log output will go. The specified file must be writable.

If there was already an opened file, then the previous file is closed first.

Do not use this method directly. To configure a FileAppender or one of its subclasses, set its properties one by one and then call activateOptions. @param filename The path to the log file. @param append If true will append to fileName. Otherwise will truncate fileName. @param bufferedIO @param bufferSize @throws IOException */ void FileAppender::setFileInternal( const LogString& filename, bool append1, bool bufferedIO1, size_t bufferSize1, Pool& p) { // It does not make sense to have immediate flush and bufferedIO. if (bufferedIO1) { setImmediateFlush(false); } closeWriter(); bool writeBOM = false; if (StringHelper::equalsIgnoreCase(getEncoding(), LOG4CXX_STR("utf-16"), LOG4CXX_STR("UTF-16"))) { // // don't want to write a byte order mark if the file exists // if (append1) { File outFile; outFile.setPath(filename); writeBOM = !outFile.exists(p); } else { writeBOM = true; } } OutputStreamPtr outStream; try { outStream = FileOutputStreamPtr(new FileOutputStream(filename, append1)); } catch (IOException&) { LogString parentName = File().setPath(filename).getParent(p); if (!parentName.empty()) { File parentDir; parentDir.setPath(parentName); if (!parentDir.exists(p) && parentDir.mkdirs(p)) { outStream = OutputStreamPtr(new FileOutputStream(filename, append1)); } else { throw; } } else { throw; } } // // if a new file and UTF-16, then write a BOM // if (writeBOM) { char bom[] = { (char) 0xFE, (char) 0xFF }; ByteBuffer buf(bom, 2); outStream->write(buf, p); } WriterPtr newWriter(createWriter(outStream)); if (bufferedIO1) { newWriter = std::make_shared(newWriter, bufferSize1); } setWriterInternal(newWriter); _priv->fileAppend = append1; _priv->bufferedIO = bufferedIO1; _priv->fileName = filename; _priv->bufferSize = (int)bufferSize1; writeHeader(p); } LogString FileAppender::getFile() const { return _priv->fileName; } bool FileAppender::getBufferedIO() const { return _priv->bufferedIO; } int FileAppender::getBufferSize() const { return _priv->bufferSize; } void FileAppender::setBufferSize(int bufferSize1) { _priv->bufferSize = bufferSize1; } bool FileAppender::getAppend() const { return _priv->fileAppend; } apache-log4cxx-1.3.1/src/main/cpp/levelrangefilter.cpp0000644000175100001770000000740714721727031022237 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::filter; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; #define priv static_cast(m_priv.get()) struct LevelRangeFilter::LevelRangeFilterPrivate : public FilterPrivate { LevelRangeFilterPrivate() : acceptOnMatch(false), levelMin(Level::getAll()), levelMax(Level::getOff()) {} /** Do we return ACCEPT when a match occurs. Default is false, so that later filters get run by default */ bool acceptOnMatch; LevelPtr levelMin; LevelPtr levelMax; }; IMPLEMENT_LOG4CXX_OBJECT(LevelRangeFilter) LevelRangeFilter::LevelRangeFilter() : Filter(std::make_unique()) { } LevelRangeFilter::~LevelRangeFilter() {} void LevelRangeFilter::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("LEVELMIN"), LOG4CXX_STR("levelmin"))) { priv->levelMin = OptionConverter::toLevel(value, priv->levelMin); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("LEVELMAX"), LOG4CXX_STR("levelmax"))) { priv->levelMax = OptionConverter::toLevel(value, priv->levelMax); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("ACCEPTONMATCH"), LOG4CXX_STR("acceptonmatch"))) { priv->acceptOnMatch = OptionConverter::toBoolean(value, priv->acceptOnMatch); } } Filter::FilterDecision LevelRangeFilter::decide( const spi::LoggingEventPtr& event) const { if (priv->levelMin != 0 && !event->getLevel()->isGreaterOrEqual(priv->levelMin)) { // level of event is less than minimum return Filter::DENY; } if (priv->levelMax != 0 && event->getLevel()->toInt() > priv->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 (priv->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; } } void LevelRangeFilter::setLevelMin(const LevelPtr& levelMin1) { priv->levelMin = levelMin1; } const LevelPtr& LevelRangeFilter::getLevelMin() const { return priv->levelMin; } void LevelRangeFilter::setLevelMax(const LevelPtr& levelMax1) { priv->levelMax = levelMax1; } const LevelPtr& LevelRangeFilter::getLevelMax() const { return priv->levelMax; } void LevelRangeFilter::setAcceptOnMatch(bool acceptOnMatch1) { priv->acceptOnMatch = acceptOnMatch1; } bool LevelRangeFilter::getAcceptOnMatch() const { return priv->acceptOnMatch; } apache-log4cxx-1.3.1/src/main/cpp/outputdebugstringappender.cpp0000644000175100001770000000277514721727031024225 0ustar runnerdocker/* * 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. */ #if defined(_WIN32) #include #include #include #include "windows.h" using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; using namespace LOG4CXX_NS::nt; IMPLEMENT_LOG4CXX_OBJECT(OutputDebugStringAppender) OutputDebugStringAppender::OutputDebugStringAppender() { } void OutputDebugStringAppender::append(const spi::LoggingEventPtr& event, Pool& p) { LogString buf; this->m_priv->layout->format(buf, event, p); #if LOG4CXX_WCHAR_T_API LOG4CXX_ENCODE_WCHAR(wstr, buf); ::OutputDebugStringW(wstr.c_str()); #else LOG4CXX_ENCODE_CHAR(str, buf); ::OutputDebugStringA(str.c_str()); #endif } #endif apache-log4cxx-1.3.1/src/main/cpp/resourcebundle.cpp0000644000175100001770000000605314721727031021722 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(ResourceBundle) ResourceBundlePtr ResourceBundle::getBundle(const LogString& baseName, const Locale& locale) { std::vector bundlesNames; if (!locale.getVariant().empty()) { bundlesNames.push_back(baseName + LOG4CXX_STR("_") + locale.getLanguage() + LOG4CXX_STR("_") + locale.getCountry() + LOG4CXX_STR("_") + locale.getVariant()); } if (!locale.getCountry().empty()) { bundlesNames.push_back(baseName + LOG4CXX_STR("_") + locale.getLanguage() + LOG4CXX_STR("_") + locale.getCountry()); } if (!locale.getLanguage().empty()) { bundlesNames.push_back(baseName + LOG4CXX_STR("_") + locale.getLanguage()); } bundlesNames.push_back(baseName); PropertyResourceBundlePtr resourceBundle, previous; for (auto bundleName : bundlesNames) { PropertyResourceBundlePtr current; // Try loading a class which implements ResourceBundle try { const Class& classObj = Loader::loadClass(bundleName); ObjectPtr obj = ObjectPtr(classObj.newInstance()); current = LOG4CXX_NS::cast(obj); } catch (ClassNotFoundException&) { current.reset(); } // No class found, then try to create a PropertyResourceBundle from a file if (!current) { InputStreamPtr bundleStream = Loader::getResourceAsStream( bundleName + LOG4CXX_STR(".properties")); if (!bundleStream) { continue; } try { current = std::make_shared(bundleStream); } catch (Exception&) { throw; } } // Add the new resource bundle to the hierarchy if (!resourceBundle) { resourceBundle = current; previous = current; } else { previous->setParent(current); previous = current; } } // no resource bundle found at all, then throw exception if (!resourceBundle) { throw MissingResourceException( ((LogString) LOG4CXX_STR("Missing resource bundle ")) + baseName); } return resourceBundle; } apache-log4cxx-1.3.1/src/main/cpp/pool.cpp0000644000175100001770000000450014721727031017645 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include using namespace LOG4CXX_NS::helpers; using namespace LOG4CXX_NS; Pool::Pool() : pool(0), release(true) { } Pool::Pool(apr_pool_t* p, bool release1) : pool(p), release(release1) { assert(p != NULL); } Pool::~Pool() { if (pool && release) { apr_pool_destroy(pool); } } void Pool::setPool() { apr_status_t stat = apr_pool_create(&pool, APRInitializer::getRootPool()); if (stat != APR_SUCCESS) { throw PoolException(stat); } } apr_pool_t* Pool::getAPRPool() { if (!pool) setPool(); return pool; } apr_pool_t* Pool::create() { if (!pool) setPool(); apr_pool_t* child; apr_status_t stat = apr_pool_create(&child, pool); if (stat != APR_SUCCESS) { throw PoolException(stat); } return child; } void* Pool::palloc(size_t size) { if (!pool) setPool(); return apr_palloc(pool, size); } char* Pool::pstralloc(size_t size) { return (char*) palloc(size); } char* Pool::itoa(int n) { if (!pool) setPool(); return apr_itoa(pool, n); } char* Pool::pstrndup(const char* s, size_t len) { if (!pool) setPool(); return apr_pstrndup(pool, s, len); } char* Pool::pstrdup(const char* s) { if (!pool) setPool(); return apr_pstrdup(pool, s); } char* Pool::pstrdup(const std::string& s) { if (!pool) setPool(); return apr_pstrndup(pool, s.data(), s.length()); } apache-log4cxx-1.3.1/src/main/cpp/defaultconfigurator.cpp0000644000175100001770000001457514721727031022760 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; namespace { LogString DefaultConfiguratorPath; int DefaultConfiguratorWatchSeconds = 0; } void DefaultConfigurator::setConfigurationFileName(const LogString& path) { DefaultConfiguratorPath = path; } void DefaultConfigurator::setConfigurationWatchSeconds(int seconds) { DefaultConfiguratorWatchSeconds = seconds; } static const int MillisecondsPerSecond = 1000; void DefaultConfigurator::configure(LoggerRepositoryPtr repository) { repository->setConfigured(true); const LogString configuratorClassName(getConfiguratorClass()); LogString configurationFileName = DefaultConfiguratorPath; if (configurationFileName.empty()) configurationFileName = getConfigurationFileName(); Pool pool; File configuration; if (configurationFileName.empty()) { LogString names[4] = { LOG4CXX_STR("log4cxx.xml") , LOG4CXX_STR("log4cxx.properties") , LOG4CXX_STR("log4j.xml") , LOG4CXX_STR("log4j.properties") }; for (int i = 0; i < 4; i++) { File candidate(names[i]); if (LogLog::isDebugEnabled()) { LogString debugMsg = LOG4CXX_STR("Checking file "); debugMsg.append(names[i]); LogLog::debug(debugMsg); } if (candidate.exists(pool)) { configuration = candidate; break; } } } else { configuration.setPath(configurationFileName); } if (configuration.exists(pool)) { if (LogLog::isDebugEnabled()) { LogString msg(LOG4CXX_STR("Using configuration file [")); msg += configuration.getPath(); msg += LOG4CXX_STR("] for automatic log4cxx configuration"); LogLog::debug(msg); } LoggerRepositoryPtr repo(repository); OptionConverter::selectAndConfigure( configuration, configuratorClassName, repo, 0 < DefaultConfiguratorWatchSeconds ? DefaultConfiguratorWatchSeconds * MillisecondsPerSecond : getConfigurationWatchDelay() ); } else if (LogLog::isDebugEnabled()) { if (configurationFileName.empty()) { LogLog::debug(LOG4CXX_STR("Could not find default configuration file.")); } else { LogString msg(LOG4CXX_STR("Could not find configuration file: [")); msg += configurationFileName; msg += LOG4CXX_STR("]."); LogLog::debug(msg); } } } const LogString DefaultConfigurator::getConfiguratorClass() { // Use automatic configration to configure the default hierarchy const LogString log4jConfiguratorClassName( OptionConverter::getSystemProperty(LOG4CXX_STR("log4j.configuratorClass"), LOG4CXX_STR(""))); const LogString configuratorClassName( OptionConverter::getSystemProperty(LOG4CXX_STR("LOG4CXX_CONFIGURATOR_CLASS"), log4jConfiguratorClassName)); return configuratorClassName; } const LogString DefaultConfigurator::getConfigurationFileName() { static const WideLife LOG4CXX_DEFAULT_CONFIGURATION_KEY(LOG4CXX_STR("LOG4CXX_CONFIGURATION")); static const WideLife LOG4J_DEFAULT_CONFIGURATION_KEY(LOG4CXX_STR("log4j.configuration")); const LogString log4jConfigurationFileName( OptionConverter::getSystemProperty(LOG4J_DEFAULT_CONFIGURATION_KEY, LOG4CXX_STR(""))); const LogString configurationFileName( OptionConverter::getSystemProperty(LOG4CXX_DEFAULT_CONFIGURATION_KEY, log4jConfigurationFileName)); return configurationFileName; } int DefaultConfigurator::getConfigurationWatchDelay() { static const WideLife LOG4CXX_DEFAULT_CONFIGURATION_WATCH_KEY(LOG4CXX_STR("LOG4CXX_CONFIGURATION_WATCH_SECONDS")); LogString optionStr = OptionConverter::getSystemProperty(LOG4CXX_DEFAULT_CONFIGURATION_WATCH_KEY, LogString()); int milliseconds = 0; if (!optionStr.empty()) milliseconds = StringHelper::toInt(optionStr) * MillisecondsPerSecond; return milliseconds; } LOG4CXX_NS::spi::ConfigurationStatus DefaultConfigurator::tryLoadFile(const LogString& filename){ #if LOG4CXX_HAS_DOMCONFIGURATOR if(helpers::StringHelper::endsWith(filename, LOG4CXX_STR(".xml"))){ return LOG4CXX_NS::xml::DOMConfigurator::configure(filename); } #endif if(helpers::StringHelper::endsWith(filename, LOG4CXX_STR(".properties"))){ return LOG4CXX_NS::PropertyConfigurator::configure(filename); } return LOG4CXX_NS::spi::ConfigurationStatus::NotConfigured; } std::tuple DefaultConfigurator::configureFromFile(const std::vector& directories, const std::vector& filenames){ using ResultType = std::tuple; LOG4CXX_NS::helpers::Pool pool; for( LogString dir : directories ){ for( LogString fname : filenames ){ LogString canidate_str = dir + LOG4CXX_STR("/") + fname; File candidate(canidate_str); if (LogLog::isDebugEnabled()) { LogString debugMsg = LOG4CXX_STR("Checking file "); debugMsg.append(canidate_str); LogLog::debug(debugMsg); } if (candidate.exists(pool)) { LOG4CXX_NS::spi::ConfigurationStatus configStatus = tryLoadFile(canidate_str); if( configStatus == LOG4CXX_NS::spi::ConfigurationStatus::Configured ){ return ResultType{configStatus, canidate_str}; } if (LogLog::isDebugEnabled()) LogLog::debug(LOG4CXX_STR("Unable to load file: trying next")); } } } return ResultType{LOG4CXX_NS::spi::ConfigurationStatus::NotConfigured, LogString()}; } apache-log4cxx-1.3.1/src/main/cpp/throwableinformationpatternconverter.cpp0000644000175100001770000000527714721727031026473 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::pattern; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; struct ThrowableInformationPatternConverter::ThrowableInformationPatternConverterPrivate : public PatternConverterPrivate { ThrowableInformationPatternConverterPrivate( const LogString& name, const LogString& style, bool shortReport ) : PatternConverterPrivate( name, style ), shortReport(shortReport) {} /** * If "short", only first line of throwable report will be formatted. */ const bool shortReport; }; IMPLEMENT_LOG4CXX_OBJECT(ThrowableInformationPatternConverter) ThrowableInformationPatternConverter::ThrowableInformationPatternConverter(bool shortReport1) : LoggingEventPatternConverter( std::make_unique( LOG4CXX_STR("Throwable"), LOG4CXX_STR("throwable"), shortReport1)) { } PatternConverterPtr ThrowableInformationPatternConverter::newInstance( const std::vector& options) { if (options.size() > 0 && options[0].compare(LOG4CXX_STR("short")) == 0) { static WideLife shortConverter = std::make_shared(true); return shortConverter; } static WideLife converter = std::make_shared(false); return converter; } void ThrowableInformationPatternConverter::format( const LoggingEventPtr& /* event */, LogString& /* toAppendTo */, Pool& /* p */) const { } /** * This converter obviously handles throwables. * @return true. */ bool ThrowableInformationPatternConverter::handlesThrowable() const { return true; } apache-log4cxx-1.3.1/src/main/cpp/messagebuffer.cpp0000644000175100001770000004544214721727031021524 0ustar runnerdocker/* * 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. */ #include /* Prevent error C2491: 'std::numpunct<_Elem>::id': definition of dllimport static data member not allowed */ #if defined(_MSC_VER) && (LOG4CXX_UNICHAR_API || LOG4CXX_LOGCHAR_IS_UNICHAR) #define __FORCE_INSTANCE #endif #include #include #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include #if !LOG4CXX_HAS_THREAD_LOCAL #include #endif using namespace LOG4CXX_NS::helpers; namespace { template struct StringOrStream { std::basic_string buf; std::basic_ostringstream* stream; StringOrStream() : stream(nullptr) {} /** * Move the character buffer from \c buf to \c stream */ std::basic_ostringstream& StreamFromBuf() { if (!this->stream) { const static std::basic_ostringstream initialState; #if LOG4CXX_HAS_THREAD_LOCAL thread_local static std::basic_ostringstream sStream; #else auto& sStream = ThreadSpecificData::getStringStream(); #endif this->stream = &sStream; this->stream->clear(); this->stream->precision(initialState.precision()); this->stream->width(initialState.width()); this->stream->setf(initialState.flags(), ~initialState.flags()); this->stream->fill(initialState.fill()); auto index = this->buf.size(); this->stream->str(std::move(this->buf)); this->stream->seekp(index); } return *this->stream; } /** * Move the character buffer from \c stream to \c buf */ std::basic_string& BufFromStream() { if (this->stream) { this->buf = std::move(*this->stream).str(); this->stream->seekp(0); this->stream->str(std::basic_string()); this->stream->clear(); } return this->buf; } }; } struct CharMessageBuffer::CharMessageBufferPrivate : public StringOrStream {}; CharMessageBuffer::CharMessageBuffer() : m_priv(std::make_unique()) { } CharMessageBuffer::~CharMessageBuffer() { } CharMessageBuffer& CharMessageBuffer::operator<<(const std::basic_string& msg) { if (m_priv->stream == 0) { m_priv->buf.append(msg); } else { *m_priv->stream << msg; } return *this; } CharMessageBuffer& CharMessageBuffer::operator<<(const char* msg) { const char* actualMsg = msg; if (actualMsg == 0) { actualMsg = "null"; } if (m_priv->stream == 0) { m_priv->buf.append(actualMsg); } else { *m_priv->stream << actualMsg; } return *this; } CharMessageBuffer& CharMessageBuffer::operator<<(char* msg) { return operator<<((const char*) msg); } CharMessageBuffer& CharMessageBuffer::operator<<(const char msg) { if (m_priv->stream == 0) { m_priv->buf.append(1, msg); } else { m_priv->buf.assign(1, msg); *m_priv->stream << m_priv->buf; } return *this; } CharMessageBuffer::operator std::basic_ostream& () { return m_priv->StreamFromBuf(); } std::basic_string CharMessageBuffer::extract_str(std::basic_ostream&) { return std::move(m_priv->BufFromStream()); } std::basic_string CharMessageBuffer::extract_str(CharMessageBuffer&) { return std::move(m_priv->buf); } const std::basic_string& CharMessageBuffer::str(std::basic_ostream&) { return m_priv->BufFromStream(); } const std::basic_string& CharMessageBuffer::str(CharMessageBuffer&) { return m_priv->buf; } bool CharMessageBuffer::hasStream() const { return (m_priv->stream != 0); } std::ostream& CharMessageBuffer::operator<<(ios_base_manip manip) { std::ostream& s = *this; (*manip)(s); return s; } std::ostream& CharMessageBuffer::operator<<(bool val) { return ((std::ostream&) * this).operator << (val); } std::ostream& CharMessageBuffer::operator<<(short val) { return ((std::ostream&) * this).operator << (val); } std::ostream& CharMessageBuffer::operator<<(int val) { return ((std::ostream&) * this).operator << (val); } std::ostream& CharMessageBuffer::operator<<(unsigned int val) { return ((std::ostream&) * this).operator << (val); } std::ostream& CharMessageBuffer::operator<<(long val) { return ((std::ostream&) * this).operator << (val); } std::ostream& CharMessageBuffer::operator<<(unsigned long val) { return ((std::ostream&) * this).operator << (val); } std::ostream& CharMessageBuffer::operator<<(float val) { return ((std::ostream&) * this).operator << (val); } std::ostream& CharMessageBuffer::operator<<(double val) { return ((std::ostream&) * this).operator << (val); } std::ostream& CharMessageBuffer::operator<<(long double val) { return ((std::ostream&) * this).operator << (val); } std::ostream& CharMessageBuffer::operator<<(void* val) { return ((std::ostream&) * this).operator << (val); } #if LOG4CXX_WCHAR_T_API struct WideMessageBuffer::WideMessageBufferPrivate : public StringOrStream {}; WideMessageBuffer::WideMessageBuffer() : m_priv(std::make_unique()) { } WideMessageBuffer::~WideMessageBuffer() { } WideMessageBuffer& WideMessageBuffer::operator<<(const std::basic_string& msg) { if (m_priv->stream == 0) { m_priv->buf.append(msg); } else { *m_priv->stream << msg; } return *this; } WideMessageBuffer& WideMessageBuffer::operator<<(const wchar_t* msg) { const wchar_t* actualMsg = msg; if (actualMsg == 0) { actualMsg = L"null"; } if (m_priv->stream == 0) { m_priv->buf.append(actualMsg); } else { *m_priv->stream << actualMsg; } return *this; } WideMessageBuffer& WideMessageBuffer::operator<<(wchar_t* msg) { return operator<<((const wchar_t*) msg); } WideMessageBuffer& WideMessageBuffer::operator<<(const wchar_t msg) { if (m_priv->stream == 0) { m_priv->buf.append(1, msg); } else { m_priv->buf.assign(1, msg); *m_priv->stream << m_priv->buf; } return *this; } WideMessageBuffer::operator std::basic_ostream& () { return m_priv->StreamFromBuf(); } std::basic_string WideMessageBuffer::extract_str(std::basic_ostream&) { return std::move(m_priv->BufFromStream()); } std::basic_string WideMessageBuffer::extract_str(WideMessageBuffer&) { return std::move(m_priv->buf); } const std::basic_string& WideMessageBuffer::str(std::basic_ostream&) { return m_priv->BufFromStream(); } const std::basic_string& WideMessageBuffer::str(WideMessageBuffer&) { return m_priv->buf; } bool WideMessageBuffer::hasStream() const { return (m_priv->stream != 0); } std::basic_ostream& WideMessageBuffer::operator<<(ios_base_manip manip) { std::basic_ostream& s = *this; (*manip)(s); return s; } std::basic_ostream& WideMessageBuffer::operator<<(bool val) { return ((std::basic_ostream&) * this).operator << (val); } std::basic_ostream& WideMessageBuffer::operator<<(short val) { return ((std::basic_ostream&) * this).operator << (val); } std::basic_ostream& WideMessageBuffer::operator<<(int val) { return ((std::basic_ostream&) * this).operator << (val); } std::basic_ostream& WideMessageBuffer::operator<<(unsigned int val) { return ((std::basic_ostream&) * this).operator << (val); } std::basic_ostream& WideMessageBuffer::operator<<(long val) { return ((std::basic_ostream&) * this).operator << (val); } std::basic_ostream& WideMessageBuffer::operator<<(unsigned long val) { return ((std::basic_ostream&) * this).operator << (val); } std::basic_ostream& WideMessageBuffer::operator<<(float val) { return ((std::basic_ostream&) * this).operator << (val); } std::basic_ostream& WideMessageBuffer::operator<<(double val) { return ((std::basic_ostream&) * this).operator << (val); } std::basic_ostream& WideMessageBuffer::operator<<(long double val) { return ((std::basic_ostream&) * this).operator << (val); } std::basic_ostream& WideMessageBuffer::operator<<(void* val) { return ((std::basic_ostream&) * this).operator << (val); } struct MessageBuffer::MessageBufferPrivate{ MessageBufferPrivate(){} /** * Character message buffer. */ CharMessageBuffer cbuf; /** * Encapsulated wide message buffer, created on demand. */ std::unique_ptr wbuf; #if LOG4CXX_UNICHAR_API /** * Encapsulated wide message buffer, created on demand. */ std::unique_ptr ubuf; #endif }; MessageBuffer::MessageBuffer() : m_priv(std::make_unique()) { } MessageBuffer::~MessageBuffer() { } bool MessageBuffer::hasStream() const { bool retval = m_priv->cbuf.hasStream() || (m_priv->wbuf != 0 && m_priv->wbuf->hasStream()); #if LOG4CXX_UNICHAR_API retval = retval || (m_priv->ubuf != 0 && m_priv->ubuf->hasStream()); #endif return retval; } std::ostream& MessageBuffer::operator<<(ios_base_manip manip) { std::ostream& s = *this; (*manip)(s); return s; } MessageBuffer::operator std::ostream& () { return (std::ostream&) m_priv->cbuf; } CharMessageBuffer& MessageBuffer::operator<<(const std::string& msg) { return m_priv->cbuf.operator << (msg); } CharMessageBuffer& MessageBuffer::operator<<(const char* msg) { return m_priv->cbuf.operator << (msg); } CharMessageBuffer& MessageBuffer::operator<<(char* msg) { return m_priv->cbuf.operator << ((const char*) msg); } CharMessageBuffer& MessageBuffer::operator<<(const char msg) { return m_priv->cbuf.operator << (msg); } std::string MessageBuffer::extract_str(CharMessageBuffer& buf) { return std::move(m_priv->cbuf.extract_str(buf)); } std::string MessageBuffer::extract_str(std::ostream& os) { return std::move(m_priv->cbuf.extract_str(os)); } const std::string& MessageBuffer::str(CharMessageBuffer& buf) { return m_priv->cbuf.str(buf); } const std::string& MessageBuffer::str(std::ostream& os) { return m_priv->cbuf.str(os); } WideMessageBuffer& MessageBuffer::operator<<(const std::wstring& msg) { m_priv->wbuf = std::make_unique(); return (*m_priv->wbuf) << msg; } WideMessageBuffer& MessageBuffer::operator<<(const wchar_t* msg) { m_priv->wbuf = std::make_unique(); return (*m_priv->wbuf) << msg; } WideMessageBuffer& MessageBuffer::operator<<(wchar_t* msg) { m_priv->wbuf = std::make_unique(); return (*m_priv->wbuf) << (const wchar_t*) msg; } WideMessageBuffer& MessageBuffer::operator<<(const wchar_t msg) { m_priv->wbuf = std::make_unique(); return (*m_priv->wbuf) << msg; } std::wstring MessageBuffer::extract_str(WideMessageBuffer& buf) { return std::move(m_priv->wbuf->extract_str(buf)); } std::wstring MessageBuffer::extract_str(std::basic_ostream& os) { return std::move(m_priv->wbuf->extract_str(os)); } const std::wstring& MessageBuffer::str(WideMessageBuffer& buf) { return m_priv->wbuf->str(buf); } const std::wstring& MessageBuffer::str(std::basic_ostream& os) { return m_priv->wbuf->str(os); } std::ostream& MessageBuffer::operator<<(bool val) { return m_priv->cbuf.operator << (val); } std::ostream& MessageBuffer::operator<<(short val) { return m_priv->cbuf.operator << (val); } std::ostream& MessageBuffer::operator<<(int val) { return m_priv->cbuf.operator << (val); } std::ostream& MessageBuffer::operator<<(unsigned int val) { return m_priv->cbuf.operator << (val); } std::ostream& MessageBuffer::operator<<(long val) { return m_priv->cbuf.operator << (val); } std::ostream& MessageBuffer::operator<<(unsigned long val) { return m_priv->cbuf.operator << (val); } std::ostream& MessageBuffer::operator<<(float val) { return m_priv->cbuf.operator << (val); } std::ostream& MessageBuffer::operator<<(double val) { return m_priv->cbuf.operator << (val); } std::ostream& MessageBuffer::operator<<(long double val) { return m_priv->cbuf.operator << (val); } std::ostream& MessageBuffer::operator<<(void* val) { return m_priv->cbuf.operator << (val); } #if LOG4CXX_UNICHAR_API UniCharMessageBuffer& MessageBuffer::operator<<(const std::basic_string& msg) { m_priv->ubuf = std::make_unique(); return (*m_priv->ubuf) << msg; } UniCharMessageBuffer& MessageBuffer::operator<<(const LOG4CXX_NS::UniChar* msg) { m_priv->ubuf = std::make_unique(); return (*m_priv->ubuf) << msg; } UniCharMessageBuffer& MessageBuffer::operator<<(LOG4CXX_NS::UniChar* msg) { m_priv->ubuf = std::make_unique(); return (*m_priv->ubuf) << (const LOG4CXX_NS::UniChar*) msg; } UniCharMessageBuffer& MessageBuffer::operator<<(const LOG4CXX_NS::UniChar msg) { m_priv->ubuf = std::make_unique(); return (*m_priv->ubuf) << msg; } std::basic_string MessageBuffer::extract_str(UniCharMessageBuffer& buf) { return std::move(m_priv->ubuf->extract_str(buf)); } std::basic_string MessageBuffer::extract_str(std::basic_ostream& os) { return std::move(m_priv->ubuf->extract_str(os)); } const std::basic_string& MessageBuffer::str(UniCharMessageBuffer& buf) { return m_priv->ubuf->str(buf); } const std::basic_string& MessageBuffer::str(std::basic_ostream& os) { return m_priv->ubuf->str(os); } #endif //LOG4CXX_UNICHAR_API #endif // LOG4CXX_WCHAR_T_API #if LOG4CXX_UNICHAR_API || LOG4CXX_LOGCHAR_IS_UNICHAR struct UniCharMessageBuffer::UniCharMessageBufferPrivate : public StringOrStream {}; UniCharMessageBuffer::UniCharMessageBuffer() : m_priv(std::make_unique()) { } UniCharMessageBuffer::~UniCharMessageBuffer() { } UniCharMessageBuffer& UniCharMessageBuffer::operator<<(const std::basic_string& msg) { if (!m_priv->stream) { m_priv->buf.append(msg); } else { *m_priv->stream << m_priv->buf; } return *this; } UniCharMessageBuffer& UniCharMessageBuffer::operator<<(const LOG4CXX_NS::UniChar* msg) { const LOG4CXX_NS::UniChar* actualMsg = msg; static const LOG4CXX_NS::UniChar nullLiteral[] = { 0x6E, 0x75, 0x6C, 0x6C, 0}; if (actualMsg == 0) { actualMsg = nullLiteral; } if (!m_priv->stream) { m_priv->buf.append(actualMsg); } else { *m_priv->stream << actualMsg; } return *this; } UniCharMessageBuffer& UniCharMessageBuffer::operator<<(LOG4CXX_NS::UniChar* msg) { return operator<<((const LOG4CXX_NS::UniChar*) msg); } UniCharMessageBuffer& UniCharMessageBuffer::operator<<(const LOG4CXX_NS::UniChar msg) { if (!m_priv->stream) { m_priv->buf.append(1, msg); } else { *m_priv->stream << msg; } return *this; } UniCharMessageBuffer::operator UniCharMessageBuffer::uostream& () { return m_priv->StreamFromBuf(); } std::basic_string UniCharMessageBuffer::extract_str(UniCharMessageBuffer::uostream&) { return std::move(m_priv->BufFromStream()); } std::basic_string UniCharMessageBuffer::extract_str(UniCharMessageBuffer&) { return std::move(m_priv->buf); } const std::basic_string& UniCharMessageBuffer::str(UniCharMessageBuffer::uostream&) { return m_priv->BufFromStream(); } const std::basic_string& UniCharMessageBuffer::str(UniCharMessageBuffer&) { return m_priv->buf; } bool UniCharMessageBuffer::hasStream() const { return (m_priv->stream != 0); } UniCharMessageBuffer::uostream& UniCharMessageBuffer::operator<<(ios_base_manip manip) { UniCharMessageBuffer::uostream& s = *this; (*manip)(s); return s; } UniCharMessageBuffer::uostream& UniCharMessageBuffer::operator<<(bool val) { return ((UniCharMessageBuffer::uostream&) * this).operator << (val); } UniCharMessageBuffer::uostream& UniCharMessageBuffer::operator<<(short val) { return ((UniCharMessageBuffer::uostream&) * this).operator << (val); } UniCharMessageBuffer::uostream& UniCharMessageBuffer::operator<<(int val) { return ((UniCharMessageBuffer::uostream&) * this).operator << (val); } UniCharMessageBuffer::uostream& UniCharMessageBuffer::operator<<(unsigned int val) { return ((UniCharMessageBuffer::uostream&) * this).operator << (val); } UniCharMessageBuffer::uostream& UniCharMessageBuffer::operator<<(long val) { return ((UniCharMessageBuffer::uostream&) * this).operator << (val); } UniCharMessageBuffer::uostream& UniCharMessageBuffer::operator<<(unsigned long val) { return ((UniCharMessageBuffer::uostream&) * this).operator << (val); } UniCharMessageBuffer::uostream& UniCharMessageBuffer::operator<<(float val) { return ((UniCharMessageBuffer::uostream&) * this).operator << (val); } UniCharMessageBuffer::uostream& UniCharMessageBuffer::operator<<(double val) { return ((UniCharMessageBuffer::uostream&) * this).operator << (val); } UniCharMessageBuffer::uostream& UniCharMessageBuffer::operator<<(long double val) { return ((UniCharMessageBuffer::uostream&) * this).operator << (val); } UniCharMessageBuffer::uostream& UniCharMessageBuffer::operator<<(void* val) { return ((UniCharMessageBuffer::uostream&) * this).operator << (val); } #endif // LOG4CXX_UNICHAR_API #if LOG4CXX_UNICHAR_API && LOG4CXX_CFSTRING_API #include #include UniCharMessageBuffer& UniCharMessageBuffer::operator<<(const CFStringRef& msg) { const LOG4CXX_NS::UniChar* chars = CFStringGetCharactersPtr(msg); if (chars != 0) { return operator<<(chars); } else { size_t length = CFStringGetLength(msg); std::vector tmp(length); CFStringGetCharacters(msg, CFRangeMake(0, length), &tmp[0]); if (m_priv->stream) { std::basic_string s(&tmp[0], tmp.size()); *m_priv->stream << s; } else { m_priv->buf.append(&tmp[0], tmp.size()); } } return *this; } UniCharMessageBuffer& MessageBuffer::operator<<(const CFStringRef& msg) { m_priv->ubuf = std::make_unique(); return (*m_priv->ubuf) << msg; } #elif LOG4CXX_CFSTRING_API #include #include CharMessageBuffer& CharMessageBuffer::operator<<(const CFStringRef& msg) { LOG4CXX_DECODE_CFSTRING(tmp, msg); if (m_priv->stream) { *m_priv->stream << tmp; } else { m_priv->buf.append(tmp); } return *this; } #if LOG4CXX_WCHAR_T_API CharMessageBuffer& MessageBuffer::operator<<(const CFStringRef& msg) { LOG4CXX_DECODE_CFSTRING(tmp, msg); return m_priv->cbuf << tmp; } #endif // LOG4CXX_WCHAR_T_API #endif // LOG4CXX_CFSTRING_API apache-log4cxx-1.3.1/src/main/cpp/relativetimedateformat.cpp0000644000175100001770000000252014721727031023435 0ustar runnerdocker/* * 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. */ #define __STDC_CONSTANT_MACROS #include #include #include #include LOG4CXX_NS::helpers::RelativeTimeDateFormat::RelativeTimeDateFormat() : DateFormat(), startTime(LOG4CXX_NS::spi::LoggingEvent::getStartTime()) { } void LOG4CXX_NS::helpers::RelativeTimeDateFormat::format( LogString& s, log4cxx_time_t date, Pool& p) const { int64_t interval = (date - startTime) / int64_t(1000); StringHelper::toString(interval, p, s); } apache-log4cxx-1.3.1/src/main/cpp/bufferedwriter.cpp0000644000175100001770000000374614721727031021726 0ustar runnerdocker/* * 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. */ #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; struct BufferedWriter::BufferedWriterPriv { BufferedWriterPriv(WriterPtr& out1, size_t sz1) : out(out1), sz(sz1) {} WriterPtr out; size_t sz; LogString buf; }; IMPLEMENT_LOG4CXX_OBJECT(BufferedWriter) BufferedWriter::BufferedWriter(WriterPtr& out1) : BufferedWriter(out1, 1024) { } BufferedWriter::BufferedWriter(WriterPtr& out1, size_t sz1) : m_priv(std::make_unique(out1, sz1)) { } BufferedWriter::~BufferedWriter() { } void BufferedWriter::close(Pool& p) { flush(p); m_priv->out->close(p); } void BufferedWriter::flush(Pool& p) { if (m_priv->buf.length() > 0) { m_priv->out->write(m_priv->buf, p); m_priv->buf.erase(m_priv->buf.begin(), m_priv->buf.end()); } } void BufferedWriter::write(const LogString& str, Pool& p) { if (m_priv->buf.length() + str.length() > m_priv->sz) { m_priv->out->write(m_priv->buf, p); m_priv->buf.erase(m_priv->buf.begin(), m_priv->buf.end()); } if (str.length() > m_priv->sz) { m_priv->out->write(str, p); } else { m_priv->buf.append(str); } } apache-log4cxx-1.3.1/src/main/cpp/writerappender.cpp0000644000175100001770000001527214721727031021737 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; using namespace LOG4CXX_NS::spi; #define _priv static_cast(m_priv.get()) IMPLEMENT_LOG4CXX_OBJECT(WriterAppender) WriterAppender::WriterAppender() : AppenderSkeleton (std::make_unique()) { } WriterAppender::WriterAppender(const LayoutPtr& layout1, LOG4CXX_NS::helpers::WriterPtr& writer1) : AppenderSkeleton (std::make_unique(layout1, writer1)) { Pool p; activateOptions(p); } WriterAppender::WriterAppender(const LayoutPtr& layout1) : AppenderSkeleton (std::make_unique(layout1)) { } WriterAppender::WriterAppender(std::unique_ptr priv) : AppenderSkeleton (std::move(priv)) { } WriterAppender::~WriterAppender() { finalize(); } void WriterAppender::activateOptions(Pool& p) { int errors = 0; if (_priv->layout == 0) { _priv->errorHandler->error( ((LogString) LOG4CXX_STR("No layout set for the appender named [")) + _priv->name + LOG4CXX_STR("].")); errors++; } if (_priv->writer == 0) { _priv->errorHandler->error( ((LogString) LOG4CXX_STR("No writer set for the appender named [")) + _priv->name + LOG4CXX_STR("].")); errors++; } if (errors == 0) { AppenderSkeleton::activateOptions(p); } } void WriterAppender::append(const spi::LoggingEventPtr& event, Pool& pool1) { if (!checkEntryConditions()) { return; } subAppend(event, pool1); } /** This method determines if there is a sense in attempting to append.

It checks whether there is a set output target and also if there is a set layout. If these checks fail, then the boolean value false is returned. */ bool WriterAppender::checkEntryConditions() const { return _priv->checkWriter() && _priv->checkLayout() && _priv->checkNotClosed(); } bool WriterAppender::WriterAppenderPriv::checkWriter() { if (this->writer == 0) { if (!this->warnedNoWriter) { this->errorHandler->error( LogString(LOG4CXX_STR("No output stream or file set for the appender named [")) + this->name + LOG4CXX_STR("].")); this->warnedNoWriter = true; } return false; } return true; } /** Close this appender instance. The underlying stream or writer is also closed.

Closed appenders cannot be reused. @see #setWriter */ void WriterAppender::close() { std::lock_guard lock(_priv->mutex); if (_priv->closed) { return; } _priv->closed = true; closeWriter(); } /** * Close the underlying {@link java.io.Writer}. * */ void WriterAppender::closeWriter() { if (_priv->writer != NULL) { try { // before closing we have to output out layout's footer // // Using the object's pool since this is a one-shot operation // and pool is likely to be reclaimed soon when appender is destructed. // writeFooter(_priv->pool); _priv->writer->close(_priv->pool); _priv->writer = 0; } catch (IOException& e) { LogLog::error(LogString(LOG4CXX_STR("Could not close writer for WriterAppender named ")) + _priv->name, e); } } } /** 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. */ WriterPtr WriterAppender::createWriter(OutputStreamPtr& os) { LogString enc(getEncoding()); CharsetEncoderPtr encoder; if (enc.empty()) { encoder = CharsetEncoder::getDefaultEncoder(); } else { if (StringHelper::equalsIgnoreCase(enc, LOG4CXX_STR("utf-16"), LOG4CXX_STR("UTF-16"))) { encoder = CharsetEncoder::getEncoder(LOG4CXX_STR("UTF-16BE")); } else { encoder = CharsetEncoder::getEncoder(enc); } if (encoder == NULL) { encoder = CharsetEncoder::getDefaultEncoder(); LogLog::warn(LOG4CXX_STR("Error initializing output writer.")); LogLog::warn(LOG4CXX_STR("Unsupported encoding?")); } } return WriterPtr(new OutputStreamWriter(os, encoder)); } LogString WriterAppender::getEncoding() const { return _priv->encoding; } void WriterAppender::setEncoding(const LogString& enc) { _priv->encoding = enc; } void WriterAppender::subAppend(const spi::LoggingEventPtr& event, Pool& p) { LogString msg; _priv->layout->format(msg, event, p); if (_priv->writer != NULL) { _priv->writer->write(msg, p); if (_priv->immediateFlush) { _priv->writer->flush(p); } } } void WriterAppender::writeFooter(Pool& p) { if (_priv->layout != NULL) { LogString foot; _priv->layout->appendFooter(foot, p); _priv->writer->write(foot, p); } } void WriterAppender::writeHeader(Pool& p) { if (_priv->layout != NULL) { LogString header; _priv->layout->appendHeader(header, p); _priv->writer->write(header, p); } } void WriterAppender::setWriter(const WriterPtr& newWriter) { std::lock_guard lock(_priv->mutex); setWriterInternal(newWriter); } void WriterAppender::setWriterInternal(const WriterPtr& newWriter) { _priv->writer = newWriter; } bool WriterAppender::requiresLayout() const { return true; } void WriterAppender::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("ENCODING"), LOG4CXX_STR("encoding"))) { setEncoding(value); } else { AppenderSkeleton::setOption(option, value); } } void WriterAppender::setImmediateFlush(bool value) { _priv->immediateFlush = value; } bool WriterAppender::getImmediateFlush() const { return _priv->immediateFlush; } const LOG4CXX_NS::helpers::WriterPtr WriterAppender::getWriter() const{ return _priv->writer; } apache-log4cxx-1.3.1/src/main/cpp/aprsocket.cpp0000644000175100001770000000753614721727031020703 0ustar runnerdocker/* * 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. */ #include #include #include #include #include "apr_network_io.h" #include "apr_signal.h" namespace LOG4CXX_NS { namespace helpers { struct APRSocket::APRSocketPriv : public Socket::SocketPrivate { APRSocketPriv(InetAddressPtr& address, int port) : Socket::SocketPrivate(address, port) , socket(nullptr) {} APRSocketPriv(apr_socket_t* sock, apr_pool_t* p) : pool(p, true), socket(sock) {} Pool pool; apr_socket_t* socket; }; #define _priv static_cast(m_priv.get()) APRSocket::APRSocket(InetAddressPtr& address, int port) : Socket(std::make_unique(address, port)){ apr_status_t status = apr_socket_create(&_priv->socket, APR_INET, SOCK_STREAM, APR_PROTO_TCP, _priv->pool.getAPRPool()); if (status != APR_SUCCESS) { throw SocketException(status); } LOG4CXX_ENCODE_CHAR(host, address->getHostAddress()); // create socket address (including port) apr_sockaddr_t* client_addr; status = apr_sockaddr_info_get(&client_addr, host.c_str(), APR_INET, port, 0, _priv->pool.getAPRPool()); if (status != APR_SUCCESS) { throw ConnectException(status); } // connect the socket status = apr_socket_connect(_priv->socket, client_addr); if (status != APR_SUCCESS) { throw ConnectException(status); } } APRSocket::APRSocket(apr_socket_t* s, apr_pool_t* pool) : Socket(std::make_unique(s, pool)){ apr_sockaddr_t* sa; apr_status_t status = apr_socket_addr_get(&sa, APR_REMOTE, s); if (status == APR_SUCCESS) { _priv->port = sa->port; LogString remotename; LogString remoteip; if (sa->hostname != NULL) { Transcoder::decode(sa->hostname, remotename); } char* buf = 0; status = apr_sockaddr_ip_get(&buf, sa); if (status == APR_SUCCESS) { Transcoder::decode(buf, remoteip); } _priv->address = std::make_shared(remotename, remoteip); } } size_t APRSocket::write(ByteBuffer& buf) { if (_priv->socket == 0) { throw ClosedChannelException(); } size_t totalWritten = 0; while (buf.remaining() > 0) { apr_size_t written = buf.remaining(); // while writing to the socket, we need to ignore the SIGPIPE // signal. Otherwise, when the client has closed the connection, // the send() function would not return an error but call the // SIGPIPE handler. #if APR_HAVE_SIGACTION apr_sigfunc_t* old = apr_signal(SIGPIPE, SIG_IGN); apr_status_t status = apr_socket_send(_priv->socket, buf.current(), &written); apr_signal(SIGPIPE, old); #else apr_status_t status = apr_socket_send(_priv->socket, buf.current(), &written); #endif buf.position(buf.position() + written); totalWritten += written; if (status != APR_SUCCESS) { throw SocketException(status); } } return totalWritten; } void APRSocket::close() { if (_priv->socket != 0) { apr_status_t status = apr_socket_close(_priv->socket); if (status != APR_SUCCESS) { throw SocketException(status); } _priv->socket = 0; } } } //namespace helpers } //namespace log4cxx apache-log4cxx-1.3.1/src/main/cpp/colorendpatternconverter.cpp0000644000175100001770000000342714721727031024036 0ustar runnerdocker/* * 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. */ #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::pattern; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(ColorEndPatternConverter) ColorEndPatternConverter::ColorEndPatternConverter() : LoggingEventPatternConverter(LOG4CXX_STR("Color End"), LOG4CXX_STR("colorEnd")) { } PatternConverterPtr ColorEndPatternConverter::newInstance( const std::vector& /* options */) { static WideLife instance = std::make_shared(); return instance; } void ColorEndPatternConverter::format( const LoggingEventPtr& event, LogString& toAppendTo, Pool& p) const { // Reset all colors on the output(code 0) // Code 39 would be to reset colors only toAppendTo.append(LOG4CXX_STR("\x1B[0m")); } apache-log4cxx-1.3.1/src/main/cpp/syslogwriter.cpp0000644000175100001770000000454214721727031021457 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; struct SyslogWriter::SyslogWriterPrivate { SyslogWriterPrivate(const LogString& syslogHost1, int syslogHostPort1) : syslogHost(syslogHost1), syslogHostPort(syslogHostPort1){} LogString syslogHost; int syslogHostPort; InetAddressPtr address; DatagramSocketPtr ds; }; SyslogWriter::SyslogWriter(const LogString& syslogHost1, int syslogHostPort1) : m_priv(std::make_unique(syslogHost1, syslogHostPort1)) { try { m_priv->address = InetAddress::getByName(syslogHost1); } catch (UnknownHostException& e) { LogLog::error(((LogString) LOG4CXX_STR("Could not find ")) + syslogHost1 + LOG4CXX_STR(". All logging will FAIL."), e); } try { m_priv->ds = DatagramSocket::create(); } catch (SocketException& e) { LogLog::error(((LogString) LOG4CXX_STR("Could not instantiate DatagramSocket to ")) + syslogHost1 + LOG4CXX_STR(". All logging will FAIL."), e); } } SyslogWriter::~SyslogWriter(){} void SyslogWriter::write(const LogString& source) { if (m_priv->ds != 0 && m_priv->address != 0) { LOG4CXX_ENCODE_CHAR(data, source); auto packet = std::make_shared( (void*) data.data(), (int)data.length(), m_priv->address, m_priv->syslogHostPort); m_priv->ds->send(packet); } } apache-log4cxx-1.3.1/src/main/cpp/system.cpp0000644000175100001770000000514214721727031020223 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; LogString System::getProperty(const LogString& lkey) { if (lkey.empty()) { throw IllegalArgumentException(LOG4CXX_STR("key is empty")); } LogString rv; if (lkey == LOG4CXX_STR("java.io.tmpdir")) { Pool p; const char* dir = NULL; apr_status_t stat = apr_temp_dir_get(&dir, p.getAPRPool()); if (stat == APR_SUCCESS) { Transcoder::decode(dir, rv); } return rv; } if (lkey == LOG4CXX_STR("user.dir")) { Pool p; char* dir = NULL; apr_status_t stat = apr_filepath_get(&dir, APR_FILEPATH_NATIVE, p.getAPRPool()); if (stat == APR_SUCCESS) { Transcoder::decode(dir, rv); } return rv; } #if APR_HAS_USER if (lkey == LOG4CXX_STR("user.home") || lkey == LOG4CXX_STR("user.name")) { Pool pool; apr_uid_t userid; apr_gid_t groupid; apr_pool_t* p = pool.getAPRPool(); apr_status_t stat = apr_uid_current(&userid, &groupid, p); if (stat == APR_SUCCESS) { char* username = NULL; stat = apr_uid_name_get(&username, userid, p); if (stat == APR_SUCCESS) { if (lkey == LOG4CXX_STR("user.name")) { Transcoder::decode(username, rv); } else { char* dirname = NULL; stat = apr_uid_homepath_get(&dirname, username, p); if (stat == APR_SUCCESS) { Transcoder::decode(dirname, rv); } } } } return rv; } #endif LOG4CXX_ENCODE_CHAR(key, lkey); Pool p; char* value = NULL; apr_status_t stat = apr_env_get(&value, key.c_str(), p.getAPRPool()); if (stat == APR_SUCCESS) { Transcoder::decode((const char*) value, rv); } return rv; } apache-log4cxx-1.3.1/src/main/cpp/aprdatagramsocket.cpp0000644000175100001770000001204314721727031022371 0ustar runnerdocker/* * 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. */ #include #include #include #include namespace LOG4CXX_NS { namespace helpers { #define _priv static_cast(m_priv.get()) struct APRDatagramSocket::APRDatagramSocketPriv : public DatagramSocketPriv { APRDatagramSocketPriv() : DatagramSocketPriv(), socket(nullptr) {} APRDatagramSocketPriv(int port) : DatagramSocketPriv(port), socket(nullptr) {} APRDatagramSocketPriv(int port, InetAddressPtr localAddress) : DatagramSocketPriv(port, localAddress), socket(nullptr) {} /** The APR socket */ apr_socket_t* socket; /** The memory pool for the socket */ Pool socketPool; }; APRDatagramSocket::APRDatagramSocket() : DatagramSocket(std::make_unique()){ init(); } APRDatagramSocket::APRDatagramSocket(int port) : DatagramSocket(std::make_unique(port)){ init(); } APRDatagramSocket::APRDatagramSocket(int port, InetAddressPtr laddr) : DatagramSocket(std::make_unique(port, laddr)){ init(); } void APRDatagramSocket::init() { apr_socket_t* newSocket; apr_status_t status = apr_socket_create(&newSocket, APR_INET, SOCK_DGRAM, APR_PROTO_UDP, _priv->socketPool.getAPRPool()); _priv->socket = newSocket; if (status != APR_SUCCESS) { throw SocketException(status); } } void APRDatagramSocket::receive(DatagramPacketPtr& p) { Pool addrPool; // Create the address from which to receive the datagram packet LOG4CXX_ENCODE_CHAR(hostAddr, p->getAddress()->getHostAddress()); apr_sockaddr_t* addr; apr_status_t status = apr_sockaddr_info_get(&addr, hostAddr.c_str(), APR_INET, p->getPort(), 0, addrPool.getAPRPool()); if (status != APR_SUCCESS) { throw SocketException(status); } // receive the datagram packet apr_size_t len = p->getLength(); status = apr_socket_recvfrom(addr, _priv->socket, 0, (char*)p->getData(), &len); if (status != APR_SUCCESS) { throw IOException(status); } } void APRDatagramSocket::send(DatagramPacketPtr& p) { Pool addrPool; // create the adress to which to send the datagram packet LOG4CXX_ENCODE_CHAR(hostAddr, p->getAddress()->getHostAddress()); apr_sockaddr_t* addr; apr_status_t status = apr_sockaddr_info_get(&addr, hostAddr.c_str(), APR_INET, p->getPort(), 0, addrPool.getAPRPool()); if (status != APR_SUCCESS) { throw SocketException(status); } // send the datagram packet apr_size_t len = p->getLength(); status = apr_socket_sendto(_priv->socket, addr, 0, (char*)p->getData(), &len); if (status != APR_SUCCESS) { throw IOException(status); } } void APRDatagramSocket::close(){ if (_priv->socket != 0) { apr_status_t status = apr_socket_close(_priv->socket); if (status != APR_SUCCESS) { throw SocketException(status); } _priv->socket = 0; _priv->localPort = 0; } } void APRDatagramSocket::bind(int localPort1, InetAddressPtr localAddress1) { Pool addrPool; // Create server socket address (including port number) LOG4CXX_ENCODE_CHAR(hostAddr, localAddress1->getHostAddress()); apr_sockaddr_t* server_addr; apr_status_t status = apr_sockaddr_info_get(&server_addr, hostAddr.c_str(), APR_INET, localPort1, 0, addrPool.getAPRPool()); if (status != APR_SUCCESS) { throw BindException(status); } // bind the socket to the address status = apr_socket_bind(_priv->socket, server_addr); if (status != APR_SUCCESS) { throw BindException(status); } m_priv->localPort = localPort1; m_priv->localAddress = localAddress1; } void APRDatagramSocket::connect(InetAddressPtr address1, int port1) { m_priv->address = address1; m_priv->port = port1; Pool addrPool; // create socket address LOG4CXX_ENCODE_CHAR(hostAddr, address1->getHostAddress()); apr_sockaddr_t* client_addr; apr_status_t status = apr_sockaddr_info_get(&client_addr, hostAddr.c_str(), APR_INET, m_priv->port, 0, addrPool.getAPRPool()); if (status != APR_SUCCESS) { throw ConnectException(status); } // connect the socket status = apr_socket_connect(_priv->socket, client_addr); if (status != APR_SUCCESS) { throw ConnectException(status); } } bool APRDatagramSocket::isClosed() const { return _priv->socket != nullptr; } } //namespace helpers } //namespace log4cxx apache-log4cxx-1.3.1/src/main/cpp/propertyconfigurator.cpp0000644000175100001770000004220314721727031023205 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #if LOG4CXX_ABI_VERSION <= 15 #include #else #include #endif #include #include #include #include #include #include #include #include #include #define LOG4CXX 1 #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; using namespace LOG4CXX_NS::config; using namespace LOG4CXX_NS::rolling; #include namespace LOG4CXX_NS { class PropertyWatchdog : public FileWatchdog { public: PropertyWatchdog(const File& filename) : FileWatchdog(filename) { } /** Call PropertyConfigurator#doConfigure(const String& configFileName, const spi::LoggerRepositoryPtr& hierarchy) with the filename to reconfigure log4cxx. */ void doOnChange() { PropertyConfigurator().doConfigure(file(), LogManager::getLoggerRepository()); } }; } PropertyWatchdog* PropertyConfigurator::pdog = NULL; IMPLEMENT_LOG4CXX_OBJECT(PropertyConfigurator) PropertyConfigurator::PropertyConfigurator() : registry(new std::map()) #if LOG4CXX_ABI_VERSION <= 15 , loggerFactory(new DefaultLoggerFactory()) #else , loggerFactory(new LoggerFactory()) #endif { } PropertyConfigurator::~PropertyConfigurator() { delete registry; } spi::ConfigurationStatus PropertyConfigurator::doConfigure ( const File& configFileName #if LOG4CXX_ABI_VERSION <= 15 , spi::LoggerRepositoryPtr repository #else , const spi::LoggerRepositoryPtr& repository #endif ) { auto hierarchy = repository ? repository : LogManager::getLoggerRepository(); hierarchy->setConfigured(true); Properties props; try { InputStreamPtr inputStream = InputStreamPtr( new FileInputStream(configFileName) ); props.load(inputStream); } catch (const IOException& ex) { LOG4CXX_DECODE_CHAR(lsMsg, ex.what()); LogLog::error(((LogString) LOG4CXX_STR("Could not read configuration file [")) + configFileName.getPath() + LOG4CXX_STR("]: ") + lsMsg); return spi::ConfigurationStatus::NotConfigured; } try { if (LogLog::isDebugEnabled()) { LogString debugMsg = LOG4CXX_STR("Loading configuration file [") + configFileName.getPath() + LOG4CXX_STR("]."); LogLog::debug(debugMsg); } return doConfigure(props, hierarchy); } catch (const std::exception& ex) { LogLog::error(((LogString) LOG4CXX_STR("Could not parse configuration file [")) + configFileName.getPath() + LOG4CXX_STR("]: "), ex); } return spi::ConfigurationStatus::NotConfigured; } spi::ConfigurationStatus PropertyConfigurator::configure(const File& configFilename) { return PropertyConfigurator().doConfigure(configFilename, LogManager::getLoggerRepository()); } spi::ConfigurationStatus PropertyConfigurator::configure(helpers::Properties& properties) { return PropertyConfigurator().doConfigure(properties, LogManager::getLoggerRepository()); } #if LOG4CXX_ABI_VERSION <= 15 spi::ConfigurationStatus PropertyConfigurator::configureAndWatch(const File& configFilename) { return configureAndWatch(configFilename, FileWatchdog::DEFAULT_DELAY); } #endif spi::ConfigurationStatus PropertyConfigurator::configureAndWatch( const File& configFilename, long delay) { if (pdog) { APRInitializer::unregisterCleanup(pdog); delete pdog; } spi::ConfigurationStatus stat = PropertyConfigurator().doConfigure(configFilename, LogManager::getLoggerRepository()); pdog = new PropertyWatchdog(configFilename); APRInitializer::registerCleanup(pdog); pdog->setDelay(0 < delay ? delay : FileWatchdog::DEFAULT_DELAY); pdog->start(); return stat; } spi::ConfigurationStatus PropertyConfigurator::doConfigure(helpers::Properties& properties, spi::LoggerRepositoryPtr hierarchy) { hierarchy->setConfigured(true); static const WideLife DEBUG_KEY(LOG4CXX_STR("log4j.debug")); LogString value(properties.getProperty(DEBUG_KEY)); if (!value.empty()) { LogLog::setInternalDebugging(OptionConverter::toBoolean(value, true)); } static const WideLife THRESHOLD_PREFIX(LOG4CXX_STR("log4j.threshold")); LogString thresholdStr = OptionConverter::findAndSubst(THRESHOLD_PREFIX, properties); if (!thresholdStr.empty()) { hierarchy->setThreshold(OptionConverter::toLevel(thresholdStr, Level::getAll())); if (LogLog::isDebugEnabled()) { LogLog::debug(((LogString) LOG4CXX_STR("Hierarchy threshold set to [")) + hierarchy->getThreshold()->toString() + LOG4CXX_STR("].")); } } LogString threadConfigurationValue(properties.getProperty(LOG4CXX_STR("log4j.threadConfiguration"))); if ( threadConfigurationValue == LOG4CXX_STR("NoConfiguration") ) { helpers::ThreadUtility::configure( ThreadConfigurationType::NoConfiguration ); } else if ( threadConfigurationValue == LOG4CXX_STR("BlockSignalsOnly") ) { helpers::ThreadUtility::configure( ThreadConfigurationType::BlockSignalsOnly ); } else if ( threadConfigurationValue == LOG4CXX_STR("NameThreadOnly") ) { helpers::ThreadUtility::configure( ThreadConfigurationType::NameThreadOnly ); } else if ( threadConfigurationValue == LOG4CXX_STR("BlockSignalsAndNameThread") ) { helpers::ThreadUtility::configure( ThreadConfigurationType::BlockSignalsAndNameThread ); } configureRootLogger(properties, hierarchy); configureLoggerFactory(properties); parseCatsAndRenderers(properties, hierarchy); LogLog::debug(LOG4CXX_STR("Finished configuring.")); // We don't want to hold references to appenders preventing their // destruction. registry->clear(); return spi::ConfigurationStatus::Configured; } void PropertyConfigurator::configureLoggerFactory(helpers::Properties& props) { static const WideLife LOGGER_FACTORY_KEY(LOG4CXX_STR("log4j.loggerFactory")); LogString factoryClassName = OptionConverter::findAndSubst(LOGGER_FACTORY_KEY, props); if (!factoryClassName.empty()) { if (LogLog::isDebugEnabled()) { LogString msg(LOG4CXX_STR("Setting logger factory to [")); msg += factoryClassName; msg += LOG4CXX_STR("]."); LogLog::debug(msg); } std::shared_ptr instance = std::shared_ptr( Loader::loadClass(factoryClassName).newInstance() ); loggerFactory = LOG4CXX_NS::cast( instance ); static const WideLife FACTORY_PREFIX(LOG4CXX_STR("log4j.factory.")); Pool p; PropertySetter::setProperties(loggerFactory, props, FACTORY_PREFIX, p); } } void PropertyConfigurator::configureRootLogger(helpers::Properties& props, spi::LoggerRepositoryPtr& hierarchy) { static const WideLife ROOT_CATEGORY_PREFIX(LOG4CXX_STR("log4j.rootCategory")); static const WideLife ROOT_LOGGER_PREFIX(LOG4CXX_STR("log4j.rootLogger")); LogString effectiveFrefix(ROOT_LOGGER_PREFIX); LogString value = OptionConverter::findAndSubst(ROOT_LOGGER_PREFIX, props); if (value.empty()) { value = OptionConverter::findAndSubst(ROOT_CATEGORY_PREFIX, props); effectiveFrefix = ROOT_CATEGORY_PREFIX; } if (value.empty()) { LogLog::debug(LOG4CXX_STR("Could not find root logger information. Is this OK?")); } else { LoggerPtr root = hierarchy->getRootLogger(); static const WideLife INTERNAL_ROOT_NAME(LOG4CXX_STR("root")); parseLogger(props, root, effectiveFrefix, INTERNAL_ROOT_NAME, value, true); } } void PropertyConfigurator::parseCatsAndRenderers(helpers::Properties& props, spi::LoggerRepositoryPtr& hierarchy) { static const WideLife CATEGORY_PREFIX(LOG4CXX_STR("log4j.category.")); static const WideLife LOGGER_PREFIX(LOG4CXX_STR("log4j.logger.")); for (auto key : props.propertyNames()) { if (key.find(CATEGORY_PREFIX) == 0 || key.find(LOGGER_PREFIX) == 0) { LogString loggerName; if (key.find(CATEGORY_PREFIX) == 0) { loggerName = key.substr(CATEGORY_PREFIX.value().length()); } else if (key.find(LOGGER_PREFIX.value()) == 0) { loggerName = key.substr(LOGGER_PREFIX.value().length()); } LogString value = OptionConverter::findAndSubst(key, props); LoggerPtr logger = hierarchy->getLogger(loggerName, loggerFactory); bool additivity = parseAdditivityForLogger(props, logger, loggerName); parseLogger(props, logger, key, loggerName, value, additivity); } } } bool PropertyConfigurator::parseAdditivityForLogger(helpers::Properties& props, LoggerPtr& cat, const LogString& loggerName) { static const WideLife ADDITIVITY_PREFIX(LOG4CXX_STR("log4j.additivity.")); LogString value(OptionConverter::findAndSubst(ADDITIVITY_PREFIX.value() + loggerName, props)); if (LogLog::isDebugEnabled()) { LogLog::debug((LogString) LOG4CXX_STR("Handling ") + ADDITIVITY_PREFIX.value() + loggerName + LOG4CXX_STR("=[") + value + LOG4CXX_STR("]")); } // touch additivity only if necessary if (!value.empty()) { bool additivity = OptionConverter::toBoolean(value, true); if (LogLog::isDebugEnabled()) { LogLog::debug(((LogString) LOG4CXX_STR("Setting additivity for \"")) + loggerName + ((additivity) ? LOG4CXX_STR("\" to true") : LOG4CXX_STR("\" to false"))); } return additivity; } return true; } /** This method must work for the root logger as well. */ void PropertyConfigurator::parseLogger( helpers::Properties& props, LoggerPtr& logger, const LogString& /* optionKey */, const LogString& loggerName, const LogString& value, bool additivity) { if (LogLog::isDebugEnabled()) { LogLog::debug(((LogString) LOG4CXX_STR("Parsing for [")) + loggerName + LOG4CXX_STR("] with value=[") + value + LOG4CXX_STR("].")); } // We must skip over ',' but not white space StringTokenizer st(value, LOG4CXX_STR(",")); // If value is not in the form ", appender.." or "", then we should set // the level of the logger. if (!(value.find(LOG4CXX_STR(",")) == 0 || value.empty())) { // just to be on the safe side... if (!st.hasMoreTokens()) { return; } LogString levelStr = st.nextToken(); if (LogLog::isDebugEnabled()) { LogLog::debug((LogString) LOG4CXX_STR("Level token is [") + levelStr + LOG4CXX_STR("].")); } // If the level value is inherited, set logger level value to // null. We also check that the user has not specified inherited for the // root logger. if (StringHelper::equalsIgnoreCase(levelStr, LOG4CXX_STR("INHERITED"), LOG4CXX_STR("inherited")) || StringHelper::equalsIgnoreCase(levelStr, LOG4CXX_STR("NULL"), LOG4CXX_STR("null"))) { static const WideLife INTERNAL_ROOT_NAME(LOG4CXX_STR("root")); if (loggerName == INTERNAL_ROOT_NAME.value()) { LogLog::warn(LOG4CXX_STR("The root logger cannot be set to null.")); } else { logger->setLevel(0); if (LogLog::isDebugEnabled()) { LogLog::debug((LogString) LOG4CXX_STR("Logger ") + loggerName + LOG4CXX_STR(" set to null")); } } } else { logger->setLevel(OptionConverter::toLevel(levelStr, Level::getDebug())); if (LogLog::isDebugEnabled()) { LogLog::debug((LogString) LOG4CXX_STR("Logger ") + loggerName + LOG4CXX_STR(" set to ") + logger->getLevel()->toString()); } } } AppenderPtr appender; LogString appenderName; std::vector newappenders; while (st.hasMoreTokens()) { appenderName = StringHelper::trim(st.nextToken()); if (appenderName.empty() || appenderName == LOG4CXX_STR(",")) { continue; } if (LogLog::isDebugEnabled()) { LogLog::debug(LOG4CXX_STR("Parsing appender named ") + appenderName + LOG4CXX_STR("\".")); } appender = parseAppender(props, appenderName); if (appender != 0) { newappenders.push_back(appender); } } logger->reconfigure( newappenders, additivity ); } AppenderPtr PropertyConfigurator::parseAppender( helpers::Properties& props, const LogString& appenderName) { AppenderPtr appender = registryGet(appenderName); if (appender != 0) { if (LogLog::isDebugEnabled()) { LogLog::debug((LogString) LOG4CXX_STR("Appender \"") + appenderName + LOG4CXX_STR("\" was already parsed.")); } return appender; } static const WideLife APPENDER_PREFIX(LOG4CXX_STR("log4j.appender.")); // Appender was not previously initialized. LogString prefix = APPENDER_PREFIX.value() + appenderName; LogString layoutPrefix = prefix + LOG4CXX_STR(".layout"); std::shared_ptr obj = OptionConverter::instantiateByKey( props, prefix, Appender::getStaticClass(), 0); appender = LOG4CXX_NS::cast( obj ); // Map obsolete DailyRollingFileAppender property configuration if (!appender && StringHelper::endsWith(OptionConverter::findAndSubst(prefix, props), LOG4CXX_STR("DailyRollingFileAppender"))) { appender = std::make_shared(); auto datePattern = OptionConverter::findAndSubst(prefix + LOG4CXX_STR(".datePattern"), props); if (!datePattern.empty()) props.put(prefix + LOG4CXX_STR(".fileDatePattern"), datePattern); } if (!appender) { LogLog::error((LogString) LOG4CXX_STR("Could not instantiate appender named \"") + appenderName + LOG4CXX_STR("\".")); return 0; } appender->setName(appenderName); if (appender->instanceof(OptionHandler::getStaticClass())) { Pool p; if (appender->requiresLayout()) { LayoutPtr layout; std::shared_ptr obj = OptionConverter::instantiateByKey( props, layoutPrefix, Layout::getStaticClass(), 0); layout = LOG4CXX_NS::cast( obj ); if (layout != 0) { appender->setLayout(layout); if (LogLog::isDebugEnabled()) { LogLog::debug((LogString) LOG4CXX_STR("Parsing layout options for \"") + appenderName + LOG4CXX_STR("\".")); } PropertySetter::setProperties(layout, props, layoutPrefix + LOG4CXX_STR("."), p); if (LogLog::isDebugEnabled()) { LogLog::debug((LogString) LOG4CXX_STR("End of parsing for \"") + appenderName + LOG4CXX_STR("\".")); } } } RollingFileAppenderPtr rolling = LOG4CXX_NS::cast(appender); if (rolling) { LogString rollingPolicyKey = prefix + LOG4CXX_STR(".rollingPolicy"); if (!OptionConverter::findAndSubst(rollingPolicyKey, props).empty()) { RollingPolicyPtr rollingPolicy; std::shared_ptr rolling_obj = OptionConverter::instantiateByKey( props, rollingPolicyKey, RollingPolicy::getStaticClass(), 0); rollingPolicy = LOG4CXX_NS::cast( rolling_obj ); if(rollingPolicy) { rolling->setRollingPolicy(rollingPolicy); if (LogLog::isDebugEnabled()) { LogLog::debug((LogString) LOG4CXX_STR("Parsing rolling policy options for \"") + appenderName + LOG4CXX_STR("\".")); } PropertySetter::setProperties(rollingPolicy, props, rollingPolicyKey + LOG4CXX_STR("."), p); } } LogString triggeringPolicyKey = prefix + LOG4CXX_STR(".triggeringPolicy"); if (!OptionConverter::findAndSubst(triggeringPolicyKey, props).empty()) { TriggeringPolicyPtr triggeringPolicy; std::shared_ptr triggering_obj = OptionConverter::instantiateByKey( props, triggeringPolicyKey, TriggeringPolicy::getStaticClass(), 0); triggeringPolicy = LOG4CXX_NS::cast( triggering_obj ); if(triggeringPolicy) { rolling->setTriggeringPolicy(triggeringPolicy); if (LogLog::isDebugEnabled()) { LogLog::debug((LogString) LOG4CXX_STR("Parsing triggering policy options for \"") + appenderName + LOG4CXX_STR("\".")); } PropertySetter::setProperties(triggeringPolicy, props, triggeringPolicyKey + LOG4CXX_STR("."), p); } } } PropertySetter::setProperties(appender, props, prefix + LOG4CXX_STR("."), p); if (LogLog::isDebugEnabled()) { LogLog::debug((LogString) LOG4CXX_STR("Parsed \"") + appenderName + LOG4CXX_STR("\" options.")); } } registryPut(appender); return appender; } void PropertyConfigurator::registryPut(const AppenderPtr& appender) { (*registry)[appender->getName()] = appender; } AppenderPtr PropertyConfigurator::registryGet(const LogString& name) { return (*registry)[name]; } apache-log4cxx-1.3.1/src/main/cpp/datepatternconverter.cpp0000644000175100001770000001135714721727031023147 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::pattern; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; struct DatePatternConverter::DatePatternConverterPrivate : public PatternConverterPrivate { DatePatternConverterPrivate( const LogString& name, const LogString& style, DateFormatPtr _df ): PatternConverterPrivate(name, style), df(_df) {} /** * Date format. */ LOG4CXX_NS::helpers::DateFormatPtr df; }; #define priv static_cast(m_priv.get()) IMPLEMENT_LOG4CXX_OBJECT(DatePatternConverter) DatePatternConverter::DatePatternConverter( const std::vector& options) : LoggingEventPatternConverter (std::make_unique(LOG4CXX_STR("Class Name"), LOG4CXX_STR("class name"), getDateFormat(options))) { } DatePatternConverter::~DatePatternConverter() {} DateFormatPtr DatePatternConverter::getDateFormat(const OptionsList& options) { DateFormatPtr df; int maximumCacheValidity = 1000000; if (options.size() == 0) { df = std::make_shared(); } else { LogString dateFormatStr(options[0]); if (dateFormatStr.empty() || StringHelper::equalsIgnoreCase(dateFormatStr, LOG4CXX_STR("ISO8601"), LOG4CXX_STR("iso8601"))) { df = std::make_shared(); } else if (StringHelper::equalsIgnoreCase(dateFormatStr, LOG4CXX_STR("ABSOLUTE"), LOG4CXX_STR("absolute"))) { df = std::make_shared(); } else if (StringHelper::equalsIgnoreCase(dateFormatStr, LOG4CXX_STR("DATE"), LOG4CXX_STR("date"))) { df = std::make_shared(); } else { if (dateFormatStr.find(0x25 /*'%'*/) == std::string::npos) { try { df = std::make_shared(dateFormatStr); maximumCacheValidity = CachedDateFormat::getMaximumCacheValidity(dateFormatStr); } catch (IllegalArgumentException& e) { df = std::make_shared(); LogLog::warn(((LogString) LOG4CXX_STR("Could not instantiate SimpleDateFormat with pattern ")) + dateFormatStr, e); } } else { df = std::make_shared(dateFormatStr); } } if (options.size() >= 2) { TimeZonePtr tz(TimeZone::getTimeZone(options[1])); if (tz != NULL) { df->setTimeZone(tz); } } } if (maximumCacheValidity > 0) { df = std::make_shared(df, maximumCacheValidity); } return df; } PatternConverterPtr DatePatternConverter::newInstance( const std::vector& options) { return std::make_shared(options); } void DatePatternConverter::format( const LoggingEventPtr& event, LogString& toAppendTo, Pool& p) const { priv->df->format(toAppendTo, event->getTimeStamp(), p); } /** * {@inheritDoc} */ void DatePatternConverter::format( const ObjectPtr& obj, LogString& toAppendTo, Pool& p) const { DatePtr date = LOG4CXX_NS::cast(obj); if (date != NULL) { format(date, toAppendTo, p); } else { LoggingEventPtr event = LOG4CXX_NS::cast(obj); if (event != NULL) { format(event, toAppendTo, p); } } } /** * Append formatted date to string buffer. * @param date date * @param toAppendTo buffer to which formatted date is appended. */ void DatePatternConverter::format( const DatePtr& date, LogString& toAppendTo, Pool& p) const { priv->df->format(toAppendTo, date->getTime(), p); } apache-log4cxx-1.3.1/src/main/cpp/namepatternconverter.cpp0000644000175100001770000000450714721727031023151 0ustar runnerdocker/* * 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. */ #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::pattern; using namespace LOG4CXX_NS::spi; #define priv static_cast(m_priv.get()) struct NamePatternConverter::NamePatternConverterPrivate : public PatternConverterPrivate { NamePatternConverterPrivate( const LogString& name, const LogString& style, const NameAbbreviatorPtr abbrev ) : PatternConverterPrivate( name, style ), abbreviator(abbrev) {} /** * Abbreviator. */ const NameAbbreviatorPtr abbreviator; }; IMPLEMENT_LOG4CXX_OBJECT(NamePatternConverter) NamePatternConverter::NamePatternConverter( const LogString& name1, const LogString& style1, const std::vector& options) : LoggingEventPatternConverter(std::make_unique(name1, style1, getAbbreviator(options))) { } NameAbbreviatorPtr NamePatternConverter::getAbbreviator( const std::vector& options) { if (options.size() > 0) { return NameAbbreviator::getAbbreviator(options[0]); } return NameAbbreviator::getDefaultAbbreviator(); } /** * Abbreviate name in string buffer. * @param nameStart starting position of name to abbreviate. * @param buf string buffer containing name. */ void NamePatternConverter::abbreviate(LogString::size_type nameStart, LogString& buf) const { priv->abbreviator->abbreviate(nameStart, buf); } apache-log4cxx-1.3.1/src/main/cpp/literalpatternconverter.cpp0000644000175100001770000000467414721727031023672 0ustar runnerdocker/* * 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. */ #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::pattern; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; #define priv static_cast(m_priv.get()) struct LiteralPatternConverter::LiteralPatternConverterPrivate : public PatternConverterPrivate { LiteralPatternConverterPrivate( const LogString& name, const LogString& style, const LogString& literal1 ) : PatternConverterPrivate( name, style ), literal(literal1) {} /** * String literal. */ const LogString literal; }; IMPLEMENT_LOG4CXX_OBJECT(LiteralPatternConverter) LiteralPatternConverter::LiteralPatternConverter(const LogString& literal1) : LoggingEventPatternConverter(std::make_unique (LOG4CXX_STR("Literal"), LOG4CXX_STR("literal"), literal1)) { } PatternConverterPtr LiteralPatternConverter::newInstance( const LogString& literal) { if (literal.length() == 1 && literal[0] == 0x20 /* ' ' */) { static WideLife blank = std::make_shared(literal); return blank; } return std::make_shared(literal); } void LiteralPatternConverter::format( const LoggingEventPtr& /* event */, LogString& toAppendTo, Pool& /* p */) const { toAppendTo.append(priv->literal); } void LiteralPatternConverter::format( const ObjectPtr& /* event */, LogString& toAppendTo, Pool& /* p */) const { toAppendTo.append(priv->literal); } apache-log4cxx-1.3.1/src/main/cpp/strftimedateformat.cpp0000644000175100001770000000375414721727031022612 0ustar runnerdocker/* * 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. */ #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; struct StrftimeDateFormat::StrftimeDateFormatPrivate{ StrftimeDateFormatPrivate() : timeZone(TimeZone::getDefault()) {} /** * Time zone. */ TimeZonePtr timeZone; std::string pattern; }; StrftimeDateFormat::StrftimeDateFormat(const LogString& fmt) : m_priv(std::make_unique()) { LOG4CXX_NS::helpers::Transcoder::encode(fmt, m_priv->pattern); } StrftimeDateFormat::~StrftimeDateFormat() { } void StrftimeDateFormat::format(LogString& s, log4cxx_time_t time, Pool& /* p */ ) const { apr_time_exp_t exploded; apr_status_t stat = m_priv->timeZone->explode(&exploded, time); if (stat == APR_SUCCESS) { const apr_size_t bufSize = 255; char buf[bufSize]; apr_size_t bufLen; stat = apr_strftime(buf, &bufLen, bufSize, m_priv->pattern.c_str(), &exploded); if (stat == APR_SUCCESS) { LOG4CXX_NS::helpers::Transcoder::decode(std::string(buf, bufLen), s); } } } void StrftimeDateFormat::setTimeZone(const TimeZonePtr& zone) { m_priv->timeZone = zone; } apache-log4cxx-1.3.1/src/main/cpp/loader.cpp0000644000175100001770000000462314721727031020150 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::filter; IMPLEMENT_LOG4CXX_OBJECT(Object) IMPLEMENT_LOG4CXX_OBJECT(OptionHandler) IMPLEMENT_LOG4CXX_OBJECT(ErrorHandler) IMPLEMENT_LOG4CXX_OBJECT(Appender) IMPLEMENT_LOG4CXX_OBJECT(Filter) IMPLEMENT_LOG4CXX_OBJECT(AppenderAttachable) IMPLEMENT_LOG4CXX_OBJECT(LoggerFactory) IMPLEMENT_LOG4CXX_OBJECT(LoggerRepository) IMPLEMENT_LOG4CXX_OBJECT(DenyAllFilter) IMPLEMENT_LOG4CXX_OBJECT(RepositorySelector) IMPLEMENT_LOG4CXX_OBJECT(XMLDOMNode) IMPLEMENT_LOG4CXX_OBJECT(XMLDOMDocument) IMPLEMENT_LOG4CXX_OBJECT(XMLDOMElement) IMPLEMENT_LOG4CXX_OBJECT(XMLDOMNodeList) IMPLEMENT_LOG4CXX_OBJECT(TriggeringEventEvaluator) const Class& Loader::loadClass(const LogString& clazz) { return Class::forName(clazz); } InputStreamPtr Loader::getResourceAsStream(const LogString& name) { try { return std::make_shared(name); } catch (const IOException&) { } return 0; } apache-log4cxx-1.3.1/src/main/cpp/appenderattachableimpl.cpp0000644000175100001770000001032214721727031023364 0ustar runnerdocker/* * 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. */ #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(AppenderAttachableImpl) struct AppenderAttachableImpl::priv_data { /** Array of appenders. */ AppenderList appenderList; mutable std::mutex m_mutex; }; AppenderAttachableImpl::AppenderAttachableImpl() { } #if LOG4CXX_ABI_VERSION <= 15 AppenderAttachableImpl::AppenderAttachableImpl(Pool& pool) : m_priv() { } #endif AppenderAttachableImpl::~AppenderAttachableImpl() { } void AppenderAttachableImpl::addAppender(const AppenderPtr newAppender) { // Null values for newAppender parameter are strictly forbidden. if (!newAppender) { return; } if (!m_priv) m_priv = std::make_unique(); std::lock_guard lock( m_priv->m_mutex ); AppenderList::iterator it = std::find( m_priv->appenderList.begin(), m_priv->appenderList.end(), newAppender); if (it == m_priv->appenderList.end()) { m_priv->appenderList.push_back(newAppender); } } int AppenderAttachableImpl::appendLoopOnAppenders( const spi::LoggingEventPtr& event, Pool& p) { int numberAppended = 0; if (m_priv) { // FallbackErrorHandler::error() may modify our list of appenders // while we are iterating over them (if it holds the same logger). // So, make a local copy of the appenders that we want to iterate over // before actually iterating over them. AppenderList allAppenders = getAllAppenders(); for (auto appender : allAppenders) { appender->doAppend(event, p); numberAppended++; } } return numberAppended; } AppenderList AppenderAttachableImpl::getAllAppenders() const { AppenderList result; if (m_priv) { std::lock_guard lock( m_priv->m_mutex ); result = m_priv->appenderList; } return result; } AppenderPtr AppenderAttachableImpl::getAppender(const LogString& name) const { AppenderPtr result; if (m_priv && !name.empty()) { std::lock_guard lock( m_priv->m_mutex ); for (auto appender : m_priv->appenderList) { if (name == appender->getName()) { result = appender; break; } } } return result; } bool AppenderAttachableImpl::isAttached(const AppenderPtr appender) const { bool result = false; if (m_priv && appender) { std::lock_guard lock( m_priv->m_mutex ); result = std::find(m_priv->appenderList.begin(), m_priv->appenderList.end(), appender) != m_priv->appenderList.end(); } return result; } void AppenderAttachableImpl::removeAllAppenders() { if (m_priv) { for (auto a : getAllAppenders()) a->close(); std::lock_guard lock( m_priv->m_mutex ); m_priv->appenderList.clear(); } } void AppenderAttachableImpl::removeAppender(const AppenderPtr appender) { if (m_priv && appender) { std::lock_guard lock( m_priv->m_mutex ); auto it = std::find(m_priv->appenderList.begin(), m_priv->appenderList.end(), appender); if (it != m_priv->appenderList.end()) { m_priv->appenderList.erase(it); } } } void AppenderAttachableImpl::removeAppender(const LogString& name) { if (m_priv && !name.empty()) { std::lock_guard lock( m_priv->m_mutex ); auto it = std::find_if(m_priv->appenderList.begin(), m_priv->appenderList.end() , [&name](const AppenderPtr& appender) -> bool { return name == appender->getName(); }); if (it != m_priv->appenderList.end()) m_priv->appenderList.erase(it); } } apache-log4cxx-1.3.1/src/main/cpp/propertiespatternconverter.cpp0000644000175100001770000000571614721727031024430 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::pattern; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; #define priv static_cast(m_priv.get()) struct PropertiesPatternConverter::PropertiesPatternConverterPrivate : public PatternConverterPrivate { PropertiesPatternConverterPrivate( const LogString& name, const LogString& style, const LogString& propertyName ) : PatternConverterPrivate( name, style ), option(propertyName) {} /** * Name of property to output. */ const LogString option; }; IMPLEMENT_LOG4CXX_OBJECT(PropertiesPatternConverter) PropertiesPatternConverter::PropertiesPatternConverter(const LogString& name1, const LogString& propertyName) : LoggingEventPatternConverter( std::make_unique(name1, LOG4CXX_STR("property"), propertyName)) { } PatternConverterPtr PropertiesPatternConverter::newInstance( const std::vector& options) { if (options.size() == 0) { static WideLife def = std::make_shared( LOG4CXX_STR("Properties"), LOG4CXX_STR("")); return def; } LogString converterName(LOG4CXX_STR("Property{")); converterName.append(options[0]); converterName.append(LOG4CXX_STR("}")); return std::make_shared(converterName, options[0]); } void PropertiesPatternConverter::format( const LoggingEventPtr& event, LogString& toAppendTo, Pool& /* p */) const { if (priv->option.length() == 0) { toAppendTo.append(1, (logchar) 0x7B /* '{' */); for (auto const& item : event->getMDCKeySet()) { toAppendTo.append(1, (logchar) 0x7B /* '{' */); toAppendTo.append(item); toAppendTo.append(1, (logchar) 0x2C /* ',' */); event->getMDC(item, toAppendTo); toAppendTo.append(1, (logchar) 0x7D /* '}' */); } toAppendTo.append(1, (logchar) 0x7D /* '}' */); } else { event->getMDC(priv->option, toAppendTo); } } apache-log4cxx-1.3.1/src/main/cpp/simplelayout.cpp0000644000175100001770000000244314721727031021427 0ustar runnerdocker/* * 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. */ #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::spi; IMPLEMENT_LOG4CXX_OBJECT(SimpleLayout) void SimpleLayout::format(LogString& output, const spi::LoggingEventPtr& event, LOG4CXX_NS::helpers::Pool&) const { output.append(event->getLevel()->toString()); output.append(LOG4CXX_STR(" - ")); output.append(event->getRenderedMessage()); output.append(LOG4CXX_EOL); } apache-log4cxx-1.3.1/src/main/cpp/socket.cpp0000644000175100001770000000267614721727031020200 0ustar runnerdocker/* * 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. */ #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(Socket) Socket::Socket(std::unique_ptr priv) : m_priv(std::move(priv)){ } Socket::~Socket() { } InetAddressPtr Socket::getInetAddress() const { return m_priv->address; } int Socket::getPort() const { return m_priv->port; } SocketUniquePtr Socket::create(InetAddressPtr& address, int port){ return std::make_unique(address, port); } apache-log4cxx-1.3.1/src/main/cpp/exception.cpp0000644000175100001770000002603314721727031020677 0ustar runnerdocker/* * 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. */ #define __STDC_WANT_LIB_EXT1__ 1 #include #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; Exception::Exception(const LogString& msg1) { LOG4CXX_ENCODE_CHAR(m, msg1); size_t len = m.size(); if (len > MSG_SIZE) { len = MSG_SIZE; } #if defined(__STDC_LIB_EXT1__) || defined(__STDC_SECURE_LIB__) memcpy_s(msg, sizeof msg, m.data(), len); #else memcpy(msg, m.data(), len); #endif msg[len] = 0; } Exception::Exception(const char* m) { #if defined(__STDC_LIB_EXT1__) || defined(__STDC_SECURE_LIB__) strncpy_s(msg, sizeof msg, m, MSG_SIZE); #else strncpy(msg, m, MSG_SIZE); #endif msg[MSG_SIZE] = 0; } Exception::Exception(const Exception& src) : std::exception() { #if defined(__STDC_LIB_EXT1__) || defined(__STDC_SECURE_LIB__) strcpy_s(msg, sizeof msg, src.msg); #else strncpy(msg, src.msg, MSG_SIZE); msg[MSG_SIZE] = 0; #endif } Exception& Exception::operator=(const Exception& src) { #if defined(__STDC_LIB_EXT1__) || defined(__STDC_SECURE_LIB__) strcpy_s(msg, sizeof msg, src.msg); #else strncpy(msg, src.msg, MSG_SIZE); msg[MSG_SIZE] = 0; #endif return *this; } const char* Exception::what() const throw() { return msg; } RuntimeException::RuntimeException(log4cxx_status_t stat) : Exception(formatMessage(stat)) { } RuntimeException::RuntimeException(const LogString& msg1) : Exception(msg1) { } RuntimeException::RuntimeException(const RuntimeException& src) : Exception(src) { } RuntimeException& RuntimeException::operator=(const RuntimeException& src) { Exception::operator=(src); return *this; } LogString RuntimeException::formatMessage(log4cxx_status_t stat) { LogString s(LOG4CXX_STR("RuntimeException: return code = ")); Pool p; StringHelper::toString(stat, p, s); return s; } NullPointerException::NullPointerException(const LogString& msg1) : RuntimeException(msg1) { } NullPointerException::NullPointerException(const NullPointerException& src) : RuntimeException(src) { } NullPointerException& NullPointerException::operator=(const NullPointerException& src) { RuntimeException::operator=(src); return *this; } IllegalArgumentException::IllegalArgumentException(const LogString& msg1) : RuntimeException(msg1) { } IllegalArgumentException::IllegalArgumentException(const IllegalArgumentException& src) : RuntimeException(src) { } IllegalArgumentException& IllegalArgumentException::operator=(const IllegalArgumentException& src) { RuntimeException::operator=(src); return *this; } IOException::IOException() : Exception(LOG4CXX_STR("IO exception")) { } IOException::IOException(log4cxx_status_t stat) : Exception(formatMessage(stat)) { } IOException::IOException(const LogString& type, log4cxx_status_t stat) : Exception(formatMessage(type, stat)) { } IOException::IOException(const LogString& msg1) : Exception(msg1) { } IOException::IOException(const IOException& src) : Exception(src) { } IOException& IOException::operator=(const IOException& src) { Exception::operator=(src); return *this; } LogString IOException::formatMessage(log4cxx_status_t stat) { return formatMessage(LOG4CXX_STR("IO Exception"), stat); } LogString IOException::formatMessage(const LogString& type, log4cxx_status_t stat) { LogString s = type; char err_buff[1024] = {0}; apr_strerror(stat, err_buff, sizeof(err_buff)); if (0 == err_buff[0] || 0 == strncmp(err_buff, "APR does not understand", 23)) { s.append(LOG4CXX_STR(": error code ")); Pool p; StringHelper::toString(stat, p, s); } else { s.append(LOG4CXX_STR(" - ")); std::string sMsg = err_buff; LOG4CXX_DECODE_CHAR(lsMsg, sMsg); s.append(lsMsg); } return s; } MissingResourceException::MissingResourceException(const LogString& key) : Exception(formatMessage(key)) { } MissingResourceException::MissingResourceException(const MissingResourceException& src) : Exception(src) { } MissingResourceException& MissingResourceException::operator=(const MissingResourceException& src) { Exception::operator=(src); return *this; } LogString MissingResourceException::formatMessage(const LogString& key) { LogString s(LOG4CXX_STR("MissingResourceException: resource key = \"")); s.append(key); s.append(LOG4CXX_STR("\".")); return s; } PoolException::PoolException(log4cxx_status_t stat) : Exception(formatMessage(stat)) { } PoolException::PoolException(const PoolException& src) : Exception(src) { } PoolException& PoolException::operator=(const PoolException& src) { Exception::operator=(src); return *this; } LogString PoolException::formatMessage(log4cxx_status_t) { return LOG4CXX_STR("Pool exception"); } TranscoderException::TranscoderException(log4cxx_status_t stat) : Exception(formatMessage(stat)) { } TranscoderException::TranscoderException(const TranscoderException& src) : Exception(src) { } TranscoderException& TranscoderException::operator=(const TranscoderException& src) { Exception::operator=(src); return *this; } LogString TranscoderException::formatMessage(log4cxx_status_t) { return LOG4CXX_STR("Transcoder exception"); } InterruptedException::InterruptedException() : Exception(LOG4CXX_STR("Thread was interrupted")) { } InterruptedException::InterruptedException(log4cxx_status_t stat) : Exception(formatMessage(stat)) { } InterruptedException::InterruptedException(const InterruptedException& src) : Exception(src) { } InterruptedException& InterruptedException::operator=(const InterruptedException& src) { Exception::operator=(src); return *this; } LogString InterruptedException::formatMessage(log4cxx_status_t stat) { LogString s(LOG4CXX_STR("InterruptedException: stat = ")); Pool p; StringHelper::toString(stat, p, s); return s; } ThreadException::ThreadException(log4cxx_status_t stat) : Exception(formatMessage(stat)) { } ThreadException::ThreadException(const LogString& msg) : Exception(msg) { } ThreadException::ThreadException(const ThreadException& src) : Exception(src) { } ThreadException& ThreadException::operator=(const ThreadException& src) { Exception::operator=(src); return *this; } LogString ThreadException::formatMessage(log4cxx_status_t stat) { LogString s(LOG4CXX_STR("Thread exception: stat = ")); Pool p; StringHelper::toString(stat, p, s); return s; } IllegalMonitorStateException::IllegalMonitorStateException(const LogString& msg1) : Exception(msg1) { } IllegalMonitorStateException::IllegalMonitorStateException(const IllegalMonitorStateException& src) : Exception(src) { } IllegalMonitorStateException& IllegalMonitorStateException::operator=(const IllegalMonitorStateException& src) { Exception::operator=(src); return *this; } InstantiationException::InstantiationException(const LogString& msg1) : Exception(msg1) { } InstantiationException::InstantiationException(const InstantiationException& src) : Exception(src) { } InstantiationException& InstantiationException::operator=(const InstantiationException& src) { Exception::operator=(src); return *this; } ClassNotFoundException::ClassNotFoundException(const LogString& className) : Exception(formatMessage(className)) { } ClassNotFoundException::ClassNotFoundException(const ClassNotFoundException& src) : Exception(src) { } ClassNotFoundException& ClassNotFoundException::operator=(const ClassNotFoundException& src) { Exception::operator=(src); return *this; } LogString ClassNotFoundException::formatMessage(const LogString& className) { LogString s(LOG4CXX_STR("Class not found: ")); s.append(className); return s; } NoSuchElementException::NoSuchElementException() : Exception(LOG4CXX_STR("No such element")) { } NoSuchElementException::NoSuchElementException(const NoSuchElementException& src) : Exception(src) { } NoSuchElementException& NoSuchElementException::operator=(const NoSuchElementException& src) { Exception::operator=(src); return *this; } IllegalStateException::IllegalStateException() : Exception(LOG4CXX_STR("Illegal state")) { } IllegalStateException::IllegalStateException(const IllegalStateException& src) : Exception(src) { } IllegalStateException& IllegalStateException::operator=(const IllegalStateException& src) { Exception::operator=(src); return *this; } SocketException::SocketException(const LogString& msg) : IOException(msg) { } SocketException::SocketException(log4cxx_status_t status) : IOException(status) { } SocketException::SocketException(const SocketException& src) : IOException(src) { } SocketException& SocketException::operator=(const SocketException& src) { IOException::operator=(src); return *this; } ConnectException::ConnectException(log4cxx_status_t status) : SocketException(status) { } ConnectException::ConnectException(const ConnectException& src) : SocketException(src) { } ConnectException& ConnectException::operator=(const ConnectException& src) { SocketException::operator=(src); return *this; } ClosedChannelException::ClosedChannelException() : SocketException(LOG4CXX_STR("Attempt to write to closed socket")) { } ClosedChannelException::ClosedChannelException(const ClosedChannelException& src) : SocketException(src) { } ClosedChannelException& ClosedChannelException::operator=(const ClosedChannelException& src) { SocketException::operator=(src); return *this; } BindException::BindException(log4cxx_status_t status) : SocketException(status) { } BindException::BindException(const BindException& src) : SocketException(src) { } BindException& BindException::operator=(const BindException& src) { SocketException::operator=(src); return *this; } InterruptedIOException::InterruptedIOException(const LogString& msg) : IOException(msg) { } InterruptedIOException::InterruptedIOException(const InterruptedIOException& src) : IOException(src) { } InterruptedIOException& InterruptedIOException::operator=(const InterruptedIOException& src) { IOException::operator=(src); return *this; } SocketTimeoutException::SocketTimeoutException() : InterruptedIOException(LOG4CXX_STR("SocketTimeoutException")) { } SocketTimeoutException::SocketTimeoutException(const SocketTimeoutException& src) : InterruptedIOException(src) { } SocketTimeoutException& SocketTimeoutException::operator=(const SocketTimeoutException& src) { InterruptedIOException::operator=(src); return *this; } apache-log4cxx-1.3.1/src/main/cpp/loggingevent.cpp0000644000175100001770000001766714721727031021406 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; struct LoggingEvent::LoggingEventPrivate { LoggingEventPrivate(const ThreadSpecificData::NamePairPtr p = ThreadSpecificData::getNames()) : timeStamp(0), #if LOG4CXX_ABI_VERSION <= 15 threadName(p->idString), threadUserName(p->threadName), #endif pNames(p) { } LoggingEventPrivate ( const LogString& logger1 , const LevelPtr& level1 , const LocationInfo& locationInfo1 , LogString&& message1 , const ThreadSpecificData::NamePairPtr p = ThreadSpecificData::getNames() ) : logger(logger1), level(level1), message(std::move(message1)), timeStamp(Date::currentTime()), locationInfo(locationInfo1), #if LOG4CXX_ABI_VERSION <= 15 threadName(p->idString), threadUserName(p->threadName), #endif chronoTimeStamp(std::chrono::microseconds(timeStamp)), pNames(p) { } LoggingEventPrivate( const LogString& logger1, const LevelPtr& level1, const LogString& message1, const LocationInfo& locationInfo1, const ThreadSpecificData::NamePairPtr& p = ThreadSpecificData::getNames() ) : logger(logger1), level(level1), message(message1), timeStamp(Date::currentTime()), locationInfo(locationInfo1), #if LOG4CXX_ABI_VERSION <= 15 threadName(p->idString), threadUserName(p->threadName), #endif chronoTimeStamp(std::chrono::microseconds(timeStamp)), pNames(p) { } ~LoggingEventPrivate() { delete properties; } /** * The name of the logger used to make the logging request **/ LogString logger; /** severity level of logging event. */ LevelPtr level; #if LOG4CXX_ABI_VERSION <= 15 mutable LogString* ndc{NULL}; mutable MDC::Map* mdcCopy{NULL}; #endif /** * A map of String keys and String values. */ std::map* properties{NULL}; #if LOG4CXX_ABI_VERSION <= 15 mutable bool ndcLookupRequired{false}; mutable bool mdcCopyLookupRequired{false}; #endif /** The application supplied message. */ LogString message; /** The number of microseconds elapsed since 1970-01-01 * at the time this logging event was created. */ log4cxx_time_t timeStamp; /** The source code location where the logging request was made. */ const spi::LocationInfo locationInfo; #if LOG4CXX_ABI_VERSION <= 15 const LogString& threadName; const LogString& threadUserName; #endif std::chrono::time_point chronoTimeStamp; /** * Thread names that remain valid for the lifetime of this LoggingEvent * (i.e. even after thread termination). */ ThreadSpecificData::NamePairPtr pNames; struct DiagnosticContext { Optional ctx; MDC::Map map; }; /** * Used to hold the diagnostic context when the lifetime * of this LoggingEvent exceeds the duration of the logging request. */ mutable std::unique_ptr dc; }; IMPLEMENT_LOG4CXX_OBJECT(LoggingEvent) // // Accessor for start time. // log4cxx_time_t LoggingEvent::getStartTime() { return APRInitializer::getStartTime(); } LoggingEvent::LoggingEvent() : m_priv(std::make_unique()) { } LoggingEvent::LoggingEvent ( const LogString& logger , const LevelPtr& level , const LocationInfo& location , LogString&& message ) : m_priv(std::make_unique(logger, level, location, std::move(message))) { } LoggingEvent::LoggingEvent( const LogString& logger1, const LevelPtr& level1, const LogString& message1, const LocationInfo& locationInfo1) : m_priv(std::make_unique(logger1, level1, message1, locationInfo1)) { } LoggingEvent::~LoggingEvent() { } const LogString& LoggingEvent::getThreadUserName() const { return m_priv->pNames->threadName; } bool LoggingEvent::getNDC(LogString& dest) const { bool result = false; // Use the copy of the diagnostic context if it exists. // Otherwise use the NDC that is associated with the thread. if (m_priv->dc) { result = bool(m_priv->dc->ctx); if (result) dest.append(NDC::getFullMessage(m_priv->dc->ctx.value())); } else result = NDC::get(dest); return result; } bool LoggingEvent::getMDC(const LogString& key, LogString& dest) const { bool result = false; // Use the copy of the diagnostic context if it exists. // Otherwise use the MDC that is associated with the thread. if (m_priv->dc) { auto& map = m_priv->dc->map; auto it = map.find(key); if (it != map.end() && !it->second.empty()) { dest.append(it->second); result = true; } } else result = MDC::get(key, dest); return result; } LoggingEvent::KeySet LoggingEvent::getMDCKeySet() const { LoggingEvent::KeySet result; if (m_priv->dc) { for (auto const& item : m_priv->dc->map) result.push_back(item.first); } else if (auto pData = ThreadSpecificData::getCurrentData()) { for (auto const& item : pData->getMap()) result.push_back(item.first); } return result; } void LoggingEvent::LoadDC() const { m_priv->dc = std::make_unique(); if (auto pData = ThreadSpecificData::getCurrentData()) { m_priv->dc->map = pData->getMap(); auto& stack = pData->getStack(); if (!stack.empty()) m_priv->dc->ctx = stack.top(); } } #if LOG4CXX_ABI_VERSION <= 15 void LoggingEvent::getMDCCopy() const { if (!m_priv->dc) LoadDC(); } #endif bool LoggingEvent::getProperty(const LogString& key, LogString& dest) const { if (m_priv->properties == 0) { return false; } std::map::const_iterator it = m_priv->properties->find(key); if (it != m_priv->properties->end()) { dest.append(it->second); return true; } return false; } LoggingEvent::KeySet LoggingEvent::getPropertyKeySet() const { LoggingEvent::KeySet set; if (m_priv->properties) { for (auto item : *m_priv->properties) { set.push_back(item.first); } } return set; } void LoggingEvent::setProperty(const LogString& key, const LogString& value) { if (m_priv->properties == 0) { m_priv->properties = new std::map; } (*m_priv->properties)[key] = value; } const LevelPtr& LoggingEvent::getLevel() const { return m_priv->level; } const LogString& LoggingEvent::getLoggerName() const { return m_priv->logger; } const LogString& LoggingEvent::getMessage() const { return m_priv->message; } const LogString& LoggingEvent::getRenderedMessage() const { return m_priv->message; } const LogString& LoggingEvent::getThreadName() const { return m_priv->pNames->idString; } log4cxx_time_t LoggingEvent::getTimeStamp() const { return m_priv->timeStamp; } const LOG4CXX_NS::spi::LocationInfo& LoggingEvent::getLocationInformation() const { return m_priv->locationInfo; } std::chrono::time_point LoggingEvent::getChronoTimeStamp() const{ return m_priv->chronoTimeStamp; } apache-log4cxx-1.3.1/src/main/cpp/shortfilelocationpatternconverter.cpp0000644000175100001770000000343614721727031025761 0ustar runnerdocker/* * 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. */ #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::pattern; using namespace LOG4CXX_NS::spi; using namespace helpers; IMPLEMENT_LOG4CXX_OBJECT(ShortFileLocationPatternConverter) ShortFileLocationPatternConverter::ShortFileLocationPatternConverter() : LoggingEventPatternConverter(LOG4CXX_STR("Short File Location"), LOG4CXX_STR("shortFile")) { } PatternConverterPtr ShortFileLocationPatternConverter::newInstance( const std::vector & /* options */ ) { static WideLife instance(new ShortFileLocationPatternConverter()); return instance; } void ShortFileLocationPatternConverter::format( const LoggingEventPtr &event, LogString &toAppendTo, Pool & /* p */ ) const { append(toAppendTo, event->getLocationInformation().getShortFileName()); } apache-log4cxx-1.3.1/src/main/cpp/filewatchdog.cpp0000644000175100001770000001060714721727031021341 0ustar runnerdocker/* * 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. */ #define __STDC_CONSTANT_MACROS #include #include #include #include #include #include #include #include #include #if LOG4CXX_EVENTS_AT_EXIT #include #endif using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; long FileWatchdog::DEFAULT_DELAY = 60000; struct FileWatchdog::FileWatchdogPrivate{ FileWatchdogPrivate(const File& file1) : file(file1), delay(DEFAULT_DELAY), lastModif(0), warnedAlready(false), interrupted(0), thread() #if LOG4CXX_EVENTS_AT_EXIT , atExitRegistryRaii([this]{stopWatcher();}) #endif { } ~FileWatchdogPrivate() { stopWatcher(); } /** The name of the file to observe for changes. */ File file; /** The delay to observe between every check. By default set DEFAULT_DELAY.*/ long delay; log4cxx_time_t lastModif; bool warnedAlready; volatile int interrupted; Pool pool; std::thread thread; std::condition_variable interrupt; std::mutex interrupt_mutex; #if LOG4CXX_EVENTS_AT_EXIT helpers::AtExitRegistry::Raii atExitRegistryRaii; #endif void stopWatcher() { { std::lock_guard lock(interrupt_mutex); interrupted = 0xFFFF; } interrupt.notify_all(); if (thread.joinable()) thread.join(); } }; FileWatchdog::FileWatchdog(const File& file1) : m_priv(std::make_unique(file1)) { } FileWatchdog::~FileWatchdog() { if (m_priv->thread.joinable()) stop(); } bool FileWatchdog::is_active() { return m_priv->thread.joinable(); } void FileWatchdog::stop() { LogLog::debug(LOG4CXX_STR("Stopping file watchdog")); m_priv->stopWatcher(); } const File& FileWatchdog::file() { return m_priv->file; } void FileWatchdog::checkAndConfigure() { if (LogLog::isDebugEnabled()) { LogString msg(LOG4CXX_STR("Checking [")); msg += m_priv->file.getPath(); msg += LOG4CXX_STR("]"); LogLog::debug(msg); } Pool pool1; if (!m_priv->file.exists(pool1)) { if (!m_priv->warnedAlready) { LogLog::warn(LOG4CXX_STR("[") + m_priv->file.getPath() + LOG4CXX_STR("] does not exist.")); m_priv->warnedAlready = true; } } else { auto thisMod = m_priv->file.lastModified(pool1); if (thisMod > m_priv->lastModif) { m_priv->lastModif = thisMod; doOnChange(); m_priv->warnedAlready = false; } } } void FileWatchdog::run() { if (LogLog::isDebugEnabled()) { LogString msg(LOG4CXX_STR("Checking [")); msg += m_priv->file.getPath(); msg += LOG4CXX_STR("] at "); StringHelper::toString((int)m_priv->delay, m_priv->pool, msg); msg += LOG4CXX_STR(" ms interval"); LogLog::debug(msg); } while (!is_interrupted()) { std::unique_lock lock( m_priv->interrupt_mutex ); if (!m_priv->interrupt.wait_for( lock, std::chrono::milliseconds( m_priv->delay ), std::bind(&FileWatchdog::is_interrupted, this) )) checkAndConfigure(); } if (LogLog::isDebugEnabled()) { LogString msg2(LOG4CXX_STR("Stop checking [")); msg2 += m_priv->file.getPath(); msg2 += LOG4CXX_STR("]"); LogLog::debug(msg2); } } void FileWatchdog::start() { checkAndConfigure(); if (!m_priv->thread.joinable()) { m_priv->interrupted = 0; m_priv->thread = ThreadUtility::instance()->createThread(LOG4CXX_STR("FileWatchdog"), &FileWatchdog::run, this); } } bool FileWatchdog::is_interrupted() { return m_priv->interrupted == 0xFFFF; } void FileWatchdog::setDelay(long delay1){ m_priv->delay = delay1; } apache-log4cxx-1.3.1/src/main/cpp/transform.cpp0000644000175100001770000000543014721727031020712 0ustar runnerdocker/* * 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. */ #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; void Transform::appendEscapingTags( LogString& buf, const LogString& input) { //Check if the string is zero length -- if so, return //what was sent in. if (input.length() == 0 ) { return; } logchar specials[] = { 0x22 /* " */, 0x26 /* & */, 0x3C /* < */, 0x3E /* > */, 0x00 }; size_t start = 0; size_t special = input.find_first_of(specials, start); while (special != LogString::npos) { if (special > start) { buf.append(input, start, special - start); } switch (input[special]) { case 0x22: buf.append(LOG4CXX_STR(""")); break; case 0x26: buf.append(LOG4CXX_STR("&")); break; case 0x3C: buf.append(LOG4CXX_STR("<")); break; case 0x3E: buf.append(LOG4CXX_STR(">")); break; default: buf.append(1, input[special]); break; } start = special + 1; if (special < input.size()) { special = input.find_first_of(specials, start); } else { special = LogString::npos; } } if (start < input.size()) { buf.append(input, start, input.size() - start); } } void Transform::appendEscapingCDATA( LogString& buf, const LogString& input) { static const WideLife CDATA_END(LOG4CXX_STR("]]>")); static const WideLife CDATA_EMBEDED_END(LOG4CXX_STR("]]>]]> static_cast<AsyncAppenderPriv*>(m_priv._Mypair._Myval2) static_cast<ConsoleAppenderPriv*>(m_priv._Mypair._Myval2) static_cast<WriterAppenderPriv*>(m_priv._Mypair._Myval2) static_cast<FileAppenderPriv*>(m_priv._Mypair._Myval2) static_cast<TelnetAppenderPriv*>(m_priv._Mypair._Myval2) static_cast<SocketAppenderSkeletonPriv*>(m_priv._Mypair._Myval2) static_cast<SMTPPriv*>(m_priv._Mypair._Myval2) static_cast<SyslogAppenderPriv*>(m_priv._Mypair._Myval2) static_cast<XMLSocketAppenderPriv*>(m_priv._Mypair._Myval2) static_cast<APRDatagramSocketPriv*>(m_priv._Mypair._Myval2) static_cast<APRServerSocketPriv*>(m_priv._Mypair._Myval2) static_cast<APRSocketPriv*>(m_priv._Mypair._Myval2) static_cast<ColorPatternConverterPrivate*>(m_priv._Mypair._Myval2) static_cast<DatePatternConverterPrivate*>(m_priv._Mypair._Myval2) static_cast<LiteralPatternConverterPrivate*>(m_priv._Mypair._Myval2) static_cast<PropertiesPatternConverterPrivate*>(m_priv._Mypair._Myval2) static_cast<AndFilterPrivate*>(m_priv._Mypair._Myval2) static_cast<LocationInfoFilterPrivate*>(m_priv._Mypair._Myval2) static_cast<LoggerMatchFilterPrivate*>(m_priv._Mypair._Myval2) static_cast<MapFilterPrivate*>(m_priv._Mypair._Myval2) static_cast<LevelMatchFilterPrivate*>(m_priv._Mypair._Myval2) static_cast<LevelRangeFilterPrivate*>(m_priv._Mypair._Myval2) static_cast<StringMatchFilterPrivate*>(m_priv._Mypair._Myval2) static_cast<FileRenameActionPrivate*>(m_priv._Mypair._Myval2) static_cast<FixedWindowRollingPolicyPrivate*>(m_priv._Mypair._Myval2) static_cast<GZCompressActionPrivate*>(m_priv._Mypair._Myval2) static_cast<RollingFileAppenderPriv*>(m_priv._Mypair._Myval2) static_cast<MultiprocessRollingFileAppenderPriv*>(m_priv._Mypair._Myval2) static_cast<ZipCompressActionPrivate*>(m_priv._Mypair._Myval2) static_cast<NTEventLogAppenderPrivate*>(m_priv._Mypair._Myval2) static_cast<DBAppenderPriv*>(m_priv._Mypair._Myval2) static_cast<ODBCAppenderPriv*>(m_priv._Mypair._Myval2) apache-log4cxx-1.3.1/src/main/cpp/nameabbreviator.cpp0000644000175100001770000002021314721727031022034 0ustar runnerdocker/* * 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. */ #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::pattern; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(NameAbbreviator) NameAbbreviator::NameAbbreviator() { } NameAbbreviator::~NameAbbreviator() { } namespace LOG4CXX_NS { namespace pattern { /** * Abbreviator that simply appends full name to buffer. */ class NOPAbbreviator : public NameAbbreviator { public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(NOPAbbreviator) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(NOPAbbreviator) LOG4CXX_CAST_ENTRY_CHAIN(NameAbbreviator) END_LOG4CXX_CAST_MAP() /** * Constructor. */ NOPAbbreviator() { } /** * {@inheritDoc} */ void abbreviate(LogString::size_type /* nameStart */, LogString& /* buf */) const override { } }; /** * Abbreviator that drops starting path elements. */ class MaxElementAbbreviator : public NameAbbreviator { /** * Maximum number of path elements to output. */ const int count; public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(MaxElementAbbreviator) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(MaxElementAbbreviator) LOG4CXX_CAST_ENTRY_CHAIN(NameAbbreviator) END_LOG4CXX_CAST_MAP() /** * Create new instance. * @param count maximum number of path elements to output. */ MaxElementAbbreviator(const int count1) : count(count1) { } /** * Abbreviate name. * @param buf buffer to append abbreviation. * @param nameStart start of name to abbreviate. */ void abbreviate(LogString::size_type nameStart, LogString& buf) const override { // We substract 1 from 'len' when assigning to 'end' to avoid out of // bounds exception in return r.substring(end+1, len). This can happen if // precision is 1 and the logger name ends with a dot. LogString::size_type end = buf.length() - 1; for (LogString::size_type i = count; i > 0; i--) { end = buf.rfind(0x2E /* '.' */, end - 1); if ((end == LogString::npos) || (end < nameStart)) { return; } } buf.erase(buf.begin() + nameStart, buf.begin() + (end + 1)); } }; /** * Fragment of an pattern abbreviator. * */ class PatternAbbreviatorFragment { /** * Count of initial characters of element to output. */ LogString::size_type charCount; /** * Character used to represent dropped characters. * '\0' indicates no representation of dropped characters. */ logchar ellipsis; public: /** * Creates a PatternAbbreviatorFragment. * @param charCount number of initial characters to preserve. * @param ellipsis character to represent elimination of characters, * '\0' if no ellipsis is desired. */ PatternAbbreviatorFragment( const int charCount1, const logchar ellipsis1) : charCount(charCount1), ellipsis(ellipsis1) { } PatternAbbreviatorFragment() : charCount(0), ellipsis(0) { } PatternAbbreviatorFragment(const PatternAbbreviatorFragment& src) : charCount(src.charCount), ellipsis(src.ellipsis) { } PatternAbbreviatorFragment& operator=(const PatternAbbreviatorFragment& src) { charCount = src.charCount; ellipsis = src.ellipsis; return *this; } /** * Abbreviate element of name. * @param buf buffer to receive element. * @param startPos starting index of name element. * @return starting index of next element. */ LogString::size_type abbreviate(LogString& buf, LogString::size_type startPos) const { LogString::size_type nextDot = buf.find(0x2E /* '.' */, startPos); if (nextDot != LogString::npos) { if ((nextDot - startPos) > charCount) { buf.erase(buf.begin() + (startPos + charCount), buf.begin() + nextDot); nextDot = startPos + charCount; if (ellipsis != 0x00) { buf.insert(nextDot, 1, ellipsis); nextDot++; } } nextDot++; } return nextDot; } }; /** * Pattern abbreviator. * * */ class PatternAbbreviator : public NameAbbreviator { /** * Element abbreviation patterns. */ std::vector fragments; public: DECLARE_ABSTRACT_LOG4CXX_OBJECT(PatternAbbreviator) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(PatternAbbreviator) LOG4CXX_CAST_ENTRY_CHAIN(NameAbbreviator) END_LOG4CXX_CAST_MAP() /** * Create PatternAbbreviator. * * @param fragments element abbreviation patterns. */ PatternAbbreviator(const std::vector& fragments1) : fragments(fragments1) { if (fragments1.size() == 0) { throw IllegalArgumentException(LOG4CXX_STR("fragments parameter must contain at least one element")); } } /** * Abbreviate name. * @param buf buffer that abbreviated name is appended. * @param nameStart start of name. */ void abbreviate(LogString::size_type nameStart, LogString& buf) const override { // // all non-terminal patterns are executed once // LogString::size_type pos = nameStart; for (LogString::size_type i = 0; (i < (fragments.size() - 1)) && (pos < buf.length()); i++) { pos = fragments[i].abbreviate(buf, pos); } // // last pattern in executed repeatedly // PatternAbbreviatorFragment terminalFragment = fragments[fragments.size() - 1]; while (pos < buf.length()) { pos = terminalFragment.abbreviate(buf, pos); } } }; } } IMPLEMENT_LOG4CXX_OBJECT(NOPAbbreviator) IMPLEMENT_LOG4CXX_OBJECT(MaxElementAbbreviator) IMPLEMENT_LOG4CXX_OBJECT(PatternAbbreviator) NameAbbreviatorPtr NameAbbreviator::getAbbreviator(const LogString& pattern) { if (pattern.length() > 0) { // if pattern is just spaces and numbers then // use MaxElementAbbreviator LogString trimmed(StringHelper::trim(pattern)); if (trimmed.length() == 0) { return getDefaultAbbreviator(); } LogString::size_type i = 0; while ( (i < trimmed.length()) && (trimmed[i] >= 0x30 /* '0' */) && (trimmed[i] <= 0x39 /* '9' */)) { i++; } // // if all blanks and digits // if (i == trimmed.length()) { return std::make_shared(StringHelper::toInt(trimmed)); } std::vector fragments; logchar ellipsis; int charCount; LogString::size_type pos = 0; while (pos < trimmed.length()) { LogString::size_type ellipsisPos = pos; if (trimmed[pos] == 0x2A /* '*' */) { charCount = INT_MAX; ellipsisPos++; } else { if ((trimmed[pos] >= 0x30 /* '0' */) && (trimmed[pos] <= 0x39 /* '9' */)) { charCount = trimmed[pos] - 0x30 /* '0' */; ellipsisPos++; } else { charCount = 0; } } ellipsis = 0; if (ellipsisPos < trimmed.length()) { ellipsis = trimmed[ellipsisPos]; if (ellipsis == 0x2E /* '.' */) { ellipsis = 0; } } fragments.push_back(PatternAbbreviatorFragment(charCount, ellipsis)); pos = trimmed.find(0x2E /* '.' */, pos); if (pos == LogString::npos) { break; } pos++; } return std::make_shared(fragments); } // // no matching abbreviation, return defaultAbbreviator // return getDefaultAbbreviator(); } /** * Gets default abbreviator. * * @return default abbreviator. */ NameAbbreviatorPtr NameAbbreviator::getDefaultAbbreviator() { static WideLife def = std::make_shared(); return def; } apache-log4cxx-1.3.1/src/main/cpp/filter.cpp0000644000175100001770000000262014721727031020162 0ustar runnerdocker/* * 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. */ #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; Filter::Filter() : m_priv(std::make_unique()) { } Filter::Filter(std::unique_ptr priv) : m_priv(std::move(priv)) { } Filter::~Filter() {} FilterPtr Filter::getNext() const { return m_priv->next; } void Filter::setNext(const FilterPtr& newNext) { m_priv->next = newNext; } void Filter::activateOptions(Pool&) { } void Filter::setOption(const LogString&, const LogString&) { } apache-log4cxx-1.3.1/src/main/cpp/patternparser.cpp0000644000175100001770000002300114721727031021563 0ustar runnerdocker/* * 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. */ #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::pattern; using namespace LOG4CXX_NS::helpers; const logchar PatternParser::ESCAPE_CHAR = 0x25; // '%' /** * Private constructor. */ PatternParser::PatternParser() { } bool PatternParser::isUnicodeIdentifierStart(logchar ch) { // // greatly simplified version checks if // character is USACII alpha or number // return (ch >= 0x41 /* 'A' */ && ch <= 0x5A /* 'Z' */) || (ch >= 0x61 /* 'a' */ && ch <= 0x7A /* 'z' */) || (ch >= 0x30 /* '0' */ && ch <= 0x39 /* '9' */); } bool PatternParser::isUnicodeIdentifierPart(logchar ch) { // // greatly simplified version checks if // character is USACII alpha or number // return isUnicodeIdentifierStart(ch) || (ch == 0x5F /* '_' */); } size_t PatternParser::extractConverter( logchar lastChar, const LogString& pattern, LogString::size_type i, LogString& convBuf, LogString& currentLiteral) { if (!convBuf.empty()) { convBuf.erase(convBuf.begin(), convBuf.end()); } // 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 (!isUnicodeIdentifierStart(lastChar)) { return i; } convBuf.append(1, lastChar); while ( (i < pattern.length()) && isUnicodeIdentifierPart(pattern[i])) { convBuf.append(1, pattern[i]); currentLiteral.append(1, pattern[i]); //System.out.println("conv buffer is now ["+convBuf+"]."); i++; } return i; } size_t PatternParser::extractOptions(const LogString& pattern, LogString::size_type i, std::vector& options) { while ((i < pattern.length()) && (pattern[i] == 0x7B /* '{' */)) { size_t end = pattern.find(0x7D /* '}' */, i); if (end == pattern.npos) { break; } LogString r(pattern.substr(i + 1, end - i - 1)); options.push_back(r); i = end + 1; } return i; } void PatternParser::parse( const LogString& pattern, std::vector& patternConverters, std::vector& formattingInfos, const PatternMap& rules) { LogString currentLiteral; size_t patternLength = pattern.length(); int state = LITERAL_STATE; logchar c; size_t i = 0; FormattingInfoPtr formattingInfo(FormattingInfo::getDefault()); while (i < patternLength) { c = pattern[i++]; switch (state) { case LITERAL_STATE: // In literal state, the last char is always a literal. if (i == patternLength) { currentLiteral.append(1, c); continue; } if (c == ESCAPE_CHAR) { // peek at the next char. if (pattern[i] == ESCAPE_CHAR) { currentLiteral.append(1, c); i++; // move pointer } else { if (!currentLiteral.empty()) { patternConverters.push_back( LiteralPatternConverter::newInstance(currentLiteral)); formattingInfos.push_back(FormattingInfo::getDefault()); currentLiteral.erase(currentLiteral.begin(), currentLiteral.end()); } currentLiteral.append(1, c); // append % state = CONVERTER_STATE; formattingInfo = FormattingInfo::getDefault(); } } else { currentLiteral.append(1, c); } break; case CONVERTER_STATE: currentLiteral.append(1, c); switch (c) { case 0x2D: // '-' formattingInfo = std::make_shared( true, formattingInfo->getMinLength(), formattingInfo->getMaxLength()); break; case 0x2E: // '.' state = DOT_STATE; break; default: if ((c >= 0x30 /* '0' */) && (c <= 0x39 /* '9' */)) { formattingInfo = std::make_shared( formattingInfo->isLeftAligned(), c - 0x30 /* '0' */, formattingInfo->getMaxLength()); state = MIN_STATE; } else { i = finalizeConverter( c, pattern, i, currentLiteral, formattingInfo, rules, patternConverters, formattingInfos); // Next pattern is assumed to be a literal. state = LITERAL_STATE; formattingInfo = FormattingInfo::getDefault(); if (!currentLiteral.empty()) { currentLiteral.erase(currentLiteral.begin(), currentLiteral.end()); } } } // switch break; case MIN_STATE: currentLiteral.append(1, c); if ((c >= 0x30 /* '0' */) && (c <= 0x39 /* '9' */)) { formattingInfo = std::make_shared( formattingInfo->isLeftAligned(), (formattingInfo->getMinLength() * 10) + (c - 0x30 /* '0' */), formattingInfo->getMaxLength()); } else if (c == 0x2E /* '.' */) { state = DOT_STATE; } else { i = finalizeConverter( c, pattern, i, currentLiteral, formattingInfo, rules, patternConverters, formattingInfos); state = LITERAL_STATE; formattingInfo = FormattingInfo::getDefault(); if (!currentLiteral.empty()) { currentLiteral.erase(currentLiteral.begin(), currentLiteral.end()); } } break; case DOT_STATE: currentLiteral.append(1, c); if ((c >= 0x30 /* '0' */) && (c <= 0x39 /* '9' */)) { formattingInfo = std::make_shared( formattingInfo->isLeftAligned(), formattingInfo->getMinLength(), c - 0x30 /* '0' */); state = MAX_STATE; } else { LogLog::error(LOG4CXX_STR("Error in pattern, was expecting digit.")); state = LITERAL_STATE; } break; case MAX_STATE: currentLiteral.append(1, c); if ((c >= 0x30 /* '0' */) && (c <= 0x39 /* '9' */)) { formattingInfo = std::make_shared( formattingInfo->isLeftAligned(), formattingInfo->getMinLength(), (formattingInfo->getMaxLength() * 10) + (c - 0x30 /* '0' */)); } else { i = finalizeConverter( c, pattern, i, currentLiteral, formattingInfo, rules, patternConverters, formattingInfos); state = LITERAL_STATE; formattingInfo = FormattingInfo::getDefault(); if (!currentLiteral.empty()) { currentLiteral.erase(currentLiteral.begin(), currentLiteral.end()); } } break; } // switch } // while if (currentLiteral.length() != 0) { patternConverters.push_back( LiteralPatternConverter::newInstance(currentLiteral)); formattingInfos.push_back(FormattingInfo::getDefault()); } } PatternConverterPtr PatternParser::createConverter( const LogString& converterId, LogString& currentLiteral, const PatternMap& rules, std::vector& options) { LogString converterName(converterId); for (size_t i = converterId.length(); i > 0; i--) { converterName = converterName.substr(0, i); PatternMap::const_iterator iter = rules.find(converterName); if (iter != rules.end()) { currentLiteral.erase(currentLiteral.begin(), currentLiteral.end() - (converterId.length() - i)); return (iter->second)(options); } } LogLog::error(LogString(LOG4CXX_STR("Unrecognized format specifier ")) + converterId); return PatternConverterPtr(); } size_t PatternParser::finalizeConverter( logchar c, const LogString& pattern, size_t i, LogString& currentLiteral, const FormattingInfoPtr& formattingInfo, const PatternMap& rules, std::vector& patternConverters, std::vector& formattingInfos) { LogString convBuf; i = extractConverter(c, pattern, i, convBuf, currentLiteral); if (convBuf.empty()) { LogLog::error(LOG4CXX_STR("Empty conversion specifier")); patternConverters.push_back( LiteralPatternConverter::newInstance(currentLiteral)); formattingInfos.push_back(FormattingInfo::getDefault()); } else { LogString converterId(convBuf); std::vector options; i = extractOptions(pattern, i, options); PatternConverterPtr pc( createConverter( converterId, currentLiteral, rules, options)); if (pc == NULL) { LogString msg(LOG4CXX_STR("Unrecognized conversion specifier [")); msg.append(converterId); msg.append(LOG4CXX_STR("] in conversion pattern.")); LogLog::error(msg); patternConverters.push_back( LiteralPatternConverter::newInstance(currentLiteral)); formattingInfos.push_back(FormattingInfo::getDefault()); } else { patternConverters.push_back(pc); formattingInfos.push_back(formattingInfo); if (currentLiteral.length() > 0) { patternConverters.push_back( LiteralPatternConverter::newInstance(currentLiteral)); formattingInfos.push_back(FormattingInfo::getDefault()); } } } if (!currentLiteral.empty()) { currentLiteral.erase(currentLiteral.begin(), currentLiteral.end()); } return i; } apache-log4cxx-1.3.1/src/main/cpp/methodlocationpatternconverter.cpp0000644000175100001770000000332414721727031025236 0ustar runnerdocker/* * 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. */ #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::pattern; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(MethodLocationPatternConverter) MethodLocationPatternConverter::MethodLocationPatternConverter() : LoggingEventPatternConverter(LOG4CXX_STR("Method"), LOG4CXX_STR("method")) { } PatternConverterPtr MethodLocationPatternConverter::newInstance( const std::vector& /* options */ ) { static WideLife def = std::make_shared(); return def; } void MethodLocationPatternConverter::format( const LoggingEventPtr& event, LogString& toAppendTo, Pool& /* p */ ) const { append(toAppendTo, event->getLocationInformation().getMethodName()); } apache-log4cxx-1.3.1/src/main/cpp/ndcpatternconverter.cpp0000644000175100001770000000321214721727031022765 0ustar runnerdocker/* * 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. */ #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::pattern; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(NDCPatternConverter) NDCPatternConverter::NDCPatternConverter() : LoggingEventPatternConverter(LOG4CXX_STR("NDC"), LOG4CXX_STR("ndc")) { } PatternConverterPtr NDCPatternConverter::newInstance( const std::vector& /* options */) { static WideLife def = std::make_shared(); return def; } void NDCPatternConverter::format( const LoggingEventPtr& event, LogString& toAppendTo, Pool& /* p */) const { if (!event->getNDC(toAppendTo)) { toAppendTo.append(LOG4CXX_STR("null")); } } apache-log4cxx-1.3.1/src/main/cpp/socketappenderskeleton.cpp0000644000175100001770000001634314721727031023460 0ustar runnerdocker/* * 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. */ #define __STDC_CONSTANT_MACROS #include #include #include #include #include #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; using namespace LOG4CXX_NS::net; #define _priv static_cast(m_priv.get()) SocketAppenderSkeleton::SocketAppenderSkeleton(int defaultPort, int reconnectionDelay) : AppenderSkeleton(std::make_unique(defaultPort, reconnectionDelay)) { } SocketAppenderSkeleton::SocketAppenderSkeleton(helpers::InetAddressPtr address, int port, int reconnectionDelay) : AppenderSkeleton(std::make_unique(address, port, reconnectionDelay)) { } SocketAppenderSkeleton::SocketAppenderSkeleton(const LogString& host, int port, int reconnectionDelay) : AppenderSkeleton(std::make_unique(host, port, reconnectionDelay)) { } SocketAppenderSkeleton::SocketAppenderSkeleton(std::unique_ptr priv) : AppenderSkeleton (std::move(priv)) { } SocketAppenderSkeleton::~SocketAppenderSkeleton() { finalize(); } void SocketAppenderSkeleton::activateOptions(Pool& p) { AppenderSkeleton::activateOptions(p); connect(p); } void SocketAppenderSkeleton::close() { _priv->stopMonitor(); cleanUp(_priv->pool); } void SocketAppenderSkeleton::connect(Pool& p) { if (_priv->address == 0) { LogLog::error(LogString(LOG4CXX_STR("No remote host is set for Appender named \"")) + _priv->name + LOG4CXX_STR("\".")); } else { cleanUp(p); try { if (LogLog::isDebugEnabled()) { LogString msg(LOG4CXX_STR("Connecting to [") + _priv->address->toString() + LOG4CXX_STR(":")); StringHelper::toString(_priv->port, p, msg); msg += LOG4CXX_STR("]."); LogLog::debug(msg); } SocketPtr socket = Socket::create(_priv->address, _priv->port); setSocket(socket, p); } catch (SocketException& e) { LogString msg = LOG4CXX_STR("Could not connect to [") + _priv->address->toString() + LOG4CXX_STR(":"); StringHelper::toString(_priv->port, p, msg); msg += LOG4CXX_STR("]."); fireConnector(); // fire the connector thread LogLog::error(msg, e); } } } void SocketAppenderSkeleton::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("REMOTEHOST"), LOG4CXX_STR("remotehost"))) { setRemoteHost(value); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("PORT"), LOG4CXX_STR("port"))) { setPort(OptionConverter::toInt(value, getDefaultPort())); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("LOCATIONINFO"), LOG4CXX_STR("locationinfo"))) { setLocationInfo(OptionConverter::toBoolean(value, false)); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("RECONNECTIONDELAY"), LOG4CXX_STR("reconnectiondelay"))) { setReconnectionDelay(OptionConverter::toInt(value, getDefaultDelay())); } else { AppenderSkeleton::setOption(option, value); } } void SocketAppenderSkeleton::fireConnector() { std::lock_guard lock(_priv->mutex); if ( !_priv->thread.joinable() ) { LogLog::debug(LOG4CXX_STR("Connector thread not alive: starting monitor.")); _priv->thread = ThreadUtility::instance()->createThread( LOG4CXX_STR("SocketAppend"), &SocketAppenderSkeleton::monitor, this ); } } void SocketAppenderSkeleton::monitor() { Pool p; SocketPtr socket; while (!is_closed()) { try { if (LogLog::isDebugEnabled()) { LogString msg(LOG4CXX_STR("Attempting connection to [") + _priv->address->toString() + LOG4CXX_STR(":")); StringHelper::toString(_priv->port, p, msg); msg += LOG4CXX_STR("]."); LogLog::debug(msg); } socket = Socket::create(_priv->address, _priv->port); setSocket(socket, p); if (LogLog::isDebugEnabled()) { LogLog::debug(LOG4CXX_STR("Connection established. Exiting connector thread.")); } return; } catch (ConnectException& e) { LogLog::error(LOG4CXX_STR("Remote host ") + _priv->address->toString() + LOG4CXX_STR(" refused connection."), e); } catch (IOException& e) { LogString msg(LOG4CXX_STR("Could not connect to [") + _priv->address->toString() + LOG4CXX_STR(":")); StringHelper::toString(_priv->port, p, msg); msg += LOG4CXX_STR("]."); LogLog::error(msg, e); } if (_priv->reconnectionDelay > 0) { if (LogLog::isDebugEnabled()) { LogString msg(LOG4CXX_STR("Waiting ")); StringHelper::toString(_priv->reconnectionDelay, p, msg); msg += LOG4CXX_STR(" ms before retrying [") + _priv->address->toString() + LOG4CXX_STR(":"); StringHelper::toString(_priv->port, p, msg); msg += LOG4CXX_STR("]."); LogLog::debug(msg); } std::unique_lock lock( _priv->interrupt_mutex ); if (_priv->interrupt.wait_for( lock, std::chrono::milliseconds( _priv->reconnectionDelay ), std::bind(&SocketAppenderSkeleton::is_closed, this) )) break; } } } void SocketAppenderSkeleton::SocketAppenderSkeletonPriv::stopMonitor() { { std::lock_guard lock(this->interrupt_mutex); if (this->closed) return; this->closed = true; } this->interrupt.notify_all(); if (this->thread.joinable()) this->thread.join(); } bool SocketAppenderSkeleton::is_closed() { return _priv->closed; } void SocketAppenderSkeleton::setRemoteHost(const LogString& host) { _priv->address = helpers::InetAddress::getByName(host); _priv->remoteHost.assign(host); } const LogString& SocketAppenderSkeleton::getRemoteHost() const { return _priv->remoteHost; } void SocketAppenderSkeleton::setPort(int port1) { _priv->port = port1; } int SocketAppenderSkeleton::getPort() const { return _priv->port; } void SocketAppenderSkeleton::setLocationInfo(bool locationInfo1) { _priv->locationInfo = locationInfo1; } bool SocketAppenderSkeleton::getLocationInfo() const { return _priv->locationInfo; } void SocketAppenderSkeleton::setReconnectionDelay(int reconnectionDelay1) { _priv->reconnectionDelay = reconnectionDelay1; } int SocketAppenderSkeleton::getReconnectionDelay() const { return _priv->reconnectionDelay; } apache-log4cxx-1.3.1/src/main/cpp/socketoutputstream.cpp0000644000175100001770000000366714721727031022676 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; struct SocketOutputStream::SocketOutputStreamPrivate { ByteList array; SocketPtr socket; }; IMPLEMENT_LOG4CXX_OBJECT(SocketOutputStream) SocketOutputStream::SocketOutputStream(const SocketPtr& socket1) : m_priv(std::make_unique()) { m_priv->socket = socket1; } SocketOutputStream::~SocketOutputStream() { } void SocketOutputStream::close(Pool& p) { flush(p); m_priv->socket->close(); } void SocketOutputStream::flush(Pool& /* p */) { if (m_priv->array.size() > 0) { ByteBuffer buf((char*) &m_priv->array[0], m_priv->array.size()); m_priv->socket->write(buf); m_priv->array.resize(0); } } void SocketOutputStream::write(ByteBuffer& buf, Pool& /* p */ ) { if (buf.remaining() > 0) { size_t sz = m_priv->array.size(); m_priv->array.resize(sz + buf.remaining()); memcpy(&m_priv->array[sz], buf.current(), buf.remaining()); buf.position(buf.limit()); } } apache-log4cxx-1.3.1/src/main/cpp/locationinfofilter.cpp0000644000175100001770000001017114721727031022567 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::filter; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; #define priv static_cast(m_priv.get()) struct LocationInfoFilter::LocationInfoFilterPrivate : public FilterPrivate { LocationInfoFilterPrivate() : FilterPrivate(), acceptOnMatch(true), mustMatchAll(false), lineNumber(-1) {} bool acceptOnMatch; bool mustMatchAll; // true = AND; false = OR int lineNumber; std::string methodName; }; IMPLEMENT_LOG4CXX_OBJECT(LocationInfoFilter) LocationInfoFilter::LocationInfoFilter() : Filter(std::make_unique()) { } LocationInfoFilter::~LocationInfoFilter() {} void LocationInfoFilter::setOption( const LogString& option, const LogString& value) { LogLog::warn(option + LOG4CXX_STR(":") + value); if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("ACCEPTONMATCH"), LOG4CXX_STR("acceptonmatch"))) { priv->acceptOnMatch = OptionConverter::toBoolean(value, priv->acceptOnMatch); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("OPERATOR"), LOG4CXX_STR("operator"))) { priv->mustMatchAll = StringHelper::equalsIgnoreCase(value, LOG4CXX_STR("AND"), LOG4CXX_STR("and")) ? true : false; } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("LINENUMBER"), LOG4CXX_STR("linenumber"))) { priv->lineNumber = OptionConverter::toInt(value, -1); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("METHOD"), LOG4CXX_STR("method"))) { LOG4CXX_ENCODE_CHAR(sName, value); priv->methodName = sName; } } Filter::FilterDecision LocationInfoFilter::decide( const LOG4CXX_NS::spi::LoggingEventPtr& event) const { if (priv->lineNumber == -1 && priv->methodName.empty()) { return Filter::NEUTRAL; } if (event->getLocationInformation().getLineNumber() == -1 || event->getLocationInformation().getMethodName().compare(LocationInfo::NA_METHOD) == 0){ return Filter::NEUTRAL; } bool matched = false; bool matchLineNumber = priv->lineNumber == event->getLocationInformation().getLineNumber(); bool matchMethodName = priv->methodName.compare(event->getLocationInformation().getMethodName()) == 0; if(priv->mustMatchAll){ matched = matchLineNumber && matchMethodName; }else{ matched = matchLineNumber || matchMethodName; } if (priv->acceptOnMatch) { return matched ? Filter::ACCEPT : Filter::NEUTRAL; } else { return matched ? Filter::DENY : Filter::NEUTRAL; } } void LocationInfoFilter::setAcceptOnMatch(bool acceptOnMatch1) { priv->acceptOnMatch = acceptOnMatch1; } bool LocationInfoFilter::getAcceptOnMatch() const { return priv->acceptOnMatch; } bool LocationInfoFilter::getMustMatchAll() const { return priv->mustMatchAll; } void LocationInfoFilter::setMustMatchAll(bool mustMatchAll1) { priv->mustMatchAll = mustMatchAll1; } void LocationInfoFilter::setLineNumber(int lineNum){ priv->lineNumber = lineNum; } void LocationInfoFilter::setMethodName(const LogString& methodName){ LOG4CXX_ENCODE_CHAR(sName, methodName); priv->methodName = sName; } apache-log4cxx-1.3.1/src/main/cpp/cyclicbuffer.cpp0000644000175100001770000001002114721727031021327 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; using namespace LOG4CXX_NS::spi; struct CyclicBuffer::CyclicBufferPriv { CyclicBufferPriv(int maxSize1) : ea(maxSize1), first(0), last(0), numElems(0), maxSize(maxSize1) {} LOG4CXX_NS::spi::LoggingEventList ea; int first; int last; int numElems; int maxSize; }; /** Instantiate a new CyclicBuffer of at most maxSize events. The maxSize argument must a positive integer. @param maxSize The maximum number of elements in the buffer. */ CyclicBuffer::CyclicBuffer(int maxSize1) : m_priv(std::make_unique(maxSize1)) { if (maxSize1 < 1) { LogString msg(LOG4CXX_STR("The maxSize argument (")); Pool p; StringHelper::toString(maxSize1, p, msg); msg.append(LOG4CXX_STR(") is not a positive integer.")); throw IllegalArgumentException(msg); } } CyclicBuffer::~CyclicBuffer() { } /** Add an event as the last event in the buffer. */ void CyclicBuffer::add(const spi::LoggingEventPtr& event) { m_priv->ea[m_priv->last] = event; if (++m_priv->last == m_priv->maxSize) { m_priv->last = 0; } if (m_priv->numElems < m_priv->maxSize) { m_priv->numElems++; } else if (++m_priv->first == m_priv->maxSize) { m_priv->first = 0; } } /** Get the ith oldest event currently in the buffer. If i is outside the range 0 to the number of elements currently in the buffer, then null is returned. */ spi::LoggingEventPtr CyclicBuffer::get(int i) { if (i < 0 || i >= m_priv->numElems) { return 0; } return m_priv->ea[(m_priv->first + i) % m_priv->maxSize]; } /** Get the oldest (first) element in the buffer. The oldest element is removed from the buffer. */ spi::LoggingEventPtr CyclicBuffer::get() { LoggingEventPtr r; if (m_priv->numElems > 0) { m_priv->numElems--; r = m_priv->ea[m_priv->first]; m_priv->ea[m_priv->first] = 0; if (++m_priv->first == m_priv->maxSize) { m_priv->first = 0; } } return r; } /** Resize the cyclic buffer to newSize. @throws IllegalArgumentException if newSize is negative. */ void CyclicBuffer::resize(int newSize) { if (newSize < 0) { LogString msg(LOG4CXX_STR("Negative array size [")); Pool p; StringHelper::toString(newSize, p, msg); msg.append(LOG4CXX_STR("] not allowed.")); throw IllegalArgumentException(msg); } if (newSize == m_priv->numElems) { return; // nothing to do } LoggingEventList temp(newSize); int loopLen = newSize < m_priv->numElems ? newSize : m_priv->numElems; int i; for (i = 0; i < loopLen; i++) { temp[i] = m_priv->ea[m_priv->first]; m_priv->ea[m_priv->first] = 0; if (++m_priv->first == m_priv->numElems) { m_priv->first = 0; } } m_priv->ea = temp; m_priv->first = 0; m_priv->numElems = loopLen; m_priv->maxSize = newSize; if (loopLen == newSize) { m_priv->last = 0; } else { m_priv->last = loopLen; } } int CyclicBuffer::getMaxSize() const { return m_priv->maxSize; } int CyclicBuffer::length() const { return m_priv->numElems; } apache-log4cxx-1.3.1/src/main/cpp/optionconverter.cpp0000644000175100001770000002454514721727031022147 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include #include namespace LOG4CXX_NS { class ConfiguratorWatchdog : public helpers::FileWatchdog { spi::ConfiguratorPtr m_config; public: ConfiguratorWatchdog(const spi::ConfiguratorPtr& config, const File& filename) : helpers::FileWatchdog(filename) , m_config(config) { } /** Call PropertyConfigurator#doConfigure(const String& configFileName, const spi::LoggerRepositoryPtr& hierarchy) with the filename to reconfigure log4cxx. */ void doOnChange() override { m_config->doConfigure(file(), LogManager::getLoggerRepository()); } }; } using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; using namespace LOG4CXX_NS::spi; LogString OptionConverter::convertSpecialChars(const LogString& s) { logchar c; LogString sbuf; LogString::const_iterator i = s.begin(); while (i != s.end()) { c = *i++; if (c == 0x5C /* '\\' */) { c = *i++; switch (c) { case 0x6E: //'n' c = 0x0A; break; case 0x72: //'r' c = 0x0D; break; case 0x74: //'t' c = 0x09; break; case 0x66: //'f' c = 0x0C; break; default: break; } } sbuf.append(1, c); } return sbuf; } bool OptionConverter::toBoolean(const LogString& value, bool dEfault) { if (value.length() >= 4) { if (StringHelper::equalsIgnoreCase(value.substr(0, 4), LOG4CXX_STR("TRUE"), LOG4CXX_STR("true"))) { return true; } } if (dEfault && value.length() >= 5) { if (StringHelper::equalsIgnoreCase(value.substr(0, 5), LOG4CXX_STR("FALSE"), LOG4CXX_STR("false"))) { return false; } } return dEfault; } int OptionConverter::toInt(const LogString& value, int dEfault) { LogString trimmed(StringHelper::trim(value)); if (trimmed.empty()) { return dEfault; } LOG4CXX_ENCODE_CHAR(cvalue, trimmed); return (int) atol(cvalue.c_str()); } long OptionConverter::toFileSize(const LogString& s, long dEfault) { if (s.empty()) { return dEfault; } size_t index = s.find_first_of(LOG4CXX_STR("bB")); if (index != LogString::npos && index > 0) { long multiplier = 1; index--; if (s[index] == 0x6B /* 'k' */ || s[index] == 0x4B /* 'K' */) { multiplier = 1024; } else if (s[index] == 0x6D /* 'm' */ || s[index] == 0x4D /* 'M' */) { multiplier = 1024 * 1024; } else if (s[index] == 0x67 /* 'g'*/ || s[index] == 0x47 /* 'G' */) { multiplier = 1024 * 1024 * 1024; } return toInt(s.substr(0, index), 1) * multiplier; } return toInt(s, 1); } LogString OptionConverter::findAndSubst(const LogString& key, Properties& props) { LogString value(props.getProperty(key)); if (value.empty()) { return value; } try { return substVars(value, props); } catch (IllegalArgumentException& e) { LogLog::error(((LogString) LOG4CXX_STR("Bad option value [")) + value + LOG4CXX_STR("]."), e); return value; } } LogString OptionConverter::substVars(const LogString& val, Properties& props) { LogString sbuf; const logchar delimStartArray[] = { 0x24, 0x7B, 0 }; const LogString delimStart(delimStartArray); const logchar delimStop = 0x7D; // '}'; const size_t DELIM_START_LEN = 2; const size_t DELIM_STOP_LEN = 1; size_t i = 0; while (true) { size_t j = val.find(delimStart, i); if (j == val.npos) { // no more variables if (i == 0) { // this is a simple string return val; } else { // add the tail string which contails no variables and return the result. sbuf.append(val.substr(i, val.length() - i)); return sbuf; } } else { sbuf.append(val.substr(i, j - i)); size_t k = val.find(delimStop, j); if (k == val.npos) { LogString msg(1, (logchar) 0x22 /* '\"' */); msg.append(val); msg.append(LOG4CXX_STR("\" has no closing brace. Opening brace at position ")); Pool p; StringHelper::toString(j, p, msg); msg.append(1, (logchar) 0x2E /* '.' */); throw IllegalArgumentException(msg); } else { j += DELIM_START_LEN; LogString key = val.substr(j, k - j); // first try in System properties LogString replacement(getSystemProperty(key, LogString())); // then try props parameter if (replacement.empty()) { replacement = props.getProperty(key); } if (!replacement.empty()) { // Do variable substitution on the replacement string // such that we can solve "Hello ${x2}" as "Hello p1" // the where the properties are // x1=p1 // x2=${x1} LogString recursiveReplacement = substVars(replacement, props); sbuf.append(recursiveReplacement); } i = k + DELIM_STOP_LEN; } } } } LogString OptionConverter::getSystemProperty(const LogString& key, const LogString& def) { if (!key.empty()) { LogString value(System::getProperty(key)); if (!value.empty()) { return value; } } return def; } LevelPtr OptionConverter::toLevel(const LogString& value, const LevelPtr& defaultValue) { size_t hashIndex = value.find(LOG4CXX_STR("#")); if (hashIndex == LogString::npos) { if (value.empty()) { return defaultValue; } else { if (LogLog::isDebugEnabled()) { LogLog::debug( ((LogString) LOG4CXX_STR("OptionConverter::toLevel: no class name specified, level=[")) + value + LOG4CXX_STR("]")); } // no class name specified : use standard Level class return Level::toLevelLS(value, defaultValue); } } LogString clazz = value.substr(hashIndex + 1); LogString levelName = value.substr(0, hashIndex); if (LogLog::isDebugEnabled()) { LogLog::debug(LOG4CXX_STR("OptionConverter::toLevel: class=[") + clazz + LOG4CXX_STR("], level=[") + levelName + LOG4CXX_STR("]") ); } // This is degenerate case but you never know. if (levelName.empty()) { return Level::toLevelLS(value, defaultValue); } try { Level::LevelClass& levelClass = (Level::LevelClass&)Loader::loadClass(clazz); return levelClass.toLevel(levelName); } catch (ClassNotFoundException&) { LogLog::warn(((LogString) LOG4CXX_STR("custom level class [")) + clazz + LOG4CXX_STR("] not found.")); } catch (Exception& oops) { LogLog::warn( LOG4CXX_STR("class [") + clazz + LOG4CXX_STR("], level [") + levelName + LOG4CXX_STR("] conversion) failed."), oops); } catch (...) { LogLog::warn( LOG4CXX_STR("class [") + clazz + LOG4CXX_STR("], level [") + levelName + LOG4CXX_STR("] conversion) failed.")); } return defaultValue; } ObjectPtr OptionConverter::instantiateByKey(Properties& props, const LogString& key, const Class& superClass, const ObjectPtr& defaultValue) { // Get the value of the property in string form LogString className(findAndSubst(key, props)); if (className.empty()) { LogLog::error( ((LogString) LOG4CXX_STR("Could not find value for key ")) + key); return defaultValue; } // Trim className to avoid trailing spaces that cause problems. return OptionConverter::instantiateByClassName( StringHelper::trim(className), superClass, defaultValue); } ObjectPtr OptionConverter::instantiateByClassName(const LogString& className, const Class& superClass, const ObjectPtr& defaultValue) { if (!className.empty()) { try { const Class& classObj = Loader::loadClass(className); ObjectPtr newObject = ObjectPtr(classObj.newInstance()); if (!newObject->instanceof(superClass)) { return defaultValue; } return newObject; } catch (Exception& e) { LogLog::error(LOG4CXX_STR("Could not instantiate class [") + className + LOG4CXX_STR("]."), e); } } return defaultValue; } void OptionConverter::selectAndConfigure(const File& configFileName, const LogString& _clazz, spi::LoggerRepositoryPtr hierarchy, int delay) { ConfiguratorPtr configurator; LogString clazz = _clazz; LogString filename(configFileName.getPath()); #if LOG4CXX_HAS_DOMCONFIGURATOR if (clazz.empty() && filename.length() > 4 && StringHelper::equalsIgnoreCase( filename.substr(filename.length() - 4), LOG4CXX_STR(".XML"), LOG4CXX_STR(".xml"))) { clazz = LOG4CXX_NS::xml::DOMConfigurator::getStaticClass().getName(); } #endif if (!clazz.empty()) { if (LogLog::isDebugEnabled()) LogLog::debug(LOG4CXX_STR("Preferred configurator class: ") + clazz); const Class& clazzObj = Loader::loadClass(clazz); ObjectPtr obj = ObjectPtr(clazzObj.newInstance()); configurator = LOG4CXX_NS::cast(obj); if (configurator == 0) { LogLog::error(LOG4CXX_STR("Could not instantiate configurator [") + clazz + LOG4CXX_STR("].")); return; } } else { configurator = std::make_shared(); } if (0 < delay) { auto dog = new ConfiguratorWatchdog(configurator, configFileName); APRInitializer::registerCleanup(dog); dog->setDelay(delay); dog->start(); } else configurator->doConfigure(configFileName, hierarchy); } apache-log4cxx-1.3.1/src/main/cpp/inputstreamreader.cpp0000644000175100001770000000520414721727031022434 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(InputStreamReader) struct InputStreamReader::InputStreamReaderPrivate{ InputStreamReaderPrivate(const InputStreamPtr& in1) : in(in1), dec(CharsetDecoder::getDefaultDecoder()){} InputStreamReaderPrivate(const InputStreamPtr& in1, const CharsetDecoderPtr& dec1) : in(in1), dec(dec1) {} InputStreamPtr in; CharsetDecoderPtr dec; }; InputStreamReader::InputStreamReader(const InputStreamPtr& in1) : m_priv(std::make_unique(in1)) { if (in1 == 0) { throw NullPointerException(LOG4CXX_STR("in parameter may not be null.")); } } InputStreamReader::InputStreamReader(const InputStreamPtr& in1, const CharsetDecoderPtr& dec1) : m_priv(std::make_unique(in1, dec1)) { if (in1 == 0) { throw NullPointerException(LOG4CXX_STR("in parameter may not be null.")); } if (dec1 == 0) { throw NullPointerException(LOG4CXX_STR("dec parameter may not be null.")); } } InputStreamReader::~InputStreamReader() { } void InputStreamReader::close(Pool& ) { m_priv->in->close(); } LogString InputStreamReader::read(Pool& p) { const size_t BUFSIZE = 4096; ByteBuffer buf(p.pstralloc(BUFSIZE), BUFSIZE); LogString output; // read whole file while (m_priv->in->read(buf) >= 0) { buf.flip(); log4cxx_status_t stat = m_priv->dec->decode(buf, output); if (stat != 0) { throw IOException(LOG4CXX_STR("decode"), stat); } if (buf.remaining() > 0) { memmove(buf.data(), buf.current(), buf.remaining()); buf.limit(buf.remaining()); } else { buf.clear(); } } return output; } apache-log4cxx-1.3.1/src/main/cpp/onlyonceerrorhandler.cpp0000644000175100001770000000456414721727031023144 0ustar runnerdocker/* * 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. */ #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; using namespace LOG4CXX_NS::spi; IMPLEMENT_LOG4CXX_OBJECT(OnlyOnceErrorHandler) struct OnlyOnceErrorHandler::OnlyOnceErrorHandlerPrivate{ OnlyOnceErrorHandlerPrivate() : firstTime(true){} #if LOG4CXX_ABI_VERSION <= 15 LogString WARN_PREFIX; LogString ERROR_PREFIX; #endif mutable bool firstTime; }; OnlyOnceErrorHandler::OnlyOnceErrorHandler() : m_priv(std::make_unique()) { } OnlyOnceErrorHandler::~OnlyOnceErrorHandler(){} void OnlyOnceErrorHandler::setLogger(const LoggerPtr&) { } void OnlyOnceErrorHandler::activateOptions(Pool&) { } void OnlyOnceErrorHandler::setOption(const LogString&, const LogString&) { } void OnlyOnceErrorHandler::error(const LogString& message, const std::exception& e, int) const { if (m_priv->firstTime) { LogLog::error(message, e); m_priv->firstTime = false; } } void OnlyOnceErrorHandler::error(const LogString& message, const std::exception& e, int errorCode, const LOG4CXX_NS::spi::LoggingEventPtr&) const { error(message, e, errorCode); } void OnlyOnceErrorHandler::error(const LogString& message) const { if (m_priv->firstTime) { LogLog::error(message); m_priv->firstTime = false; } } void OnlyOnceErrorHandler::setAppender(const AppenderPtr&) { } void OnlyOnceErrorHandler::setBackupAppender(const AppenderPtr&) { } bool OnlyOnceErrorHandler::errorReported() const { return !m_priv->firstTime; } apache-log4cxx-1.3.1/src/main/cpp/mdc.cpp0000644000175100001770000001244014721727031017441 0ustar runnerdocker/* * 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. */ #include #include #include #if LOG4CXX_CFSTRING_API #include #endif using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; MDC::MDC(const std::string& key1, const std::string& value) : key() { Transcoder::decode(key1, key); LOG4CXX_DECODE_CHAR(v, value); putLS(key, v); } MDC::~MDC() { LogString prevVal; remove(key, prevVal); } void MDC::putLS(const LogString& key, const LogString& value) { ThreadSpecificData::put(key, value); } void MDC::put(const std::string& key, const std::string& value) { LOG4CXX_DECODE_CHAR(lkey, key); LOG4CXX_DECODE_CHAR(lvalue, value); putLS(lkey, lvalue); } bool MDC::get(const LogString& key, LogString& value) { ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { Map& map = data->getMap(); Map::iterator it = map.find(key); if (it != map.end()) { value.append(it->second); return true; } data->recycle(); } return false; } std::string MDC::get(const std::string& key) { LOG4CXX_DECODE_CHAR(lkey, key); LogString lvalue; if (get(lkey, lvalue)) { LOG4CXX_ENCODE_CHAR(value, lvalue); return value; } return std::string(); } bool MDC::remove(const LogString& key, LogString& value) { ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { Map& map = data->getMap(); Map::iterator it; if ((it = map.find(key)) != map.end()) { value = it->second; map.erase(it); data->recycle(); return true; } } return false; } std::string MDC::remove(const std::string& key) { LOG4CXX_DECODE_CHAR(lkey, key); LogString lvalue; if (remove(lkey, lvalue)) { LOG4CXX_ENCODE_CHAR(value, lvalue); return value; } return std::string(); } void MDC::clear() { ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { Map& map = data->getMap(); map.erase(map.begin(), map.end()); data->recycle(); } } #if LOG4CXX_WCHAR_T_API MDC::MDC(const std::wstring& key1, const std::wstring& value) : key() { Transcoder::decode(key1, key); LOG4CXX_DECODE_WCHAR(v, value); putLS(key, v); } std::wstring MDC::get(const std::wstring& key) { LOG4CXX_DECODE_WCHAR(lkey, key); LogString lvalue; if (get(lkey, lvalue)) { LOG4CXX_ENCODE_WCHAR(value, lvalue); return value; } return std::wstring(); } void MDC::put(const std::wstring& key, const std::wstring& value) { LOG4CXX_DECODE_WCHAR(lkey, key); LOG4CXX_DECODE_WCHAR(lvalue, value); putLS(lkey, lvalue); } std::wstring MDC::remove(const std::wstring& key) { LOG4CXX_DECODE_WCHAR(lkey, key); LogString lvalue; if (remove(lkey, lvalue)) { LOG4CXX_ENCODE_WCHAR(value, lvalue); return value; } return std::wstring(); } #endif #if LOG4CXX_UNICHAR_API MDC::MDC(const std::basic_string& key1, const std::basic_string& value) { Transcoder::decode(key1, key); LOG4CXX_DECODE_UNICHAR(v, value); putLS(key, v); } std::basic_string MDC::get(const std::basic_string& key) { LOG4CXX_DECODE_UNICHAR(lkey, key); LogString lvalue; if (get(lkey, lvalue)) { LOG4CXX_ENCODE_UNICHAR(value, lvalue); return value; } return std::basic_string(); } void MDC::put(const std::basic_string& key, const std::basic_string& value) { LOG4CXX_DECODE_UNICHAR(lkey, key); LOG4CXX_DECODE_UNICHAR(lvalue, value); putLS(lkey, lvalue); } std::basic_string MDC::remove(const std::basic_string& key) { LOG4CXX_DECODE_UNICHAR(lkey, key); LogString lvalue; if (remove(lkey, lvalue)) { LOG4CXX_ENCODE_UNICHAR(value, lvalue); return value; } return std::basic_string(); } #endif #if LOG4CXX_CFSTRING_API MDC::MDC(const CFStringRef& key1, const CFStringRef& value) { Transcoder::decode(key1, key); LOG4CXX_DECODE_CFSTRING(v, value); putLS(key, v); } CFStringRef MDC::get(const CFStringRef& key) { LOG4CXX_DECODE_CFSTRING(lkey, key); LogString lvalue; if (get(lkey, lvalue)) { LOG4CXX_ENCODE_CFSTRING(value, lvalue); return value; } return CFSTR(""); } void MDC::put(const CFStringRef& key, const CFStringRef& value) { LOG4CXX_DECODE_CFSTRING(lkey, key); LOG4CXX_DECODE_CFSTRING(lvalue, value); putLS(lkey, lvalue); } CFStringRef MDC::remove(const CFStringRef& key) { LOG4CXX_DECODE_CFSTRING(lkey, key); LogString lvalue; if (remove(lkey, lvalue)) { LOG4CXX_ENCODE_CFSTRING(value, lvalue); return value; } return CFSTR(""); } #endif apache-log4cxx-1.3.1/src/main/cpp/messagepatternconverter.cpp0000644000175100001770000000530214721727031023647 0ustar runnerdocker/* * 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. */ #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::pattern; IMPLEMENT_LOG4CXX_OBJECT(MessagePatternConverter) namespace { /** * Formats the message of an logging event for a quoted context */ class QuotedMessagePatternConverter : public LoggingEventPatternConverter { logchar m_quote; public: QuotedMessagePatternConverter(logchar quote) : LoggingEventPatternConverter(LOG4CXX_STR("Message"), LOG4CXX_STR("quoted")) , m_quote(quote) {} using LoggingEventPatternConverter::format; // Duplicate any quote character in the event message void format ( const spi::LoggingEventPtr& event , LogString& toAppendTo , helpers::Pool& p ) const override { auto& input = event->getRenderedMessage(); size_t endIndex, startIndex = 0; while ((endIndex = input.find(m_quote, startIndex)) != input.npos) { toAppendTo.append(input.substr(startIndex, endIndex - startIndex + 1)); toAppendTo += m_quote; startIndex = endIndex + 1; } toAppendTo.append(input.substr(startIndex)); } }; } MessagePatternConverter::MessagePatternConverter() : LoggingEventPatternConverter(LOG4CXX_STR("Message") , LOG4CXX_STR("message")) { } PatternConverterPtr MessagePatternConverter::newInstance( const std::vector& options) { if (options.empty() || options.front().empty()) { static helpers::WideLife def = std::make_shared(); return def; } return std::make_shared(options.front().front()); } void MessagePatternConverter::format ( const spi::LoggingEventPtr& event , LogString& toAppendTo , helpers::Pool& /* p */ ) const { toAppendTo.append(event->getRenderedMessage()); } apache-log4cxx-1.3.1/src/main/cpp/rollingfileappender.cpp0000644000175100001770000003520514721727031022727 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::rolling; using namespace LOG4CXX_NS::helpers; using namespace LOG4CXX_NS::spi; struct RollingFileAppender::RollingFileAppenderPriv : public FileAppenderPriv { RollingFileAppenderPriv() : FileAppenderPriv(), fileLength(0) {} /** * Triggering policy. */ TriggeringPolicyPtr triggeringPolicy; /** * Rolling policy. */ RollingPolicyPtr rollingPolicy; /** * Length of current active log file. */ size_t fileLength; /** * save the loggingevent */ spi::LoggingEventPtr _event; }; #define _priv static_cast(m_priv.get()) IMPLEMENT_LOG4CXX_OBJECT(RollingFileAppender) /** * Construct a new instance. */ RollingFileAppender::RollingFileAppender() : FileAppender (std::make_unique()) { } void RollingFileAppender::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("MAXFILESIZE"), LOG4CXX_STR("maxfilesize")) || StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("MAXIMUMFILESIZE"), LOG4CXX_STR("maximumfilesize"))) { setMaxFileSize(value); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("MAXBACKUPINDEX"), LOG4CXX_STR("maxbackupindex")) || StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("MAXIMUMBACKUPINDEX"), LOG4CXX_STR("maximumbackupindex"))) { setMaxBackupIndex(StringHelper::toInt(value)); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("FILEDATEPATTERN"), LOG4CXX_STR("filedatepattern"))) { setDatePattern(value); } else { FileAppender::setOption(option, value); } } int RollingFileAppender::getMaxBackupIndex() const { int result = 1; if (auto fwrp = LOG4CXX_NS::cast(_priv->rollingPolicy)) result = fwrp->getMaxIndex(); return result; } void RollingFileAppender::setMaxBackupIndex(int maxBackups) { auto fwrp = LOG4CXX_NS::cast(_priv->rollingPolicy); if (!fwrp) { fwrp = std::make_shared(); fwrp->setFileNamePattern(getFile() + LOG4CXX_STR(".%i")); _priv->rollingPolicy = fwrp; } fwrp->setMaxIndex(maxBackups); } size_t RollingFileAppender::getMaximumFileSize() const { size_t result = 10 * 1024 * 1024; if (auto sbtp = LOG4CXX_NS::cast(_priv->triggeringPolicy)) result = sbtp->getMaxFileSize(); return result; } void RollingFileAppender::setMaximumFileSize(size_t maxFileSize) { auto sbtp = LOG4CXX_NS::cast(_priv->triggeringPolicy); if (!sbtp) { sbtp = std::make_shared(); _priv->triggeringPolicy = sbtp; } sbtp->setMaxFileSize(maxFileSize); } void RollingFileAppender::setMaxFileSize(const LogString& value) { setMaximumFileSize(OptionConverter::toFileSize(value, long(getMaximumFileSize() + 1))); } LogString RollingFileAppender::makeFileNamePattern(const LogString& datePattern) { LogString result(getFile()); bool inLiteral = false; bool inPattern = false; for (size_t i = 0; i < datePattern.length(); i++) { if (datePattern[i] == 0x27 /* '\'' */) { inLiteral = !inLiteral; if (inLiteral && inPattern) { result.append(1, (logchar) 0x7D /* '}' */); inPattern = false; } } else { if (!inLiteral && !inPattern) { const logchar dbrace[] = { 0x25, 0x64, 0x7B, 0 }; // "%d{" result.append(dbrace); inPattern = true; } result.append(1, datePattern[i]); } } if (inPattern) { result.append(1, (logchar) 0x7D /* '}' */); } return result; } void RollingFileAppender::setDatePattern(const LogString& newPattern) { auto tbrp = LOG4CXX_NS::cast(_priv->rollingPolicy); if (!tbrp) { tbrp = std::make_shared(); _priv->rollingPolicy = tbrp; } tbrp->setFileNamePattern(makeFileNamePattern(newPattern)); } /** * Prepare instance of use. */ void RollingFileAppender::activateOptions(Pool& p) { if (!_priv->rollingPolicy) { LogLog::warn(LOG4CXX_STR("No rolling policy configured for the appender named [") + _priv->name + LOG4CXX_STR("].")); auto fwrp = std::make_shared(); fwrp->setFileNamePattern(getFile() + LOG4CXX_STR(".%i")); _priv->rollingPolicy = fwrp; } // // if no explicit triggering policy and rolling policy is both. // if (!_priv->triggeringPolicy) { TriggeringPolicyPtr trig = LOG4CXX_NS::cast(_priv->rollingPolicy); if (trig != NULL) { _priv->triggeringPolicy = trig; } } if (!_priv->triggeringPolicy) { LogLog::warn(LOG4CXX_STR("No triggering policy configured for the appender named [") + _priv->name + LOG4CXX_STR("].")); _priv->triggeringPolicy = std::make_shared(); } { std::lock_guard lock(_priv->mutex); _priv->triggeringPolicy->activateOptions(p); _priv->rollingPolicy->activateOptions(p); try { RolloverDescriptionPtr rollover1 = _priv->rollingPolicy->initialize(getFile(), getAppend(), p); if (rollover1 != NULL) { ActionPtr syncAction(rollover1->getSynchronous()); if (syncAction != NULL) { syncAction->execute(p); } _priv->fileName = rollover1->getActiveFileName(); _priv->fileAppend = rollover1->getAppend(); // // async action not yet implemented // ActionPtr asyncAction(rollover1->getAsynchronous()); if (asyncAction != NULL) { asyncAction->execute(p); } } File activeFile; activeFile.setPath(getFile()); if (getAppend()) { _priv->fileLength = activeFile.length(p); } else { _priv->fileLength = 0; } FileAppender::activateOptionsInternal(p); } catch (std::exception&) { LogLog::warn( LogString(LOG4CXX_STR("Exception will initializing RollingFileAppender named ")) + getName()); } } } /** 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. */ bool RollingFileAppender::rollover(Pool& p) { std::lock_guard lock(_priv->mutex); return rolloverInternal(p); } bool RollingFileAppender::rolloverInternal(Pool& p) { // // can't roll without a policy // if (_priv->rollingPolicy != NULL) { { try { RolloverDescriptionPtr rollover1(_priv->rollingPolicy->rollover(this->getFile(), this->getAppend(), p)); if (rollover1 != NULL) { if (rollover1->getActiveFileName() == getFile()) { closeWriter(); bool success = true; if (rollover1->getSynchronous() != NULL) { success = false; try { success = rollover1->getSynchronous()->execute(p); } catch (std::exception& ex) { LogString msg(LOG4CXX_STR("Rollover of [")); msg.append(getFile()); msg.append(LOG4CXX_STR("] failed")); _priv->errorHandler->error(msg, ex, 0); } } bool appendToExisting = true; if (success) { appendToExisting = rollover1->getAppend(); if (appendToExisting) { _priv->fileLength = File().setPath(rollover1->getActiveFileName()).length(p); } else { _priv->fileLength = 0; } ActionPtr asyncAction(rollover1->getAsynchronous()); if (asyncAction != NULL) { try { asyncAction->execute(p); } catch (std::exception& ex) { LogString msg(LOG4CXX_STR("Rollover of [")); msg.append(getFile()); msg.append(LOG4CXX_STR("] failed")); _priv->errorHandler->error(msg, ex, 0); } } } setFileInternal(rollover1->getActiveFileName(), appendToExisting, _priv->bufferedIO, _priv->bufferSize, p); } else { closeWriter(); setFileInternal(rollover1->getActiveFileName()); // Call activateOptions to create any intermediate directories(if required) FileAppender::activateOptionsInternal(p); OutputStreamPtr os(new FileOutputStream( rollover1->getActiveFileName(), rollover1->getAppend())); WriterPtr newWriter(createWriter(os)); setWriterInternal(newWriter); bool success = true; if (rollover1->getSynchronous() != NULL) { success = false; try { success = rollover1->getSynchronous()->execute(p); } catch (std::exception& ex) { LogString msg(LOG4CXX_STR("Rollover of [")); msg.append(getFile()); msg.append(LOG4CXX_STR("] failed")); _priv->errorHandler->error(msg, ex, 0); } } if (success) { if (rollover1->getAppend()) { _priv->fileLength = File().setPath(rollover1->getActiveFileName()).length(p); } else { _priv->fileLength = 0; } ActionPtr asyncAction(rollover1->getAsynchronous()); if (asyncAction != NULL) { asyncAction->execute(p); } } writeHeader(p); } return true; } } catch (std::exception& ex) { LogString msg(LOG4CXX_STR("Rollover of [")); msg.append(getFile()); msg.append(LOG4CXX_STR("] failed")); _priv->errorHandler->error(msg, ex, 0); } } } return false; } /** * {@inheritDoc} */ void RollingFileAppender::subAppend(const LoggingEventPtr& event, Pool& p) { // The rollover check must precede actual writing. This is the // only correct behavior for time driven triggers. if ( _priv->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 { _priv->_event = event; rolloverInternal(p); } catch (std::exception& ex) { LogString msg(LOG4CXX_STR("Rollover of [")); msg.append(getFile()); msg.append(LOG4CXX_STR("] failed")); _priv->errorHandler->error(msg, ex, 0); } } FileAppender::subAppend(event, p); } /** * TThe policy that implements the scheme for rolling over a log file. */ RollingPolicyPtr RollingFileAppender::getRollingPolicy() const { return _priv->rollingPolicy; } /** * The policy that determine when to trigger a log file rollover. */ TriggeringPolicyPtr RollingFileAppender::getTriggeringPolicy() const { return _priv->triggeringPolicy; } /** * Set the scheme for rolling over log files. */ void RollingFileAppender::setRollingPolicy(const RollingPolicyPtr& policy) { _priv->rollingPolicy = policy; } /** * Set policy that determine when to trigger a log file rollover. */ void RollingFileAppender::setTriggeringPolicy(const TriggeringPolicyPtr& policy) { _priv->triggeringPolicy = policy; } /** * Close appender. Waits for any asynchronous file compression actions to be completed. */ void RollingFileAppender::close() { FileAppender::close(); } namespace LOG4CXX_NS { namespace rolling { /** * Wrapper for OutputStream that will report all write * operations back to this class for file length calculations. */ class CountingOutputStream : public OutputStream { /** * Wrapped output stream. */ private: OutputStreamPtr os; /** * Rolling file appender to inform of stream writes. */ RollingFileAppender* rfa; public: /** * Constructor. * @param os output stream to wrap. * @param rfa rolling file appender to inform. */ CountingOutputStream( OutputStreamPtr& os1, RollingFileAppender* rfa1) : os(os1), rfa(rfa1) { } /** * {@inheritDoc} */ void close(Pool& p) { os->close(p); rfa = 0; } /** * {@inheritDoc} */ void flush(Pool& p) { os->flush(p); } /** * {@inheritDoc} */ void write(ByteBuffer& buf, Pool& p) { os->write(buf, p); if (rfa != 0) { rfa->incrementFileLength(buf.limit()); } } }; } } /** 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. */ WriterPtr RollingFileAppender::createWriter(OutputStreamPtr& os) { OutputStreamPtr cos = std::make_shared(os, this); return FileAppender::createWriter(cos); } /** * Get byte length of current active log file. * @return byte length of current active log file. */ size_t RollingFileAppender::getFileLength() const { return _priv->fileLength; } /** * Increments estimated byte length of current active log file. * @param increment additional bytes written to log file. */ void RollingFileAppender::incrementFileLength(size_t increment) { _priv->fileLength += increment; } apache-log4cxx-1.3.1/src/main/cpp/dbappender.cpp0000644000175100001770000002171614721727031021010 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; using namespace LOG4CXX_NS::db; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::pattern; IMPLEMENT_LOG4CXX_OBJECT(DBAppender) #define _priv static_cast(m_priv.get()) struct DBAppender::DBAppenderPriv : public AppenderSkeleton::AppenderSkeletonPrivate { DBAppenderPriv() : AppenderSkeletonPrivate() { static bool initialized = false; if (!initialized) { initialized = true; apr_status_t stat = apr_dbd_init(m_pool.getAPRPool()); assert(stat == APR_SUCCESS); } } apr_dbd_driver_t* m_driver = nullptr; apr_dbd_t* m_databaseHandle = nullptr; apr_dbd_prepared_t* preparedStmt = nullptr; std::vector mappedName; std::string driverName; std::string driverParams; std::string databaseName; std::string sqlStatement; Pool m_pool; std::vector converters; }; #define RULES_PUT(spec, cls) \ specs.insert(PatternMap::value_type(LogString(LOG4CXX_STR(spec)), cls ::newInstance)) static PatternMap getFormatSpecifiers() { PatternMap specs; if (specs.empty()) { RULES_PUT("logger", LoggerPatternConverter); RULES_PUT("class", ClassNamePatternConverter); RULES_PUT("time", DatePatternConverter); RULES_PUT("shortfilename", ShortFileLocationPatternConverter); RULES_PUT("fullfilename", FileLocationPatternConverter); RULES_PUT("location", FullLocationPatternConverter); RULES_PUT("line", LineLocationPatternConverter); RULES_PUT("message", MessagePatternConverter); RULES_PUT("method", MethodLocationPatternConverter); RULES_PUT("level", LevelPatternConverter); RULES_PUT("thread", ThreadPatternConverter); RULES_PUT("threadname", ThreadUsernamePatternConverter); RULES_PUT("ndc", NDCPatternConverter); } return specs; } DBAppender::DBAppender() : AppenderSkeleton (std::make_unique()) { } DBAppender::~DBAppender() { close(); } void DBAppender::close(){ if(_priv->m_driver && _priv->m_databaseHandle){ apr_dbd_close(_priv->m_driver, _priv->m_databaseHandle); } _priv->m_driver = nullptr; _priv->m_databaseHandle = nullptr; } void DBAppender::setOption(const LogString& option, const LogString& value){ if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("COLUMNMAPPING"), LOG4CXX_STR("columnmapping"))) { _priv->mappedName.push_back(value); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("DRIVERNAME"), LOG4CXX_STR("drivername"))) { Transcoder::encodeUTF8(value, _priv->driverName); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("DRIVERPARAMS"), LOG4CXX_STR("driverparams"))) { Transcoder::encodeUTF8(value, _priv->driverParams); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("DATABASENAME"), LOG4CXX_STR("databasename"))) { Transcoder::encodeUTF8(value, _priv->databaseName); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("SQL"), LOG4CXX_STR("sql"))) { Transcoder::encodeUTF8(value, _priv->sqlStatement); } else { AppenderSkeleton::setOption(option, value); } } void DBAppender::activateOptions(helpers::Pool& p){ apr_status_t stat = apr_dbd_get_driver(_priv->m_pool.getAPRPool(), _priv->driverName.c_str(), const_cast(&_priv->m_driver)); if(stat != APR_SUCCESS){ LogString errMsg = LOG4CXX_STR("Unable to get driver named "); LOG4CXX_DECODE_CHAR(driverName, _priv->driverName); errMsg.append(driverName); LogLog::error(errMsg); _priv->errorHandler->error(errMsg); return; } stat = apr_dbd_open(_priv->m_driver, _priv->m_pool.getAPRPool(), _priv->driverParams.c_str(), &_priv->m_databaseHandle); if(stat != APR_SUCCESS){ LogLog::error(LOG4CXX_STR("Unable to open database")); _priv->errorHandler->error(LOG4CXX_STR("Unable to open database")); return; } if(!_priv->databaseName.empty()){ apr_dbd_set_dbname(_priv->m_driver, _priv->m_pool.getAPRPool(), _priv->m_databaseHandle, _priv->databaseName.c_str()); } stat = apr_dbd_prepare(_priv->m_driver, _priv->m_pool.getAPRPool(), _priv->m_databaseHandle, _priv->sqlStatement.c_str(), "log_insert", &_priv->preparedStmt); if(stat != APR_SUCCESS){ LogString error = LOG4CXX_STR("Unable to prepare statement: "); std::string dbdErr(apr_dbd_error(_priv->m_driver, _priv->m_databaseHandle, stat)); LOG4CXX_DECODE_CHAR(dbdErrLS, dbdErr); error.append(dbdErrLS); LogLog::error(error); _priv->errorHandler->error(error); return; } auto specs = getFormatSpecifiers(); for (auto& name : _priv->mappedName) { auto pItem = specs.find(StringHelper::toLowerCase(name)); if (specs.end() == pItem) LogLog::error(name + LOG4CXX_STR(" is not a supported ColumnMapping value")); else { std::vector options; if (LOG4CXX_STR("time") == pItem->first) options.push_back(LOG4CXX_STR("yyyy-MM-ddTHH:mm:ss.SSS")); pattern::LoggingEventPatternConverterPtr converter = LOG4CXX_NS::cast((pItem->second)(options)); _priv->converters.push_back(converter); } } } void DBAppender::append(const spi::LoggingEventPtr& event, helpers::Pool& p){ std::vector ls_args; std::vector args; int stat; int num_rows; if(_priv->m_driver == nullptr || _priv->m_databaseHandle == nullptr || _priv->preparedStmt == nullptr){ _priv->errorHandler->error(LOG4CXX_STR("DBAppender not initialized properly: logging not available")); return; } for(auto& converter : _priv->converters){ LogString str_data; converter->format(event, str_data, p); LOG4CXX_ENCODE_CHAR(new_str_data, str_data); ls_args.push_back(new_str_data); } for(std::string& str : ls_args){ args.push_back(str.data()); } args.push_back(nullptr); stat = apr_dbd_pquery(_priv->m_driver, _priv->m_pool.getAPRPool(), _priv->m_databaseHandle, &num_rows, _priv->preparedStmt, int(args.size()), args.data()); if(stat != APR_SUCCESS){ LogString error = LOG4CXX_STR("Unable to insert: "); LOG4CXX_DECODE_CHAR(local_error, apr_dbd_error(_priv->m_driver, _priv->m_databaseHandle, stat)); error.append(local_error); LogLog::error(error); _priv->errorHandler->error(error); } } apache-log4cxx-1.3.1/src/main/cpp/logstream.cpp0000644000175100001770000003036214721727031020676 0ustar runnerdocker/* * 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. */ #include /* Prevent std::basic_streambuf etc destructor ... already defined in logstream.obj */ #if defined(_MSC_VER) && LOG4CXX_UNICHAR_API #define __FORCE_INSTANCE #endif #include #include #include #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include using namespace LOG4CXX_NS; logstream_base::logstream_ios_base::logstream_ios_base(std::ios_base::fmtflags initval, int initsize) { #if LOG4CXX_MEMSET_IOS_BASE // // the destructor for std::ios_base in the MSVC STL // releases a pointer that was not initialized in the constructor. // memset(this, 0, sizeof(*this)); #endif #if LOG4CXX_INIT_IOS_BASE init(NULL); #endif flags(initval); precision(initsize); width(initsize); } logstream_base::logstream_base(const LoggerPtr& log, const LevelPtr& lvl) : initset((std::ios_base::fmtflags) - 1, 1), initclear((std::ios_base::fmtflags) 0, 0), fillchar(0), fillset(false), logger(log), level(lvl), location() { enabled = logger->isEnabledFor(level); } logstream_base::~logstream_base() { } void logstream_base::insert(std::ios_base & (*manip)(std::ios_base&)) { get_stream_state(initclear, initset, fillchar, fillset); (*manip)(initset); (*manip)(initclear); refresh_stream_state(); } bool logstream_base::set_stream_state(std::ios_base& dest, int& dstchar) { std::ios_base::fmtflags setval = initset.flags(); std::ios_base::fmtflags clrval = initclear.flags(); std::ios_base::fmtflags mask = setval ^ (~clrval); dest.setf(clrval, mask); if (initset.precision() == initclear.precision()) { dest.precision(initset.precision()); } if (initset.width() == initclear.width()) { dest.width(initset.width()); } dstchar = fillchar; return fillset; } logstream_base& logstream_base::endmsg(logstream_base& stream) { stream.end_message(); return stream; } logstream_base& logstream_base::nop(logstream_base& stream) { return stream; } void logstream_base::end_message() { if (isEnabled()) { log(logger, level, location); } erase(); } int LOG4CXX_NS::logstream_base::precision(int p) { get_stream_state(initclear, initset, fillchar, fillset); initset.precision(p); int oldVal = (int)initclear.precision(p); refresh_stream_state(); return oldVal; } int LOG4CXX_NS::logstream_base::precision() { get_stream_state(initclear, initset, fillchar, fillset); return (int)initclear.precision(); } int LOG4CXX_NS::logstream_base::width(int w) { get_stream_state(initclear, initset, fillchar, fillset); initset.width(w); int oldVal = (int)initclear.width(w); refresh_stream_state(); return oldVal; } int LOG4CXX_NS::logstream_base::width() { get_stream_state(initclear, initset, fillchar, fillset); return (int)initclear.width(); } int LOG4CXX_NS::logstream_base::fill(int newfill) { get_stream_state(initclear, initset, fillchar, fillset); int oldfill = fillchar; fillchar = newfill; fillset = true; refresh_stream_state(); return oldfill; } int logstream_base::fill() { get_stream_state(initclear, initset, fillchar, fillset); return fillchar; } std::ios_base::fmtflags logstream_base::flags(std::ios_base::fmtflags newflags) { get_stream_state(initclear, initset, fillchar, fillset); initset.flags(newflags); std::ios_base::fmtflags oldVal = initclear.flags(newflags); refresh_stream_state(); return oldVal; } std::ios_base::fmtflags logstream_base::setf(std::ios_base::fmtflags newflags, std::ios_base::fmtflags mask) { get_stream_state(initclear, initset, fillchar, fillset); initset.setf(newflags, mask); std::ios_base::fmtflags oldVal = initclear.setf(newflags, mask); refresh_stream_state(); return oldVal; } std::ios_base::fmtflags logstream_base::setf(std::ios_base::fmtflags newflags) { get_stream_state(initclear, initset, fillchar, fillset); initset.setf(newflags); std::ios_base::fmtflags oldVal = initclear.setf(newflags); refresh_stream_state(); return oldVal; } void logstream_base::setLevel(const ::LOG4CXX_NS::LevelPtr& newlevel) { level = newlevel; bool oldLevel = enabled; enabled = logger->isEnabledFor(level); if (oldLevel != enabled) { erase(); } } bool logstream_base::isEnabledFor(const ::LOG4CXX_NS::LevelPtr& l) const { return logger->isEnabledFor(l); } void logstream_base::setLocation(const LOG4CXX_NS::spi::LocationInfo& newlocation) { if (LOG4CXX_UNLIKELY(enabled)) { location = newlocation; } } logstream::logstream(const LOG4CXX_NS::LoggerPtr& logger, const LOG4CXX_NS::LevelPtr& level) : logstream_base(logger, level), stream(0) { } logstream::logstream(const Ch* loggerName, const LOG4CXX_NS::LevelPtr& level) : logstream_base(LOG4CXX_NS::Logger::getLogger(loggerName), level), stream(0) { } logstream::logstream(const std::basic_string& loggerName, const LOG4CXX_NS::LevelPtr& level) : logstream_base(LOG4CXX_NS::Logger::getLogger(loggerName), level), stream(0) { } logstream::~logstream() { delete stream; } logstream& logstream::operator<<(logstream_base & (*manip)(logstream_base&)) { (*manip)(*this); return *this; } logstream& logstream::operator<<(const LevelPtr& l) { setLevel(l); return *this; } logstream& logstream::operator<<(const LOG4CXX_NS::spi::LocationInfo& newlocation) { setLocation(newlocation); return *this; } logstream& logstream::operator>>(const LOG4CXX_NS::spi::LocationInfo& newlocation) { setLocation(newlocation); return *this; } logstream& logstream::operator<<(std::ios_base & (*manip)(std::ios_base&)) { logstream_base::insert(manip); return *this; } logstream::operator std::basic_ostream& () { if (stream == 0) { stream = new std::basic_stringstream(); refresh_stream_state(); } return *stream; } void logstream::log(LoggerPtr& log, const LevelPtr& lev, const LOG4CXX_NS::spi::LocationInfo& loc) { if (stream != 0) { std::basic_string msg = stream->str(); if (!msg.empty()) { log->log(lev, msg, loc); } } } void logstream::erase() { if (stream != 0) { std::basic_string emptyStr; stream->str(emptyStr); } } void logstream::get_stream_state(std::ios_base& base, std::ios_base& mask, int& fill, bool& fillSet) const { if (stream != 0) { std::ios_base::fmtflags flags = stream->flags(); base.flags(flags); mask.flags(flags); int width = (int)stream->width(); base.width(width); mask.width(width); int precision = (int)stream->precision(); base.precision(precision); mask.precision(precision); fill = stream->fill(); fillSet = true; } } void logstream::refresh_stream_state() { if (stream != 0) { int ch; if (logstream_base::set_stream_state(*stream, ch)) { stream->fill(ch); } } } #if LOG4CXX_WCHAR_T_API wlogstream::wlogstream(const LOG4CXX_NS::LoggerPtr& logger, const LOG4CXX_NS::LevelPtr& level) : logstream_base(logger, level), stream(0) { } wlogstream::wlogstream(const Ch* loggerName, const LOG4CXX_NS::LevelPtr& level) : logstream_base(LOG4CXX_NS::Logger::getLogger(loggerName), level), stream(0) { } wlogstream::wlogstream(const std::basic_string& loggerName, const LOG4CXX_NS::LevelPtr& level) : logstream_base(LOG4CXX_NS::Logger::getLogger(loggerName), level), stream(0) { } wlogstream::~wlogstream() { delete stream; } wlogstream& wlogstream::operator<<(logstream_base & (*manip)(logstream_base&)) { (*manip)(*this); return *this; } wlogstream& wlogstream::operator<<(const LevelPtr& l) { setLevel(l); return *this; } wlogstream& wlogstream::operator<<(const LOG4CXX_NS::spi::LocationInfo& newlocation) { setLocation(newlocation); return *this; } wlogstream& wlogstream::operator>>(const LOG4CXX_NS::spi::LocationInfo& newlocation) { setLocation(newlocation); return *this; } wlogstream& wlogstream::operator<<(std::ios_base & (*manip)(std::ios_base&)) { logstream_base::insert(manip); return *this; } wlogstream::operator std::basic_ostream& () { if (stream == 0) { stream = new std::basic_stringstream(); refresh_stream_state(); } return *stream; } void wlogstream::log(LoggerPtr& log, const LevelPtr& lev, const LOG4CXX_NS::spi::LocationInfo& loc) { if (stream != 0) { std::basic_string msg = stream->str(); if (!msg.empty()) { log->log(lev, msg, loc); } } } void wlogstream::erase() { if (stream != 0) { std::basic_string emptyStr; stream->str(emptyStr); } } void wlogstream::get_stream_state(std::ios_base& base, std::ios_base& mask, int& fill, bool& fillSet) const { if (stream != 0) { std::ios_base::fmtflags flags = stream->flags(); base.flags(flags); mask.flags(flags); int width = (int)stream->width(); base.width(width); mask.width(width); int precision = (int)stream->precision(); base.precision(precision); mask.precision(precision); fill = stream->fill(); fillSet = true; } } void wlogstream::refresh_stream_state() { if (stream != 0) { int ch; if (logstream_base::set_stream_state(*stream, ch)) { stream->fill(ch); } } } #endif #if LOG4CXX_UNICHAR_API ulogstream::ulogstream(const Ch* loggerName, const LOG4CXX_NS::LevelPtr& level) : logstream_base(LOG4CXX_NS::Logger::getLogger(loggerName), level), stream(0) { } ulogstream::ulogstream(const std::basic_string& loggerName, const LOG4CXX_NS::LevelPtr& level) : logstream_base(LOG4CXX_NS::Logger::getLogger(loggerName), level), stream(0) { } #endif #if LOG4CXX_UNICHAR_API && LOG4CXX_CFSTRING_API ulogstream::ulogstream(const CFStringRef& loggerName, const LOG4CXX_NS::LevelPtr& level) : logstream_base(LOG4CXX_NS::Logger::getLogger(loggerName), level), stream(0) { } #endif #if LOG4CXX_UNICHAR_API ulogstream::ulogstream(const LOG4CXX_NS::LoggerPtr& logger, const LOG4CXX_NS::LevelPtr& level) : logstream_base(logger, level), stream(0) { } ulogstream::~ulogstream() { delete stream; } ulogstream& ulogstream::operator<<(logstream_base & (*manip)(logstream_base&)) { (*manip)(*this); return *this; } ulogstream& ulogstream::operator<<(const LevelPtr& level) { setLevel(level); return *this; } ulogstream& ulogstream::operator<<(const LOG4CXX_NS::spi::LocationInfo& newlocation) { setLocation(newlocation); return *this; } ulogstream& ulogstream::operator>>(const LOG4CXX_NS::spi::LocationInfo& newlocation) { setLocation(newlocation); return *this; } ulogstream& ulogstream::operator<<(std::ios_base & (*manip)(std::ios_base&)) { logstream_base::insert(manip); return *this; } ulogstream::operator std::basic_ostream& () { if (stream == 0) { stream = new std::basic_stringstream(); refresh_stream_state(); } return *stream; } void ulogstream::log(LoggerPtr& logger, const LevelPtr& level, const LOG4CXX_NS::spi::LocationInfo& location) { if (stream != 0) { std::basic_string msg = stream->str(); if (!msg.empty() && logger->isEnabledFor(level)) { LOG4CXX_DECODE_UNICHAR(lsmsg, msg); logger->forcedLogLS(level, lsmsg, location); } } } void ulogstream::erase() { if (stream != 0) { std::basic_string emptyStr; stream->str(emptyStr); } } void ulogstream::get_stream_state(std::ios_base& base, std::ios_base& mask, int& fill, bool& fillSet) const { if (stream != 0) { std::ios_base::fmtflags flags = stream->flags(); base.flags(flags); mask.flags(flags); int width = stream->width(); base.width(width); mask.width(width); int precision = stream->precision(); base.precision(precision); mask.precision(precision); fill = stream->fill(); fillSet = true; } } void ulogstream::refresh_stream_state() { if (stream != 0) { int fillchar; if (logstream_base::set_stream_state(*stream, fillchar)) { stream->fill(fillchar); } } } #endif apache-log4cxx-1.3.1/src/main/cpp/loggingeventpatternconverter.cpp0000644000175100001770000000337514721727031024723 0ustar runnerdocker/* * 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. */ #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::pattern; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(LoggingEventPatternConverter) LoggingEventPatternConverter::LoggingEventPatternConverter( const LogString& name1, const LogString& style1) : PatternConverter(name1, style1) { } LoggingEventPatternConverter::LoggingEventPatternConverter(std::unique_ptr priv) : PatternConverter (std::move(priv)) { } void LoggingEventPatternConverter::format(const ObjectPtr& obj, LogString& output, LOG4CXX_NS::helpers::Pool& p) const { LoggingEventPtr le = LOG4CXX_NS::cast(obj); if (le != NULL) { format(le, output, p); } } bool LoggingEventPatternConverter::handlesThrowable() const { return false; } apache-log4cxx-1.3.1/src/main/cpp/basicconfigurator.cpp0000644000175100001770000000333314721727031022403 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include using namespace LOG4CXX_NS; void BasicConfigurator::configure(const LayoutPtr& layoutArg) { LogManager::getLoggerRepository()->setConfigured(true); auto layout = layoutArg; if (!layout) { static const helpers::WideLife TTCC_CONVERSION_PATTERN(LOG4CXX_STR("%r [%t] %p %c %x - %m%n")); layout = std::make_shared(TTCC_CONVERSION_PATTERN); } auto appender = std::make_shared(layout); Logger::getRootLogger()->addAppender(appender); } void BasicConfigurator::configure(const AppenderPtr& appender) { LoggerPtr root = Logger::getRootLogger(); root->addAppender(appender); } void BasicConfigurator::resetConfiguration() { LogManager::resetConfiguration(); } apache-log4cxx-1.3.1/src/main/cpp/htmllayout.cpp0000644000175100001770000002023414721727031021100 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; using namespace LOG4CXX_NS::spi; struct HTMLLayout::HTMLLayoutPrivate { HTMLLayoutPrivate() : locationInfo(false) , title(LOG4CXX_STR("Log4cxx Log Messages")) , dateFormat() , expectedPatternLength(100) {} // Print no location info by default bool locationInfo; //= false LogString title; helpers::ISO8601DateFormat dateFormat; // Expected length of a formatted event excluding the message text size_t expectedPatternLength; }; IMPLEMENT_LOG4CXX_OBJECT(HTMLLayout) HTMLLayout::HTMLLayout() : m_priv(std::make_unique()) { m_priv->dateFormat.setTimeZone(TimeZone::getGMT()); m_priv->expectedPatternLength = getFormattedEventCharacterCount() * 2; } HTMLLayout::~HTMLLayout() {} void HTMLLayout::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("TITLE"), LOG4CXX_STR("title"))) { setTitle(value); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("LOCATIONINFO"), LOG4CXX_STR("locationinfo"))) { setLocationInfo(OptionConverter::toBoolean(value, false)); m_priv->expectedPatternLength = getFormattedEventCharacterCount() * 2; } } void HTMLLayout::format(LogString& output, const spi::LoggingEventPtr& event, Pool& p) const { output.reserve(m_priv->expectedPatternLength + event->getMessage().size()); output.append(LOG4CXX_EOL); output.append(LOG4CXX_STR("")); output.append(LOG4CXX_EOL); output.append(LOG4CXX_STR("")); m_priv->dateFormat.format(output, event->getTimeStamp(), p); output.append(LOG4CXX_STR("")); output.append(LOG4CXX_EOL); output.append(LOG4CXX_STR("getThreadName()); output.append(threadName); output.append(LOG4CXX_STR(" thread\">")); output.append(threadName); output.append(LOG4CXX_STR("")); output.append(LOG4CXX_EOL); output.append(LOG4CXX_STR("")); if (event->getLevel()->equals(Level::getDebug())) { output.append(LOG4CXX_STR("")); output.append(event->getLevel()->toString()); output.append(LOG4CXX_STR("")); } else if (event->getLevel()->isGreaterOrEqual(Level::getWarn())) { output.append(LOG4CXX_STR("")); output.append(event->getLevel()->toString()); output.append(LOG4CXX_STR("")); } else { output.append(event->getLevel()->toString()); } output.append(LOG4CXX_STR("")); output.append(LOG4CXX_EOL); output.append(LOG4CXX_STR("getLoggerName()); output.append(LOG4CXX_STR(" logger\">")); Transform::appendEscapingTags(output, event->getLoggerName()); output.append(LOG4CXX_STR("")); output.append(LOG4CXX_EOL); if (m_priv->locationInfo) { output.append(LOG4CXX_STR("")); const LocationInfo& locInfo = event->getLocationInformation(); LOG4CXX_DECODE_CHAR(fileName, locInfo.getFileName()); Transform::appendEscapingTags(output, fileName); output.append(1, (logchar) 0x3A /* ':' */); int line = event->getLocationInformation().getLineNumber(); if (line != 0) { StringHelper::toString(line, p, output); } output.append(LOG4CXX_STR("")); output.append(LOG4CXX_EOL); } output.append(LOG4CXX_STR("")); Transform::appendEscapingTags(output, event->getRenderedMessage()); output.append(LOG4CXX_STR("")); output.append(LOG4CXX_EOL); output.append(LOG4CXX_STR("")); output.append(LOG4CXX_EOL); LogString ndcVal; if (event->getNDC(ndcVal)) { output.append(LOG4CXX_STR("")); output.append(LOG4CXX_STR("NDC: ")); Transform::appendEscapingTags(output, ndcVal); output.append(LOG4CXX_STR("")); output.append(LOG4CXX_EOL); } } void HTMLLayout::appendHeader(LogString& output, Pool& p) { output.append(LOG4CXX_STR("")); output.append(LOG4CXX_EOL); output.append(LOG4CXX_STR("")); output.append(LOG4CXX_EOL); output.append(LOG4CXX_STR("")); output.append(LOG4CXX_EOL); output.append(LOG4CXX_STR("")); output.append(m_priv->title); output.append(LOG4CXX_STR("")); output.append(LOG4CXX_EOL); output.append(LOG4CXX_STR("")); output.append(LOG4CXX_EOL); output.append(LOG4CXX_STR("")); output.append(LOG4CXX_EOL); output.append(LOG4CXX_STR("")); output.append(LOG4CXX_EOL); output.append(LOG4CXX_STR("


")); output.append(LOG4CXX_EOL); output.append(LOG4CXX_STR("Log session start time ")); m_priv->dateFormat.format(output, Date::currentTime(), p); output.append(LOG4CXX_STR("
")); output.append(LOG4CXX_EOL); output.append(LOG4CXX_STR("
")); output.append(LOG4CXX_EOL); output.append(LOG4CXX_STR("")); output.append(LOG4CXX_EOL); output.append(LOG4CXX_STR("")); output.append(LOG4CXX_EOL); output.append(LOG4CXX_STR("")); output.append(LOG4CXX_EOL); output.append(LOG4CXX_STR("")); output.append(LOG4CXX_EOL); output.append(LOG4CXX_STR("")); output.append(LOG4CXX_EOL); output.append(LOG4CXX_STR("")); output.append(LOG4CXX_EOL); if (m_priv->locationInfo) { output.append(LOG4CXX_STR("")); output.append(LOG4CXX_EOL); } output.append(LOG4CXX_STR("")); output.append(LOG4CXX_EOL); output.append(LOG4CXX_STR("")); output.append(LOG4CXX_EOL); } void HTMLLayout::appendFooter(LogString& output, Pool& /* pool */ ) { output.append(LOG4CXX_STR("
TimeThreadLevelLoggerFile:LineMessage
")); output.append(LOG4CXX_EOL); output.append(LOG4CXX_STR("
")); output.append(LOG4CXX_EOL); output.append(LOG4CXX_STR("")); } void HTMLLayout::setLocationInfo(bool locationInfoFlag) { m_priv->locationInfo = locationInfoFlag; } bool HTMLLayout::getLocationInfo() const { return m_priv->locationInfo; } void HTMLLayout::setTitle(const LogString& title1) { m_priv->title.assign(title1); } const LogString& HTMLLayout::getTitle() const { return m_priv->title; } LogString HTMLLayout::getContentType() const { return LOG4CXX_STR("text/html"); } bool HTMLLayout::ignoresThrowable() const { return false; } apache-log4cxx-1.3.1/src/main/cpp/propertyresourcebundle.cpp0000644000175100001770000000333714721727031023531 0ustar runnerdocker/* * 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. */ #include #include #include #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(PropertyResourceBundle) PropertyResourceBundle::PropertyResourceBundle(InputStreamPtr inStream) { properties.load(inStream); } LogString PropertyResourceBundle::getString(const LogString& key) const { LogString resource; PropertyResourceBundle* resourceBundle(const_cast(this)); do { resource = resourceBundle->properties.getProperty(key); if (!resource.empty()) { return resource; } resourceBundle = dynamic_cast(resourceBundle->parent.get()); } while (resourceBundle != 0); throw MissingResourceException(key); #if LOG4CXX_RETURN_AFTER_THROW return resource; #endif } apache-log4cxx-1.3.1/src/main/cpp/action.cpp0000644000175100001770000000370214721727031020154 0ustar runnerdocker/* * 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. */ #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::rolling; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(Action) Action::Action() : m_priv( std::make_unique() ) { } Action::Action( std::unique_ptr priv ) : m_priv( std::move(priv) ) {} Action::~Action() { } /** * {@inheritDoc} */ void Action::run(LOG4CXX_NS::helpers::Pool& pool1) { std::lock_guard lock(m_priv->mutex); if (!m_priv->interrupted) { try { execute(pool1); } catch (std::exception& ex) { reportException(ex); } m_priv->complete = true; m_priv->interrupted = true; } } /** * {@inheritDoc} */ void Action::close() { std::lock_guard lock(m_priv->mutex); m_priv->interrupted = true; } /** * Tests if the action is complete. * @return true if action is complete. */ bool Action::isComplete() const { return m_priv->complete; } /** * Capture exception. * * @param ex exception. */ void Action::reportException(const std::exception& /* ex */) { } apache-log4cxx-1.3.1/src/main/cpp/fmtlayout.cpp0000644000175100001770000001140214721727031020717 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::spi; struct FMTLayout::FMTLayoutPrivate{ FMTLayoutPrivate() : expectedPatternLength(100) {} FMTLayoutPrivate(const LogString& pattern) : conversionPattern(pattern) , expectedPatternLength(100) {} LogString conversionPattern; // Expected length of a formatted event excluding the message text size_t expectedPatternLength; }; IMPLEMENT_LOG4CXX_OBJECT(FMTLayout) FMTLayout::FMTLayout() : m_priv(std::make_unique()) {} FMTLayout::FMTLayout(const LogString& pattern) : m_priv(std::make_unique(pattern)) {} FMTLayout::~FMTLayout(){} void FMTLayout::setConversionPattern(const LogString& pattern) { m_priv->conversionPattern = pattern; helpers::Pool pool; activateOptions(pool); } LogString FMTLayout::getConversionPattern() const { return m_priv->conversionPattern; } void FMTLayout::setOption(const LogString& option, const LogString& value) { if (helpers::StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("CONVERSIONPATTERN"), LOG4CXX_STR("conversionpattern"))) { m_priv->conversionPattern = helpers::OptionConverter::convertSpecialChars(value); } } void FMTLayout::activateOptions(helpers::Pool&) { m_priv->expectedPatternLength = getFormattedEventCharacterCount() * 2; } void FMTLayout::format(LogString& output, const spi::LoggingEventPtr& event, LOG4CXX_NS::helpers::Pool&) const { output.reserve(m_priv->expectedPatternLength + event->getMessage().size()); auto locationFull = fmt::format("{}({})", event->getLocationInformation().getFileName(), event->getLocationInformation().getLineNumber()); LogString ndc; event->getNDC(ndc); #if LOG4CXX_LOGCHAR_IS_WCHAR || LOG4CXX_LOGCHAR_IS_UNICHAR LOG4CXX_ENCODE_CHAR(sNDC, ndc); LOG4CXX_ENCODE_CHAR(sPattern, m_priv->conversionPattern); LOG4CXX_ENCODE_CHAR(sLogger, event->getLoggerName()); LOG4CXX_ENCODE_CHAR(sLevel, event->getLevel()->toString()); LOG4CXX_ENCODE_CHAR(sMsg, event->getMessage()); LOG4CXX_ENCODE_CHAR(sThread, event->getThreadName()); LOG4CXX_ENCODE_CHAR(endOfLine, LOG4CXX_EOL); #else auto& sNDC = ndc; auto& sPattern = m_priv->conversionPattern; auto& sLogger = event->getLoggerName(); auto sLevel = event->getLevel()->toString(); auto& sMsg = event->getMessage(); auto& sThread = event->getThreadName(); auto endOfLine = LOG4CXX_EOL; #endif fmt::format_to(std::back_inserter(output), fmt::runtime(sPattern), fmt::arg("d", event->getChronoTimeStamp()), fmt::arg("c", sLogger), fmt::arg("logger", sLogger), fmt::arg("f", event->getLocationInformation().getShortFileName()), fmt::arg("shortfilename", event->getLocationInformation().getShortFileName()), fmt::arg("F", event->getLocationInformation().getFileName()), fmt::arg("filename", event->getLocationInformation().getFileName()), fmt::arg("l", locationFull), fmt::arg("location", locationFull), fmt::arg("L", event->getLocationInformation().getLineNumber()), fmt::arg("line", event->getLocationInformation().getLineNumber()), fmt::arg("m", sMsg), fmt::arg("message", sMsg), fmt::arg("M", event->getLocationInformation().getMethodName()), fmt::arg("method", event->getLocationInformation().getMethodName()), fmt::arg("n", endOfLine), fmt::arg("newline", endOfLine), fmt::arg("p", sLevel), fmt::arg("level", sLevel), fmt::arg("r", event->getTimeStamp()), fmt::arg("t", sThread), fmt::arg("thread", sThread), fmt::arg("T", sThread), fmt::arg("threadname", sThread), fmt::arg("x", sNDC), fmt::arg("ndc", sNDC) ); } apache-log4cxx-1.3.1/src/main/cpp/inetaddress.cpp0000644000175100001770000001005314721727031021201 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include "apr_network_io.h" using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(InetAddress) struct InetAddress::InetAddressPrivate{ LogString ipAddrString; LogString hostNameString; }; UnknownHostException::UnknownHostException(const LogString& msg1) : Exception(msg1) { } UnknownHostException::UnknownHostException(const UnknownHostException& src) : Exception(src) { } UnknownHostException& UnknownHostException::operator=(const UnknownHostException& src) { Exception::operator=(src); return *this; } InetAddress::InetAddress(const LogString& hostName, const LogString& hostAddr) : m_priv(std::make_unique()) { m_priv->ipAddrString = hostAddr; m_priv->hostNameString = hostName; } InetAddress::~InetAddress(){} /** Determines all the IP addresses of a host, given the host's name. */ std::vector InetAddress::getAllByName(const LogString& host) { LOG4CXX_ENCODE_CHAR(encodedHost, host); // retrieve information about the given host Pool addrPool; apr_sockaddr_t* address = 0; apr_status_t status = apr_sockaddr_info_get(&address, encodedHost.c_str(), APR_INET, 0, 0, addrPool.getAPRPool()); if (status != APR_SUCCESS) { LogString msg(LOG4CXX_STR("Cannot get information about host: ")); msg.append(host); LogLog::error(msg); throw UnknownHostException(msg); } std::vector result; apr_sockaddr_t* currentAddr = address; while (currentAddr != NULL) { // retrieve the IP address of this InetAddress. LogString ipAddrString; char* ipAddr; status = apr_sockaddr_ip_get(&ipAddr, currentAddr); if (status == APR_SUCCESS) { std::string ip(ipAddr); Transcoder::decode(ip, ipAddrString); } // retrieve the host name of this InetAddress. LogString hostNameString; char* hostName; status = apr_getnameinfo(&hostName, currentAddr, 0); if (status == APR_SUCCESS) { std::string host(hostName); Transcoder::decode(host, hostNameString); } result.push_back(std::make_shared(hostNameString, ipAddrString)); currentAddr = currentAddr->next; } return result; } /** Determines the IP address of a host, given the host's name. */ InetAddressPtr InetAddress::getByName(const LogString& host) { InetAddressPtr result; auto address = getAllByName(host); if (!address.empty()) result = address.front(); return result; } /** Returns the IP address string "%d.%d.%d.%d". */ LogString InetAddress::getHostAddress() const { return m_priv->ipAddrString; } /** Gets the host name for this IP address. */ LogString InetAddress::getHostName() const { return m_priv->hostNameString; } /** Returns the local host. */ InetAddressPtr InetAddress::getLocalHost() { return getByName(LOG4CXX_STR("127.0.0.1")); } InetAddressPtr InetAddress::anyAddress() { // APR_ANYADDR does not work with the LOG4CXX_STR macro return getByName(LOG4CXX_STR("0.0.0.0")); } /** Converts this IP address to a String. */ LogString InetAddress::toString() const { LogString rv(getHostName()); if (!rv.empty()) rv.append(LOG4CXX_STR("/")); rv.append(getHostAddress()); return rv; } apache-log4cxx-1.3.1/src/main/cpp/manualtriggeringpolicy.cpp0000644000175100001770000000276614721727031023467 0ustar runnerdocker/* * 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. */ #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::rolling; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(ManualTriggeringPolicy) ManualTriggeringPolicy::ManualTriggeringPolicy() { } bool ManualTriggeringPolicy::isTriggeringEvent(Appender* /* appender */, const LOG4CXX_NS::spi::LoggingEventPtr& /* event */, const LogString& /* file */, size_t /* fileLength */ ) { return false; } void ManualTriggeringPolicy::activateOptions(Pool& /* p */ ) { } void ManualTriggeringPolicy::setOption(const LogString& /* option */, const LogString& /* value */ ) { } apache-log4cxx-1.3.1/src/main/cpp/odbcappender.cpp0000644000175100001770000004623414721727031021334 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #include #include // std::pow #include #include #include #include #include #include #include #include #include #include #include #include #include #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include #if LOG4CXX_HAVE_ODBC #if defined(WIN32) || defined(_WIN32) #include #endif #include #else typedef void* SQLHSTMT; #endif #include #if defined(min) #undef min #endif #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; using namespace LOG4CXX_NS::db; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::pattern; SQLException::SQLException(short fHandleType, void* hInput, const char* prolog, LOG4CXX_NS::helpers::Pool& p) : Exception(formatMessage(fHandleType, hInput, prolog, p)) { } SQLException::SQLException(const char* msg) : Exception(msg) { } SQLException::SQLException(const SQLException& src) : Exception(src) { } const char* SQLException::formatMessage(short fHandleType, void* hInput, const char* prolog, LOG4CXX_NS::helpers::Pool& p) { std::string strReturn(prolog); strReturn.append(" - "); #if LOG4CXX_HAVE_ODBC SQLCHAR SqlState[6]; SQLCHAR Msg[SQL_MAX_MESSAGE_LENGTH]; SQLINTEGER NativeError; SQLSMALLINT i; SQLSMALLINT MsgLen; SQLRETURN rc2; // Get the status records. i = 1; while ((rc2 = SQLGetDiagRecA(fHandleType, hInput, i, SqlState, &NativeError, Msg, sizeof(Msg), &MsgLen)) != SQL_NO_DATA) { strReturn.append((char*) Msg); i++; } #else strReturn.append("log4cxx built without ODBC support"); #endif return apr_pstrdup((apr_pool_t*) p.getAPRPool(), strReturn.c_str()); } IMPLEMENT_LOG4CXX_OBJECT(ODBCAppender) #define _priv static_cast(m_priv.get()) ODBCAppender::ODBCAppender() : AppenderSkeleton (std::make_unique( #if LOG4CXX_EVENTS_AT_EXIT [this] { std::lock_guard lock(_priv->mutex); if(_priv->closed) return; try { flushBuffer(_priv->pool); } catch (SQLException& e) { _priv->errorHandler->error(LOG4CXX_STR("Error flushing connection"), e, ErrorCode::GENERIC_FAILURE); } } #endif )) { } ODBCAppender::~ODBCAppender() { finalize(); } #define RULES_PUT(spec, cls) \ specs.insert(PatternMap::value_type(LogString(LOG4CXX_STR(spec)), cls ::newInstance)) static PatternMap getFormatSpecifiers() { PatternMap specs; if (specs.empty()) { RULES_PUT("logger", LoggerPatternConverter); RULES_PUT("class", ClassNamePatternConverter); RULES_PUT("time", DatePatternConverter); RULES_PUT("shortfilename", ShortFileLocationPatternConverter); RULES_PUT("fullfilename", FileLocationPatternConverter); RULES_PUT("location", FullLocationPatternConverter); RULES_PUT("line", LineLocationPatternConverter); RULES_PUT("message", MessagePatternConverter); RULES_PUT("method", MethodLocationPatternConverter); RULES_PUT("level", LevelPatternConverter); RULES_PUT("thread", ThreadPatternConverter); RULES_PUT("threadname", ThreadUsernamePatternConverter); RULES_PUT("mdc", MDCPatternConverter); RULES_PUT("ndc", NDCPatternConverter); } return specs; } void ODBCAppender::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("BUFFERSIZE"), LOG4CXX_STR("buffersize"))) { setBufferSize((size_t)OptionConverter::toInt(value, 1)); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("PASSWORD"), LOG4CXX_STR("password"))) { setPassword(value); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("SQL"), LOG4CXX_STR("sql"))) { setSql(value); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("URL"), LOG4CXX_STR("url")) || StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("DSN"), LOG4CXX_STR("dsn")) || StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("CONNECTIONSTRING"), LOG4CXX_STR("connectionstring")) ) { setURL(value); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("USER"), LOG4CXX_STR("user"))) { setUser(value); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("COLUMNMAPPING"), LOG4CXX_STR("columnmapping"))) { _priv->mappedName.push_back(value); } else { AppenderSkeleton::setOption(option, value); } } // Does ODBCAppender require a layout? bool ODBCAppender::requiresLayout() const { return false; } void ODBCAppender::activateOptions(LOG4CXX_NS::helpers::Pool&) { #if !LOG4CXX_HAVE_ODBC LogLog::error(LOG4CXX_STR("Can not activate ODBCAppender unless compiled with ODBC support.")); #else if (_priv->mappedName.empty()) { LogLog::error(LOG4CXX_STR("ODBCAppender column mappings not defined, logging events will not be inserted")); } auto specs = getFormatSpecifiers(); for (auto& name : _priv->mappedName) { auto lowerName = StringHelper::toLowerCase(name); auto pItem = specs.find(lowerName); if (specs.end() == pItem) { if (lowerName.size() < 5 || lowerName.substr(0, 4) != LOG4CXX_STR("mdc{")) LogLog::error(name + LOG4CXX_STR(" is not a supported ColumnMapping value")); else // A single MDC entry { auto index = lowerName.find(0x7D /* '}' */, 4); auto len = (lowerName.npos == index ? lowerName.size() : index) - 4; ODBCAppenderPriv::DataBinding paramData{ 0, 0, 0, 0, 0 }; paramData.converter = std::make_shared(lowerName.substr(4, len)); _priv->parameterValue.push_back(paramData); } } else { ODBCAppenderPriv::DataBinding paramData{ 0, 0, 0, 0, 0 }; std::vector options; if (LOG4CXX_STR("time") == pItem->first) options.push_back(LOG4CXX_STR("yyyy-MM-dd HH:mm:ss.SSSSSS")); paramData.converter = LOG4CXX_NS::cast((pItem->second)(options)); _priv->parameterValue.push_back(paramData); } } #endif } void ODBCAppender::append(const spi::LoggingEventPtr& event, LOG4CXX_NS::helpers::Pool& p) { #if LOG4CXX_HAVE_ODBC _priv->buffer.push_back(event); if (_priv->buffer.size() >= _priv->bufferSize) { flushBuffer(p); } #endif } LogString ODBCAppender::getLogStatement(const spi::LoggingEventPtr& event, LOG4CXX_NS::helpers::Pool& p) const { return LogString(); } void ODBCAppender::execute(const LogString& sql, LOG4CXX_NS::helpers::Pool& p) { } /* The default behavior holds a single connection open until the appender is closed (typically when garbage collected).*/ void ODBCAppender::closeConnection(ODBCAppender::SQLHDBC /* con */) { } ODBCAppender::SQLHDBC ODBCAppender::getConnection(LOG4CXX_NS::helpers::Pool& p) { #if LOG4CXX_HAVE_ODBC SQLRETURN ret; if (_priv->env == SQL_NULL_HENV) { ret = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &_priv->env); if (ret < 0) { SQLException ex(SQL_HANDLE_ENV, _priv->env, "Failed to allocate SQL handle", p); _priv->env = SQL_NULL_HENV; throw ex; } ret = SQLSetEnvAttr(_priv->env, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3, SQL_IS_INTEGER); if (ret < 0) { SQLException ex(SQL_HANDLE_ENV, _priv->env, "Failed to set odbc version", p); SQLFreeHandle(SQL_HANDLE_ENV, _priv->env); _priv->env = SQL_NULL_HENV; throw ex; } } if (_priv->connection == SQL_NULL_HDBC) { ret = SQLAllocHandle(SQL_HANDLE_DBC, _priv->env, &_priv->connection); if (ret < 0) { SQLException ex(SQL_HANDLE_DBC, _priv->connection, "Failed to allocate sql handle", p); _priv->connection = SQL_NULL_HDBC; throw ex; } #if LOG4CXX_LOGCHAR_IS_WCHAR SQLWCHAR *wUser = nullptr, *wPwd = nullptr; if (!_priv->databaseUser.empty()) wUser = (SQLWCHAR*)_priv->databaseUser.c_str(); if (!_priv->databasePassword.empty()) wPwd = (SQLWCHAR*)_priv->databasePassword.c_str(); ret = SQLConnectW(_priv->connection , (SQLWCHAR*)_priv->databaseURL.c_str(), SQL_NTS , wUser, SQL_NTS , wPwd, SQL_NTS ); #elif LOG4CXX_LOGCHAR_IS_UTF8 SQLCHAR *wUser = nullptr, *wPwd = nullptr; if (!_priv->databaseUser.empty()) wUser = (SQLCHAR*)_priv->databaseUser.c_str(); if (!_priv->databasePassword.empty()) wPwd = (SQLCHAR*)_priv->databasePassword.c_str(); ret = SQLConnectA(_priv->connection , (SQLCHAR*)_priv->databaseURL.c_str(), SQL_NTS , wUser, SQL_NTS , wPwd, SQL_NTS ); #else SQLWCHAR* wURL, *wUser = nullptr, *wPwd = nullptr; encode(&wURL, _priv->databaseURL, p); if (!_priv->databaseUser.empty()) encode(&wUser, _priv->databaseUser, p); if (!_priv->databasePassword.empty()) encode(&wPwd, _priv->databasePassword, p); ret = SQLConnectW( _priv->connection , wURL, SQL_NTS , wUser, SQL_NTS , wPwd, SQL_NTS ); #endif if (ret < 0) { SQLException ex(SQL_HANDLE_DBC, _priv->connection, "Failed to connect to database", p); SQLFreeHandle(SQL_HANDLE_DBC, _priv->connection); _priv->connection = SQL_NULL_HDBC; throw ex; } } return _priv->connection; #else return 0; #endif } void ODBCAppender::close() { if (_priv->closed) { return; } Pool p; try { flushBuffer(p); } catch (SQLException& e) { _priv->errorHandler->error(LOG4CXX_STR("Error closing connection"), e, ErrorCode::GENERIC_FAILURE); } #if LOG4CXX_HAVE_ODBC if (_priv->connection != SQL_NULL_HDBC) { SQLDisconnect(_priv->connection); SQLFreeHandle(SQL_HANDLE_DBC, _priv->connection); } if (_priv->env != SQL_NULL_HENV) { SQLFreeHandle(SQL_HANDLE_ENV, _priv->env); } #endif _priv->closed = true; } #if LOG4CXX_HAVE_ODBC void ODBCAppender::ODBCAppenderPriv::setPreparedStatement(SQLHDBC con, Pool& p) { auto ret = SQLAllocHandle( SQL_HANDLE_STMT, con, &this->preparedStatement); if (ret < 0) { throw SQLException( SQL_HANDLE_DBC, con, "Failed to allocate statement handle.", p); } #if LOG4CXX_LOGCHAR_IS_WCHAR ret = SQLPrepareW(this->preparedStatement, (SQLWCHAR*)this->sqlStatement.c_str(), SQL_NTS); #elif LOG4CXX_LOGCHAR_IS_UTF8 ret = SQLPrepareA(this->preparedStatement, (SQLCHAR*)this->sqlStatement.c_str(), SQL_NTS); #else SQLWCHAR* wsql; encode(&wsql, this->sqlStatement, p); ret = SQLPrepareW(this->preparedStatement, wsql, SQL_NTS); #endif if (ret < 0) { throw SQLException(SQL_HANDLE_STMT, this->preparedStatement, "Failed to prepare sql statement.", p); } int parameterNumber = 0; for (auto& item : this->parameterValue) { ++parameterNumber; SQLSMALLINT targetType; SQLULEN targetMaxCharCount; SQLSMALLINT decimalDigits; SQLSMALLINT nullable; auto ret = SQLDescribeParam ( this->preparedStatement , parameterNumber , &targetType , &targetMaxCharCount , &decimalDigits , &nullable ); if (ret < 0) { throw SQLException(SQL_HANDLE_STMT, this->preparedStatement, "Failed to describe parameter", p); } if (SQL_CHAR == targetType || SQL_VARCHAR == targetType || SQL_LONGVARCHAR == targetType) { item.paramType = SQL_C_CHAR; item.paramMaxCharCount = targetMaxCharCount; item.paramValueSize = (SQLINTEGER)(item.paramMaxCharCount) * sizeof(char) + sizeof(char); item.paramValue = (SQLPOINTER)p.palloc(item.paramValueSize + sizeof(char)); } else if (SQL_WCHAR == targetType || SQL_WVARCHAR == targetType || SQL_WLONGVARCHAR == targetType) { item.paramType = SQL_C_WCHAR; item.paramMaxCharCount = targetMaxCharCount; item.paramValueSize = (SQLINTEGER)(targetMaxCharCount) * sizeof(wchar_t) + sizeof(wchar_t); item.paramValue = (SQLPOINTER)p.palloc(item.paramValueSize + sizeof(wchar_t)); } else if (SQL_TYPE_TIMESTAMP == targetType || SQL_TYPE_DATE == targetType || SQL_TYPE_TIME == targetType || SQL_DATETIME == targetType) { item.paramType = SQL_C_TYPE_TIMESTAMP; item.paramMaxCharCount = (0 <= decimalDigits) ? decimalDigits : 6; item.paramValueSize = sizeof(SQL_TIMESTAMP_STRUCT); item.paramValue = (SQLPOINTER)p.palloc(item.paramValueSize); } else { if (SQL_INTEGER != targetType) { LogString msg(LOG4CXX_STR("Unexpected targetType (")); helpers::StringHelper::toString(targetType, p, msg); msg += LOG4CXX_STR(") at parameter "); helpers::StringHelper::toString(parameterNumber, p, msg); msg += LOG4CXX_STR(" while preparing SQL"); LogLog::warn(msg); } item.paramMaxCharCount = 30; #if LOG4CXX_LOGCHAR_IS_UTF8 item.paramType = SQL_C_CHAR; item.paramValueSize = (SQLINTEGER)(item.paramMaxCharCount) * sizeof(char); item.paramValue = (SQLPOINTER)p.palloc(item.paramValueSize + sizeof(char)); #else item.paramType = SQL_C_WCHAR; item.paramValueSize = (SQLINTEGER)(item.paramMaxCharCount) * sizeof(wchar_t); item.paramValue = (SQLPOINTER)p.palloc(item.paramValueSize + sizeof(wchar_t)); #endif } item.strLen_or_Ind = SQL_NTS; ret = SQLBindParameter ( this->preparedStatement , parameterNumber , SQL_PARAM_INPUT , item.paramType // ValueType , targetType , targetMaxCharCount , decimalDigits , item.paramValue , item.paramValueSize , &item.strLen_or_Ind ); if (ret < 0) { throw SQLException(SQL_HANDLE_STMT, this->preparedStatement, "Failed to bind parameter", p); } } } void ODBCAppender::ODBCAppenderPriv::setParameterValues(const spi::LoggingEventPtr& event, Pool& p) { for (auto& item : this->parameterValue) { if (!item.paramValue || item.paramValueSize <= 0) ; else if (SQL_C_WCHAR == item.paramType) { LogString sbuf; item.converter->format(event, sbuf, p); #if LOG4CXX_LOGCHAR_IS_WCHAR_T std::wstring& tmp = sbuf; #else std::wstring tmp; Transcoder::encode(sbuf, tmp); #endif auto dst = (wchar_t*)item.paramValue; auto charCount = std::min(size_t(item.paramMaxCharCount), tmp.size()); auto copySize = std::min(size_t(item.paramValueSize - 1), charCount * sizeof(wchar_t)); std::memcpy(dst, tmp.data(), copySize); dst[copySize / sizeof(wchar_t)] = 0; } else if (SQL_C_CHAR == item.paramType) { LogString sbuf; item.converter->format(event, sbuf, p); #if LOG4CXX_LOGCHAR_IS_UTF8 std::string& tmp = sbuf; #else std::string tmp; Transcoder::encode(sbuf, tmp); #endif auto dst = (char*)item.paramValue; auto sz = std::min(size_t(item.paramMaxCharCount), tmp.size()); auto copySize = std::min(size_t(item.paramValueSize - 1), sz * sizeof(char)); std::memcpy(dst, tmp.data(), copySize); dst[copySize] = 0; } else if (SQL_C_TYPE_TIMESTAMP == item.paramType) { apr_time_exp_t exploded; apr_status_t stat = this->timeZone->explode(&exploded, event->getTimeStamp()); if (stat == APR_SUCCESS) { auto dst = (SQL_TIMESTAMP_STRUCT*)item.paramValue; dst->year = 1900 + exploded.tm_year; dst->month = 1 + exploded.tm_mon; dst->day = exploded.tm_mday; dst->hour = exploded.tm_hour; dst->minute = exploded.tm_min; dst->second = exploded.tm_sec; // Prevent '[ODBC SQL Server Driver]Datetime field overflow' by rounding to the target field precision int roundingExponent = 6 - (int)item.paramMaxCharCount; if (0 < roundingExponent) { int roundingDivisor = (int)std::pow(10, roundingExponent); dst->fraction = 1000 * roundingDivisor * ((exploded.tm_usec + roundingDivisor / 2) / roundingDivisor); } else dst->fraction = 1000 * exploded.tm_usec; } } } } #endif void ODBCAppender::flushBuffer(Pool& p) { for (auto& logEvent : _priv->buffer) { if (_priv->parameterValue.empty()) _priv->errorHandler->error(LOG4CXX_STR("ODBCAppender column mappings not defined")); #if LOG4CXX_HAVE_ODBC else try { if (0 == _priv->preparedStatement) _priv->setPreparedStatement(getConnection(p), p); _priv->setParameterValues(logEvent, p); auto ret = SQLExecute(_priv->preparedStatement); if (ret < 0) { throw SQLException(SQL_HANDLE_STMT, _priv->preparedStatement, "Failed to execute prepared statement", p); } } catch (SQLException& e) { _priv->errorHandler->error(LOG4CXX_STR("Failed to execute sql"), e, ErrorCode::FLUSH_FAILURE); } #endif } // clear the buffer of reported events _priv->buffer.clear(); } void ODBCAppender::setSql(const LogString& s) { _priv->sqlStatement = s; } #if LOG4CXX_WCHAR_T_API || LOG4CXX_LOGCHAR_IS_WCHAR_T || defined(WIN32) || defined(_WIN32) void ODBCAppender::encode(wchar_t** dest, const LogString& src, Pool& p) { *dest = Transcoder::wencode(src, p); } #endif void ODBCAppender::encode(unsigned short** dest, const LogString& src, Pool& p) { // worst case double number of characters from UTF-8 or wchar_t *dest = (unsigned short*) p.palloc((src.size() + 1) * 2 * sizeof(unsigned short)); unsigned short* current = *dest; for (LogString::const_iterator i = src.begin(); i != src.end();) { unsigned int sv = Transcoder::decode(src, i); if (sv < 0x10000) { *current++ = (unsigned short) sv; } else { unsigned char u = (unsigned char) (sv >> 16); unsigned char w = (unsigned char) (u - 1); unsigned short hs = (0xD800 + ((w & 0xF) << 6) + ((sv & 0xFFFF) >> 10)); unsigned short ls = (0xDC00 + (sv & 0x3FF)); *current++ = (unsigned short) hs; *current++ = (unsigned short) ls; } } *current = 0; } const LogString& ODBCAppender::getSql() const { return _priv->sqlStatement; } void ODBCAppender::setUser(const LogString& user) { _priv->databaseUser = user; } void ODBCAppender::setURL(const LogString& url) { _priv->databaseURL = url; } void ODBCAppender::setPassword(const LogString& password) { _priv->databasePassword = password; } void ODBCAppender::setBufferSize(size_t newBufferSize) { _priv->bufferSize = newBufferSize; } const LogString& ODBCAppender::getUser() const { return _priv->databaseUser; } const LogString& ODBCAppender::getURL() const { return _priv->databaseURL; } const LogString& ODBCAppender::getPassword() const { return _priv->databasePassword; } size_t ODBCAppender::getBufferSize() const { return _priv->bufferSize; } apache-log4cxx-1.3.1/src/main/cpp/rolloverdescription.cpp0000644000175100001770000000541214721727031023007 0ustar runnerdocker/* * 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. */ #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::rolling; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(RolloverDescription) struct RolloverDescription::RolloverDescriptionPrivate{ RolloverDescriptionPrivate(){} RolloverDescriptionPrivate( const LogString& activeFileName1, const bool append1, const ActionPtr& synchronous1, const ActionPtr& asynchronous1) : activeFileName(activeFileName1), append(append1), synchronous(synchronous1), asynchronous(asynchronous1) {} /** * Active log file name after rollover. */ LogString activeFileName; /** * Should active file be opened for appending. */ bool append; /** * Action to be completed after close of current active log file * before returning control to caller. */ ActionPtr synchronous; /** * Action to be completed after close of current active log file * and before next rollover attempt, may be executed asynchronously. */ ActionPtr asynchronous; }; RolloverDescription::RolloverDescription() : m_priv(std::make_unique()) { } RolloverDescription::RolloverDescription( const LogString& activeFileName1, const bool append1, const ActionPtr& synchronous1, const ActionPtr& asynchronous1) : m_priv(std::make_unique(activeFileName1, append1, synchronous1, asynchronous1)) { } RolloverDescription::~RolloverDescription(){} LogString RolloverDescription::getActiveFileName() const { return m_priv->activeFileName; } bool RolloverDescription::getAppend() const { return m_priv->append; } ActionPtr RolloverDescription::getSynchronous() const { return m_priv->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. */ ActionPtr RolloverDescription::getAsynchronous() const { return m_priv->asynchronous; } apache-log4cxx-1.3.1/src/main/cpp/properties.cpp0000644000175100001770000001754314721727031021103 0ustar runnerdocker/* * 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. */ #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; class PropertyParser { public: void parse(LogString& in, Properties& properties) { LogString key, element; LexemType lexemType = BEGIN; logchar c; bool finished = false; if (!get(in, c)) { return; } while (!finished) { switch (lexemType) { case BEGIN: switch (c) { case 0x20: // ' ' case 0x09: // '\t' case 0x0A: // '\n' case 0x0D: // '\r' if (!get(in, c)) { finished = true; } break; case 0x23: // '#' case 0x21: // '!' lexemType = COMMENT; if (!get(in, c)) { finished = true; } break; default: lexemType = KEY; break; } break; case KEY: switch (c) { case 0x5C: // '\\' lexemType = KEY_ESCAPE; if (!get(in, c)) { finished = true; } break; case 0x09: // '\t' case 0x20: // ' ' case 0x3A: // ':' case 0x3D: // '=' lexemType = DELIMITER; if (!get(in, c)) { finished = true; } break; case 0x0A: case 0x0D: // key associated with an empty string element properties.setProperty(key, LogString()); key.erase(key.begin(), key.end()); lexemType = BEGIN; if (!get(in, c)) { finished = true; } break; default: key.append(1, c); if (!get(in, c)) { finished = true; } break; } break; case KEY_ESCAPE: switch (c) { case 0x74: // 't' key.append(1, 0x09); lexemType = KEY; break; case 0x6E: // 'n' key.append(1, 0x0A); lexemType = KEY; break; case 0x72: // 'r' key.append(1, 0x0D); lexemType = KEY; break; case 0x0A: // '\n' lexemType = KEY_CONTINUE; break; case 0x0D: // '\r' lexemType = KEY_CONTINUE2; break; default: key.append(1, c); lexemType = KEY; } if (!get(in, c)) { finished = true; } break; case KEY_CONTINUE: switch (c) { case 0x20: // ' ' case 0x09: // '\t' if (!get(in, c)) { finished = true; } break; default: lexemType = KEY; break; } break; case KEY_CONTINUE2: switch (c) { case 0x0A: // '\n' if (!get(in, c)) { finished = true; } lexemType = KEY_CONTINUE; break; default: lexemType = KEY_CONTINUE; break; } break; case DELIMITER: switch (c) { case 0x09: // '\t' case 0x20: // ' ' case 0x3A: // ':' case 0x3D: // '=' if (!get(in, c)) { finished = true; } break; default: lexemType = ELEMENT; break; } break; case ELEMENT: switch (c) { case 0x5C: // '\\' lexemType = ELEMENT_ESCAPE; if (!get(in, c)) { finished = true; } break; case 0x0A: // '\n' case 0x0D: // '\r' // key associated with an empty string element properties.setProperty(key, element); key.erase(key.begin(), key.end()); element.erase(element.begin(), element.end()); lexemType = BEGIN; if (!get(in, c)) { finished = true; } break; default: element.append(1, c); if (!get(in, c)) { finished = true; } break; } break; case ELEMENT_ESCAPE: switch (c) { case 0x74: // 't' element.append(1, 0x09); lexemType = ELEMENT; break; case 0x6E: // 'n' element.append(1, 0x0A); lexemType = ELEMENT; break; case 0x72: // 'r' element.append(1, 0x0D); lexemType = ELEMENT; break; case 0x0A: // '\n' lexemType = ELEMENT_CONTINUE; break; case 0x0D: // '\r' lexemType = ELEMENT_CONTINUE2; break; default: element.append(1, c); lexemType = ELEMENT; break; } if (!get(in, c)) { finished = true; } break; case ELEMENT_CONTINUE: switch (c) { case 0x20: // ' ' case 0x09: // '\t' if (!get(in, c)) { finished = true; } break; default: lexemType = ELEMENT; break; } break; case ELEMENT_CONTINUE2: switch (c) { case 0x0A: // '\n' if (!get(in, c)) { finished = true; } lexemType = ELEMENT_CONTINUE; break; default: lexemType = ELEMENT_CONTINUE; break; } break; case COMMENT: if (c == 0x0A || c == 0x0D) { lexemType = BEGIN; } if (!get(in, c)) { finished = true; } break; } } if (!key.empty()) { properties.setProperty(key, element); } } protected: static bool get(LogString& in, logchar& c) { if (in.empty()) { c = 0; return false; } c = in[0]; in.erase(in.begin()); return true; } typedef enum { BEGIN, KEY, KEY_ESCAPE, KEY_CONTINUE, KEY_CONTINUE2, DELIMITER, ELEMENT, ELEMENT_ESCAPE, ELEMENT_CONTINUE, ELEMENT_CONTINUE2, COMMENT } LexemType; }; Properties::Properties() : properties(new PropertyMap()) { } Properties::~Properties() { delete properties; } LogString Properties::setProperty(const LogString& key, const LogString& value) { return put(key, value); } LogString Properties::put(const LogString& key, const LogString& value) { LogString oldValue((*properties)[key]); (*properties)[key] = value; return oldValue; } LogString Properties::getProperty(const LogString& key) const { return get(key); } LogString Properties::get(const LogString& key) const { PropertyMap::const_iterator it = properties->find(key); return (it != properties->end()) ? it->second : LogString(); } void Properties::load(InputStreamPtr inStream) { Pool pool; auto lineReader = std::make_shared(inStream, CharsetDecoder::getISOLatinDecoder()); LogString contents = lineReader->read(pool); properties->clear(); PropertyParser parser; parser.parse(contents, *this); } std::vector Properties::propertyNames() const { std::vector names; names.reserve(properties->size()); for (auto const& item : *properties) { const LogString& key = item.first; names.push_back(key); } return names; } apache-log4cxx-1.3.1/src/main/cpp/filerenameaction.cpp0000644000175100001770000000340314721727031022202 0ustar runnerdocker/* * 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. */ #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::rolling; using namespace LOG4CXX_NS::helpers; #define priv static_cast(m_priv.get()) struct FileRenameAction::FileRenameActionPrivate : public ActionPrivate { FileRenameActionPrivate( const File& toRename, const File& renameTo, bool renameEmptyFile1): source(toRename), destination(renameTo), renameEmptyFile(renameEmptyFile1) {} const File source; const File destination; bool renameEmptyFile; }; IMPLEMENT_LOG4CXX_OBJECT(FileRenameAction) FileRenameAction::FileRenameAction(const File& toRename, const File& renameTo, bool renameEmptyFile1) : Action( std::make_unique(toRename, renameTo, renameEmptyFile1) ) { } bool FileRenameAction::execute(LOG4CXX_NS::helpers::Pool& pool1) const { return priv->source.renameTo(priv->destination, pool1); } apache-log4cxx-1.3.1/src/main/cpp/aprserversocket.cpp0000644000175100001770000000732714721727031022130 0ustar runnerdocker/* * 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. */ #include #include #include #include "apr_network_io.h" #include "apr_pools.h" #include "apr_poll.h" namespace LOG4CXX_NS { namespace helpers { #define _priv static_cast(m_priv.get()) struct APRServerSocket::APRServerSocketPriv : public ServerSocketPrivate { Pool pool; std::mutex mutex; apr_socket_t* socket; }; APRServerSocket::APRServerSocket(int port) : ServerSocket(std::make_unique()){ apr_status_t status = apr_socket_create(&_priv->socket, APR_INET, SOCK_STREAM, APR_PROTO_TCP, _priv->pool.getAPRPool()); if (status != APR_SUCCESS) { throw SocketException(status); } status = apr_socket_opt_set(_priv->socket, APR_SO_NONBLOCK, 1); if (status != APR_SUCCESS) { throw SocketException(status); } // Create server socket address (including port number) apr_sockaddr_t* server_addr; status = apr_sockaddr_info_get(&server_addr, NULL, APR_INET, port, 0, _priv->pool.getAPRPool()); if (status != APR_SUCCESS) { throw ConnectException(status); } // bind the socket to the address status = apr_socket_bind(_priv->socket, server_addr); if (status != APR_SUCCESS) { throw BindException(status); } status = apr_socket_listen(_priv->socket, 50); if (status != APR_SUCCESS) { throw SocketException(status); } } void APRServerSocket::close() { std::lock_guard lock(_priv->mutex); if (_priv->socket != 0) { apr_status_t status = apr_socket_close(_priv->socket); if (status != APR_SUCCESS) { throw SocketException(status); } _priv->socket = 0; } } /** Listens for a connection to be made to this socket and accepts it */ SocketPtr APRServerSocket::accept() { apr_socket_t* s; { std::lock_guard lock(_priv->mutex); s = _priv->socket; } if (s == 0) { throw NullPointerException(LOG4CXX_STR("socket")); } apr_pollfd_t poll; poll.p = _priv->pool.getAPRPool(); poll.desc_type = APR_POLL_SOCKET; poll.reqevents = APR_POLLIN; poll.rtnevents = 0; poll.desc.s = s; poll.client_data = NULL; apr_int32_t signaled; apr_interval_time_t to = _priv->timeout * 1000; apr_status_t status = apr_poll(&poll, 1, &signaled, to); if (APR_STATUS_IS_TIMEUP(status)) { throw SocketTimeoutException(); } else if (status != APR_SUCCESS) { throw SocketException(status); } apr_pool_t* newPool; status = apr_pool_create(&newPool, 0); if (status != APR_SUCCESS) { throw PoolException(status); } apr_socket_t* newSocket; status = apr_socket_accept(&newSocket, s, newPool); if (status != APR_SUCCESS) { apr_pool_destroy(newPool); throw SocketException(status); } status = apr_socket_opt_set(newSocket, APR_SO_NONBLOCK, 0); if (status != APR_SUCCESS) { apr_pool_destroy(newPool); throw SocketException(status); } return std::make_shared(newSocket, newPool); } } //namespace helpers } //namespace log4cxx apache-log4cxx-1.3.1/src/main/cpp/atexitregistry.cpp0000644000175100001770000000354114721727031021767 0ustar runnerdocker/* * 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. */ #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; namespace { struct AtExitRegistryImpl : public AtExitRegistry { ~AtExitRegistryImpl() { std::lock_guard lock(mutex); while(!actions.empty()) { std::function action = std::move(actions.begin()->second); actions.erase(actions.begin()); action(); } } void add(void* key, std::function action) { std::lock_guard lock(mutex); actions.emplace(key, std::move(action)); } void del(void* key) { std::lock_guard lock(mutex); actions.erase(key); } private: std::recursive_mutex mutex; std::map> actions; } s_instance; } AtExitRegistry& AtExitRegistry::instance() { return s_instance; } void AtExitRegistry::add(void* key, std::function action) { return s_instance.add(key, std::move(action)); } void AtExitRegistry::del(void* key) { return s_instance.del(key); } apache-log4cxx-1.3.1/src/main/cpp/charsetdecoder.cpp0000644000175100001770000003202314721727031021654 0ustar runnerdocker/* * 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. */ #define NOMINMAX /* tell windows not to define min/max macros */ #include #include #include #include #include #include #include #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(CharsetDecoder) namespace LOG4CXX_NS { namespace helpers { #if APR_HAS_XLATE /** * Converts from an arbitrary encoding to LogString * using apr_xlate. Requires real iconv implementation, * apr-iconv will crash in use. */ class APRCharsetDecoder : public CharsetDecoder { public: /** * Creates a new instance. * @param frompage name of source encoding. */ APRCharsetDecoder(const LogString& frompage) : pool() { #if LOG4CXX_LOGCHAR_IS_WCHAR const char* topage = "WCHAR_T"; #endif #if LOG4CXX_LOGCHAR_IS_UTF8 const char* topage = "UTF-8"; #endif #if LOG4CXX_LOGCHAR_IS_UNICHAR const char* topage = "UTF-16"; #endif std::string fpage(Transcoder::encodeCharsetName(frompage)); apr_status_t stat = apr_xlate_open(&convset, topage, fpage.c_str(), pool.getAPRPool()); if (stat != APR_SUCCESS) { throw IllegalArgumentException(frompage); } } /** * Destructor. */ virtual ~APRCharsetDecoder() { } virtual log4cxx_status_t decode(ByteBuffer& in, LogString& out) { enum { BUFSIZE = 256 }; logchar buf[BUFSIZE]; const apr_size_t initial_outbytes_left = BUFSIZE * sizeof(logchar); apr_status_t stat = APR_SUCCESS; if (in.remaining() == 0) { size_t outbytes_left = initial_outbytes_left; { std::lock_guard lock(mutex); stat = apr_xlate_conv_buffer((apr_xlate_t*) convset, NULL, NULL, (char*) buf, &outbytes_left); } out.append(buf, (initial_outbytes_left - outbytes_left) / sizeof(logchar)); } else { while (in.remaining() > 0 && stat == APR_SUCCESS) { size_t inbytes_left = in.remaining(); size_t initial_inbytes_left = inbytes_left; size_t pos = in.position(); apr_size_t outbytes_left = initial_outbytes_left; { std::lock_guard lock(mutex); stat = apr_xlate_conv_buffer((apr_xlate_t*) convset, in.data() + pos, &inbytes_left, (char*) buf, &outbytes_left); } out.append(buf, (initial_outbytes_left - outbytes_left) / sizeof(logchar)); in.position(pos + (initial_inbytes_left - inbytes_left)); } } return stat; } private: APRCharsetDecoder(const APRCharsetDecoder&); APRCharsetDecoder& operator=(const APRCharsetDecoder&); LOG4CXX_NS::helpers::Pool pool; std::mutex mutex; apr_xlate_t* convset; }; #endif #if LOG4CXX_LOGCHAR_IS_WCHAR && LOG4CXX_HAS_MBSRTOWCS /** * Converts from the default multi-byte string to * LogString using mbstowcs. * */ class MbstowcsCharsetDecoder : public CharsetDecoder { public: MbstowcsCharsetDecoder() { } virtual ~MbstowcsCharsetDecoder() { } private: inline log4cxx_status_t append(LogString& out, const wchar_t* buf) { out.append(buf); return APR_SUCCESS; } virtual log4cxx_status_t decode(ByteBuffer& in, LogString& out) { log4cxx_status_t stat = APR_SUCCESS; enum { BUFSIZE = 256 }; wchar_t wbuf[BUFSIZE]; char cbuf[BUFSIZE*4]; mbstate_t mbstate; memset(&mbstate, 0, sizeof(mbstate)); while (in.remaining() > 0) { const char* src = in.current(); if (*src == 0) { out.append(1, (logchar) 0); in.position(in.position() + 1); } else { auto available = std::min(sizeof (cbuf) - 1, in.remaining()); strncpy(cbuf, src, available); cbuf[available] = 0; src = cbuf; size_t wCharCount = mbsrtowcs(wbuf, &src, BUFSIZE - 1, &mbstate); auto converted = src - cbuf; in.position(in.position() + converted); if (wCharCount == (size_t) -1) // Illegal byte sequence? { LogString msg(LOG4CXX_STR("Illegal byte sequence at ")); msg.append(std::to_wstring(in.position())); msg.append(LOG4CXX_STR(" of ")); msg.append(std::to_wstring(in.limit())); LogLog::warn(msg); stat = APR_BADCH; break; } else { wbuf[wCharCount] = 0; stat = append(out, wbuf); } } } return stat; } private: MbstowcsCharsetDecoder(const MbstowcsCharsetDecoder&); MbstowcsCharsetDecoder& operator=(const MbstowcsCharsetDecoder&); }; #endif /** * Decoder used when the external and internal charsets * are the same. * */ class TrivialCharsetDecoder : public CharsetDecoder { public: TrivialCharsetDecoder() { } virtual ~TrivialCharsetDecoder() { } virtual log4cxx_status_t decode(ByteBuffer& in, LogString& out) { size_t remaining = in.remaining(); if ( remaining > 0) { const logchar* src = (const logchar*) (in.data() + in.position()); size_t count = remaining / sizeof(logchar); out.append(src, count); in.position(in.position() + remaining); } return APR_SUCCESS; } private: TrivialCharsetDecoder(const TrivialCharsetDecoder&); TrivialCharsetDecoder& operator=(const TrivialCharsetDecoder&); }; #if LOG4CXX_LOGCHAR_IS_UTF8 typedef TrivialCharsetDecoder UTF8CharsetDecoder; #else /** * Converts from UTF-8 to std::wstring * */ class UTF8CharsetDecoder : public CharsetDecoder { public: UTF8CharsetDecoder() { } virtual ~UTF8CharsetDecoder() { } private: virtual log4cxx_status_t decode(ByteBuffer& in, LogString& out) { if (in.remaining() > 0) { std::string tmp(in.current(), in.remaining()); std::string::const_iterator iter = tmp.begin(); while (iter != tmp.end()) { unsigned int sv = Transcoder::decode(tmp, iter); if (sv == 0xFFFF) { size_t offset = iter - tmp.begin(); in.position(in.position() + offset); return APR_BADARG; } else { Transcoder::encode(sv, out); } } in.position(in.limit()); } return APR_SUCCESS; } private: UTF8CharsetDecoder(const UTF8CharsetDecoder&); UTF8CharsetDecoder& operator=(const UTF8CharsetDecoder&); }; #endif /** * Converts from ISO-8859-1 to LogString. * */ class ISOLatinCharsetDecoder : public CharsetDecoder { public: ISOLatinCharsetDecoder() { } virtual ~ISOLatinCharsetDecoder() { } private: virtual log4cxx_status_t decode(ByteBuffer& in, LogString& out) { if (in.remaining() > 0) { const unsigned char* src = (unsigned char*) in.current(); const unsigned char* srcEnd = src + in.remaining(); while (src < srcEnd) { unsigned int sv = *(src++); Transcoder::encode(sv, out); } in.position(in.limit()); } return APR_SUCCESS; } private: ISOLatinCharsetDecoder(const ISOLatinCharsetDecoder&); ISOLatinCharsetDecoder& operator=(const ISOLatinCharsetDecoder&); }; /** * Converts from US-ASCII to LogString. * */ class USASCIICharsetDecoder : public CharsetDecoder { public: USASCIICharsetDecoder() { } virtual ~USASCIICharsetDecoder() { } private: virtual log4cxx_status_t decode(ByteBuffer& in, LogString& out) { log4cxx_status_t stat = APR_SUCCESS; if (in.remaining() > 0) { const unsigned char* src = (unsigned char*) in.current(); const unsigned char* srcEnd = src + in.remaining(); while (src < srcEnd) { unsigned char sv = *src; if (sv < 0x80) { src++; Transcoder::encode(sv, out); } else { stat = APR_BADARG; break; } } in.position(src - (const unsigned char*) in.data()); } return stat; } private: USASCIICharsetDecoder(const USASCIICharsetDecoder&); USASCIICharsetDecoder& operator=(const USASCIICharsetDecoder&); }; /** * Charset decoder that uses current locale settings. */ class LocaleCharsetDecoder : public CharsetDecoder { public: LocaleCharsetDecoder() : state() { } log4cxx_status_t decode(ByteBuffer& in, LogString& out) override { log4cxx_status_t result = APR_SUCCESS; const char* p = in.current(); size_t i = in.position(); size_t remain = in.limit() - i; #if !LOG4CXX_CHARSET_EBCDIC if (std::mbsinit(&this->state)) // ByteBuffer not partially decoded? { // Copy single byte characters for (; 0 < remain && ((unsigned int) *p) < 0x80; --remain, ++i, p++) { out.append(1, *p); } } #endif // Decode characters that may be represented by multiple bytes while (0 < remain) { wchar_t ch = 0; size_t n = std::mbrtowc(&ch, p, remain, &this->state); if (0 == n) // NULL encountered? { ++i; break; } if (static_cast(-1) == n) // decoding error? { result = APR_BADARG; break; } if (static_cast(-2) == n) // incomplete sequence? { break; } Transcoder::encode(static_cast(ch), out); remain -= n; i += n; p += n; } in.position(i); return result; } private: std::mbstate_t state; }; } // namespace helpers } //namespace log4cxx CharsetDecoder::CharsetDecoder() { } CharsetDecoder::~CharsetDecoder() { } CharsetDecoder* CharsetDecoder::createDefaultDecoder() { #if LOG4CXX_CHARSET_UTF8 return new UTF8CharsetDecoder(); #elif LOG4CXX_CHARSET_ISO88591 || defined(_WIN32_WCE) return new ISOLatinCharsetDecoder(); #elif LOG4CXX_CHARSET_USASCII return new USASCIICharsetDecoder(); #elif LOG4CXX_LOGCHAR_IS_WCHAR && LOG4CXX_HAS_MBSRTOWCS return new MbstowcsCharsetDecoder(); #else return new LocaleCharsetDecoder(); #endif } CharsetDecoderPtr CharsetDecoder::getDefaultDecoder() { static WideLife decoder(createDefaultDecoder()); // // if invoked after static variable destruction // (if logging is called in the destructor of a static object) // then create a new decoder. // if (decoder.value() == 0) { return CharsetDecoderPtr( createDefaultDecoder() ); } return decoder; } CharsetDecoderPtr CharsetDecoder::getUTF8Decoder() { static WideLife decoder(new UTF8CharsetDecoder()); // // if invoked after static variable destruction // (if logging is called in the destructor of a static object) // then create a new decoder. // if (decoder.value() == 0) { return std::make_shared(); } return decoder; } CharsetDecoderPtr CharsetDecoder::getISOLatinDecoder() { return std::make_shared(); } CharsetDecoderPtr CharsetDecoder::getDecoder(const LogString& charset) { if (StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("UTF-8"), LOG4CXX_STR("utf-8")) || StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("UTF8"), LOG4CXX_STR("utf8")) || StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("CP65001"), LOG4CXX_STR("cp65001"))) { return std::make_shared(); } else if (StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("C"), LOG4CXX_STR("c")) || charset == LOG4CXX_STR("646") || StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("US-ASCII"), LOG4CXX_STR("us-ascii")) || StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("ISO646-US"), LOG4CXX_STR("iso646-US")) || StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("ANSI_X3.4-1968"), LOG4CXX_STR("ansi_x3.4-1968")) || StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("CP20127"), LOG4CXX_STR("cp20127"))) { return std::make_shared(); } else if (StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("ISO-8859-1"), LOG4CXX_STR("iso-8859-1")) || StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("ISO-LATIN-1"), LOG4CXX_STR("iso-latin-1")) || StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("CP1252"), LOG4CXX_STR("cp1252"))) { return std::make_shared(); } else if (StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("LOCALE"), LOG4CXX_STR("locale"))) { return std::make_shared(); } #if APR_HAS_XLATE return std::make_shared(charset); #else throw IllegalArgumentException(charset); #endif } apache-log4cxx-1.3.1/src/main/cpp/timebasedrollingpolicy.cpp0000644000175100001770000003545114721727031023451 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::rolling; using namespace LOG4CXX_NS::helpers; using namespace LOG4CXX_NS::pattern; IMPLEMENT_LOG4CXX_OBJECT(TimeBasedRollingPolicy) struct TimeBasedRollingPolicy::TimeBasedRollingPolicyPrivate{ #if LOG4CXX_HAS_MULTIPROCESS_ROLLING_FILE_APPENDER TimeBasedRollingPolicyPrivate() : _mmap(nullptr), _file_map(nullptr), _lock_file(nullptr), bAlreadyInitialized(false), bRefreshCurFile(false){} #else TimeBasedRollingPolicyPrivate(){} #endif /** * Time for next determination if time for rollover. */ log4cxx_time_t nextCheck; /** * File name at last rollover. */ LogString lastFileName; /** * Length of any file type suffix (.gz, .zip). */ int suffixLength; /** * mmap pointer */ apr_mmap_t* _mmap; /* * pool for mmap handler * */ LOG4CXX_NS::helpers::Pool _mmapPool; /** * mmap file descriptor */ apr_file_t* _file_map; /** * mmap file name */ std::string _mapFileName; /* * lock file handle * */ apr_file_t* _lock_file; /** * Check nextCheck if it has already been set * Timebased rolling policy has an issue when working at low rps. * Under low rps, multiple processes will not be scheduled in time for the second chance(do rolling), * so the rolling mechanism will not be triggered even if the time period is out of date. * This results in log entries will be accumulated for serveral minutes to be rolling. * Adding this flag to provide rolling opportunity for a process even if it is writing the first log entry */ bool bAlreadyInitialized; /* * If the current file name contains date information, retrieve the current writting file from mmap * */ bool bRefreshCurFile; /* * mmap file name * */ LogString _fileNamePattern; bool multiprocess = false; bool throwIOExceptionOnForkFailure = true; }; #define MMAP_FILE_SUFFIX ".map" #define LOCK_FILE_SUFFIX ".maplck" #define MAX_FILE_LEN 2048 #if LOG4CXX_HAS_MULTIPROCESS_ROLLING_FILE_APPENDER bool TimeBasedRollingPolicy::isMapFileEmpty(LOG4CXX_NS::helpers::Pool& pool) { apr_finfo_t finfo; apr_status_t st = apr_stat(&finfo, m_priv->_mapFileName.c_str(), APR_FINFO_SIZE, pool.getAPRPool()); if (st != APR_SUCCESS) { LogLog::warn(LOG4CXX_STR("apr_stat failed.")); } if (st == APR_SUCCESS && !finfo.size) { return true; } return false; } void TimeBasedRollingPolicy::initMMapFile(const LogString& lastFileName, LOG4CXX_NS::helpers::Pool& pool) { int iRet = 0; if (!m_priv->_mmap) { iRet = createMMapFile(std::string(m_priv->_fileNamePattern), pool); } if (!iRet && isMapFileEmpty(pool)) { lockMMapFile(APR_FLOCK_EXCLUSIVE); memset(m_priv->_mmap->mm, 0, MAX_FILE_LEN); memcpy(m_priv->_mmap->mm, std::string(lastFileName).c_str(), std::string(lastFileName).size()); unLockMMapFile(); } } const std::string TimeBasedRollingPolicy::createFile(const std::string& fileName, const std::string& suffix, LOG4CXX_NS::helpers::Pool& pool) { char szUid[MAX_FILE_LEN] = {'\0'}; char szBaseName[MAX_FILE_LEN] = {'\0'}; char szDirName[MAX_FILE_LEN] = {'\0'}; memcpy(szDirName, fileName.c_str(), fileName.size() > MAX_FILE_LEN ? MAX_FILE_LEN : fileName.size()); memcpy(szBaseName, fileName.c_str(), fileName.size() > MAX_FILE_LEN ? MAX_FILE_LEN : fileName.size()); apr_uid_t uid; apr_gid_t groupid; apr_status_t stat = apr_uid_current(&uid, &groupid, pool.getAPRPool()); if (stat == APR_SUCCESS) { #ifdef _WIN32 snprintf(szUid, MAX_FILE_LEN, "%p", uid); #else snprintf(szUid, MAX_FILE_LEN, "%u", uid); #endif } LOG4CXX_NS::filesystem::path path(fileName); std::string newFilename = path.filename().string() + szUid + suffix; LOG4CXX_NS::filesystem::path retval = path.parent_path() / newFilename; return retval.string(); } int TimeBasedRollingPolicy::createMMapFile(const std::string& fileName, LOG4CXX_NS::helpers::Pool& pool) { m_priv->_mapFileName = createFile(fileName, MMAP_FILE_SUFFIX, pool); apr_status_t stat = apr_file_open(&m_priv->_file_map, m_priv->_mapFileName.c_str(), APR_CREATE | APR_READ | APR_WRITE, APR_OS_DEFAULT, m_priv->_mmapPool.getAPRPool()); if (stat != APR_SUCCESS) { std::string err(std::string("open mmap file failed. ") + std::string(strerror(errno)) + ". Check the privilege or try to remove " + m_priv->_mapFileName + " if exist."); LogLog::warn(LOG4CXX_STR(err.c_str())); return -1; } if (isMapFileEmpty(pool)) { stat = apr_file_trunc(m_priv->_file_map, MAX_FILE_LEN + 1); if (stat != APR_SUCCESS) { LogLog::warn(LOG4CXX_STR("apr_file_trunc failed.")); apr_file_close(m_priv->_file_map); return -1; } } stat = apr_mmap_create(&m_priv->_mmap, m_priv->_file_map, 0, MAX_FILE_LEN, APR_MMAP_WRITE | APR_MMAP_READ, m_priv->_mmapPool.getAPRPool()); if (stat != APR_SUCCESS) { LogLog::warn(LOG4CXX_STR("mmap failed.")); apr_file_close(m_priv->_file_map); return -1; } return 0; } int TimeBasedRollingPolicy::lockMMapFile(int type) { apr_status_t stat = apr_file_lock(m_priv->_lock_file, type); if (stat != APR_SUCCESS) { LogLog::warn(LOG4CXX_STR("apr_file_lock for mmap failed.")); } return stat; } int TimeBasedRollingPolicy::unLockMMapFile() { apr_status_t stat = apr_file_unlock(m_priv->_lock_file); if (stat != APR_SUCCESS) { LogLog::warn(LOG4CXX_STR("apr_file_unlock for mmap failed.")); } return stat; } #else int TimeBasedRollingPolicy::createMMapFile(const std::string&, LOG4CXX_NS::helpers::Pool&) { return 0; } bool TimeBasedRollingPolicy::isMapFileEmpty(LOG4CXX_NS::helpers::Pool&){ return true; } void TimeBasedRollingPolicy::initMMapFile(const LogString&, LOG4CXX_NS::helpers::Pool&){} int TimeBasedRollingPolicy::lockMMapFile(int){ return 0; } int TimeBasedRollingPolicy::unLockMMapFile(){ return 0; } const std::string TimeBasedRollingPolicy::createFile(const std::string&, const std::string&, LOG4CXX_NS::helpers::Pool&){ return ""; } #endif TimeBasedRollingPolicy::TimeBasedRollingPolicy() : m_priv(std::make_unique()) { } TimeBasedRollingPolicy::~TimeBasedRollingPolicy(){} void TimeBasedRollingPolicy::activateOptions(LOG4CXX_NS::helpers::Pool& pool) { // find out period from the filename pattern if (getFileNamePattern().length() > 0) { parseFileNamePattern(); } else { LogLog::warn( LOG4CXX_STR("The FileNamePattern option must be set before using TimeBasedRollingPolicy. ")); throw IllegalStateException(); } PatternConverterPtr dtc(getDatePatternConverter()); if (dtc == NULL) { throw IllegalStateException(); } LogString buf; ObjectPtr obj = std::make_shared(); formatFileName(obj, buf, pool); m_priv->lastFileName = buf; if( m_priv->multiprocess ){ #if LOG4CXX_HAS_MULTIPROCESS_ROLLING_FILE_APPENDER if (getPatternConverterList().size()) { (*(getPatternConverterList().begin()))->format(obj, m_priv->_fileNamePattern, pool); } else { m_priv->_fileNamePattern = m_priv->lastFileName; } if (!m_priv->_lock_file) { const std::string lockname = createFile(std::string(m_priv->_fileNamePattern), LOCK_FILE_SUFFIX, m_priv->_mmapPool); apr_status_t stat = apr_file_open(&m_priv->_lock_file, lockname.c_str(), APR_CREATE | APR_READ | APR_WRITE, APR_OS_DEFAULT, m_priv->_mmapPool.getAPRPool()); if (stat != APR_SUCCESS) { LogLog::warn(LOG4CXX_STR("open lock file failed.")); } } initMMapFile(m_priv->lastFileName, m_priv->_mmapPool); #endif } m_priv->suffixLength = 0; if (m_priv->lastFileName.length() >= 3) { if (m_priv->lastFileName.compare(m_priv->lastFileName.length() - 3, 3, LOG4CXX_STR(".gz")) == 0) { m_priv->suffixLength = 3; } else if (m_priv->lastFileName.length() >= 4 && m_priv->lastFileName.compare(m_priv->lastFileName.length() - 4, 4, LOG4CXX_STR(".zip")) == 0) { m_priv->suffixLength = 4; } } } #define RULES_PUT(spec, cls) \ specs.insert(PatternMap::value_type(LogString(LOG4CXX_STR(spec)), (PatternConstructor) cls ::newInstance)) LOG4CXX_NS::pattern::PatternMap TimeBasedRollingPolicy::getFormatSpecifiers() const { PatternMap specs; RULES_PUT("d", FileDatePatternConverter); RULES_PUT("date", FileDatePatternConverter); return specs; } /** * {@inheritDoc} */ RolloverDescriptionPtr TimeBasedRollingPolicy::initialize( const LogString& currentActiveFile, const bool append, Pool& pool) { Date now; log4cxx_time_t n = now.getTime(); m_priv->nextCheck = now.getNextSecond(); File currentFile(currentActiveFile); LogString buf; ObjectPtr obj = std::make_shared(currentFile.exists(pool) ? currentFile.lastModified(pool) : n); formatFileName(obj, buf, pool); m_priv->lastFileName = buf; ActionPtr noAction; if (currentActiveFile.length() > 0) { return std::make_shared( currentActiveFile, append, noAction, noAction); } else { m_priv->bRefreshCurFile = true; return std::make_shared( m_priv->lastFileName.substr(0, m_priv->lastFileName.length() - m_priv->suffixLength), append, noAction, noAction); } } RolloverDescriptionPtr TimeBasedRollingPolicy::rollover( const LogString& currentActiveFile, const bool append, Pool& pool) { Date now; log4cxx_time_t n = now.getTime(); m_priv->nextCheck = now.getNextSecond(); LogString buf; ObjectPtr obj = std::make_shared(n); formatFileName(obj, buf, pool); LogString newFileName(buf); if( m_priv->multiprocess ){ #if LOG4CXX_HAS_MULTIPROCESS_ROLLING_FILE_APPENDER m_priv->bAlreadyInitialized = true; if (m_priv->_mmap && !isMapFileEmpty(m_priv->_mmapPool)) { lockMMapFile(APR_FLOCK_SHARED); LogString mapLastFile((char*)m_priv->_mmap->mm); m_priv->lastFileName = mapLastFile; unLockMMapFile(); } else { m_priv->_mmap = NULL; initMMapFile(m_priv->lastFileName, m_priv->_mmapPool); } #endif } // // if file names haven't changed, no rollover // if (newFileName == m_priv->lastFileName) { RolloverDescriptionPtr desc; return desc; } ActionPtr renameAction; ActionPtr compressAction; LogString lastBaseName( m_priv->lastFileName.substr(0, m_priv->lastFileName.length() - m_priv->suffixLength)); LogString nextActiveFile( newFileName.substr(0, newFileName.length() - m_priv->suffixLength)); if(getCreateIntermediateDirectories()){ File compressedFile(m_priv->lastFileName); File compressedParent (compressedFile.getParent(pool)); compressedParent.mkdirs(pool); } // // 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 != lastBaseName) { renameAction = std::make_shared( File().setPath(currentActiveFile), File().setPath(lastBaseName), true); nextActiveFile = currentActiveFile; } if (m_priv->suffixLength == 3) { GZCompressActionPtr comp = std::make_shared( File().setPath(lastBaseName), File().setPath(m_priv->lastFileName), true); comp->setThrowIOExceptionOnForkFailure(m_priv->throwIOExceptionOnForkFailure); compressAction = comp; } if (m_priv->suffixLength == 4) { ZipCompressActionPtr comp = std::make_shared( File().setPath(lastBaseName), File().setPath(m_priv->lastFileName), true); comp->setThrowIOExceptionOnForkFailure(m_priv->throwIOExceptionOnForkFailure); compressAction = comp; } if( m_priv->multiprocess ){ #if LOG4CXX_HAS_MULTIPROCESS_ROLLING_FILE_APPENDER if (m_priv->_mmap && !isMapFileEmpty(m_priv->_mmapPool)) { lockMMapFile(APR_FLOCK_EXCLUSIVE); memset(m_priv->_mmap->mm, 0, MAX_FILE_LEN); memcpy(m_priv->_mmap->mm, std::string(newFileName).c_str(), std::string(newFileName).size()); unLockMMapFile(); } else { m_priv->_mmap = NULL; initMMapFile(newFileName, m_priv->_mmapPool); } #endif }else{ m_priv->lastFileName = newFileName; } return std::make_shared(nextActiveFile, append, renameAction, compressAction); } bool TimeBasedRollingPolicy::isTriggeringEvent( Appender* appender, const LOG4CXX_NS::spi::LoggingEventPtr& /* event */, const LogString& filename, size_t /* fileLength */) { if( m_priv->multiprocess ){ #if LOG4CXX_HAS_MULTIPROCESS_ROLLING_FILE_APPENDER if (m_priv->bRefreshCurFile && m_priv->_mmap && !isMapFileEmpty(m_priv->_mmapPool)) { lockMMapFile(APR_FLOCK_SHARED); LogString mapCurrent((char*)m_priv->_mmap->mm); unLockMMapFile(); LogString mapCurrentBase(mapCurrent.substr(0, mapCurrent.length() - m_priv->suffixLength)); if (!mapCurrentBase.empty() && mapCurrentBase != filename) { const FileAppender* fappend = reinterpret_cast(appender->cast(FileAppender::getStaticClass())); if( fappend ){ const_cast(fappend)->setFile(mapCurrentBase); } } } return ( Date::currentTime() > m_priv->nextCheck) || (!m_priv->bAlreadyInitialized); #endif } return Date::currentTime() > m_priv->nextCheck; } void TimeBasedRollingPolicy::setMultiprocess(bool multiprocess){ #if LOG4CXX_HAS_MULTIPROCESS_ROLLING_FILE_APPENDER // If we don't have the multiprocess stuff, disregard any attempt to set this value m_priv->multiprocess = multiprocess; #endif } void TimeBasedRollingPolicy::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("THROWIOEXCEPTIONONFORKFAILURE"), LOG4CXX_STR("throwioexceptiononforkfailure"))) { m_priv->throwIOExceptionOnForkFailure = OptionConverter::toBoolean(value, true); } else { RollingPolicyBase::setOption(option, value); } } apache-log4cxx-1.3.1/src/main/cpp/loggerpatternconverter.cpp0000644000175100001770000000353714721727031023512 0ustar runnerdocker/* * 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. */ #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::pattern; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(LoggerPatternConverter) LoggerPatternConverter::LoggerPatternConverter( const std::vector& options) : NamePatternConverter(LOG4CXX_STR("Logger"), LOG4CXX_STR("logger"), options) { } PatternConverterPtr LoggerPatternConverter::newInstance( const std::vector& options) { if (options.size() == 0) { static WideLife def = std::make_shared(options); return def; } return std::make_shared(options); } void LoggerPatternConverter::format( const LoggingEventPtr& event, LogString& toAppendTo, Pool& /* p */ ) const { int initialLength = (int)toAppendTo.length(); toAppendTo.append(event->getLoggerName()); abbreviate(initialLength, toAppendTo); } apache-log4cxx-1.3.1/src/main/cpp/domconfigurator.cpp0000644000175100001770000010011714721727031022077 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if LOG4CXX_ABI_VERSION <= 15 #include #else #include #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define LOG4CXX 1 #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::xml; using namespace LOG4CXX_NS::helpers; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::config; using namespace LOG4CXX_NS::rolling; #define MAX_ATTRIBUTE_NAME_LEN 2000 struct DOMConfigurator::DOMConfiguratorPrivate { helpers::Properties props; spi::LoggerRepositoryPtr repository; spi::LoggerFactoryPtr loggerFactory; }; namespace LOG4CXX_NS { namespace xml { class XMLWatchdog : public FileWatchdog { public: XMLWatchdog(const File& filename) : FileWatchdog(filename) { } /** Call DOMConfigurator#doConfigure with the filename to reconfigure log4cxx. */ void doOnChange() { DOMConfigurator().doConfigure(file(), LogManager::getLoggerRepository()); } }; } } XMLWatchdog* DOMConfigurator::xdog = NULL; IMPLEMENT_LOG4CXX_OBJECT(DOMConfigurator) #define CONFIGURATION_TAG "log4j:configuration" #define OLD_CONFIGURATION_TAG "configuration" #define APPENDER_TAG "appender" #define APPENDER_REF_TAG "appender-ref" #define PARAM_TAG "param" #define LAYOUT_TAG "layout" #define ROLLING_POLICY_TAG "rollingPolicy" #define TRIGGERING_POLICY_TAG "triggeringPolicy" #define CATEGORY "category" #define LOGGER "logger" #define LOGGER_REF "logger-ref" #define CATEGORY_FACTORY_TAG "categoryFactory" #define NAME_ATTR "name" #define CLASS_ATTR "class" #define VALUE_ATTR "value" #define ROOT_TAG "root" #define ROOT_REF "root-ref" #define LEVEL_TAG "level" #define PRIORITY_TAG "priority" #define FILTER_TAG "filter" #define ERROR_HANDLER_TAG "errorHandler" #define REF_ATTR "ref" #define ADDITIVITY_ATTR "additivity" #define THRESHOLD_ATTR "threshold" #define STRINGSTREAM_ATTR "stringstream" #define CONFIG_DEBUG_ATTR "configDebug" #define INTERNAL_DEBUG_ATTR "debug" #define THREAD_CONFIG_ATTR "threadConfiguration" DOMConfigurator::DOMConfigurator() : m_priv(std::make_unique()) { } DOMConfigurator::~DOMConfigurator() {} /** Used internally to parse appenders by IDREF name. */ AppenderPtr DOMConfigurator::findAppenderByName(LOG4CXX_NS::helpers::Pool& p, LOG4CXX_NS::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* element, apr_xml_doc* doc, const LogString& appenderName, AppenderMap& appenders) { AppenderPtr appender; std::string tagName(element->name); if (tagName == APPENDER_TAG) { if (appenderName == getAttribute(utf8Decoder, element, NAME_ATTR)) { appender = parseAppender(p, utf8Decoder, element, doc, appenders); } } if (element->first_child && !appender) { appender = findAppenderByName(p, utf8Decoder, element->first_child, doc, appenderName, appenders); } if (element->next && !appender) { appender = findAppenderByName(p, utf8Decoder, element->next, doc, appenderName, appenders); } return appender; } /** Used internally to parse appenders by IDREF element. */ AppenderPtr DOMConfigurator::findAppenderByReference( LOG4CXX_NS::helpers::Pool& p, LOG4CXX_NS::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* appenderRef, apr_xml_doc* doc, AppenderMap& appenders) { LogString appenderName(subst(getAttribute(utf8Decoder, appenderRef, REF_ATTR))); AppenderMap::const_iterator match = appenders.find(appenderName); AppenderPtr appender; if (match != appenders.end()) { appender = match->second; } else if (doc) { appender = findAppenderByName(p, utf8Decoder, doc->root, doc, appenderName, appenders); if (appender) { appenders.insert(AppenderMap::value_type(appenderName, appender)); } } if (!appender) { LogLog::error(LOG4CXX_STR("No appender named [") + appenderName + LOG4CXX_STR("] could be found.")); } return appender; } /** Used internally to parse an appender element. */ AppenderPtr DOMConfigurator::parseAppender(Pool& p, LOG4CXX_NS::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* appenderElement, apr_xml_doc* doc, AppenderMap& appenders) { LogString className(subst(getAttribute(utf8Decoder, appenderElement, CLASS_ATTR))); if (LogLog::isDebugEnabled()) { LogLog::debug(LOG4CXX_STR("Class name: [") + className + LOG4CXX_STR("]")); } try { ObjectPtr instance = ObjectPtr(Loader::loadClass(className).newInstance()); AppenderPtr appender = LOG4CXX_NS::cast(instance); PropertySetter propSetter(appender); appender->setName(subst(getAttribute(utf8Decoder, appenderElement, NAME_ATTR))); for (apr_xml_elem* currentElement = appenderElement->first_child; currentElement; currentElement = currentElement->next) { std::string tagName(currentElement->name); // Parse appender parameters if (tagName == PARAM_TAG) { setParameter(p, utf8Decoder, currentElement, propSetter); } // Set appender layout else if (tagName == LAYOUT_TAG) { appender->setLayout(parseLayout(p, utf8Decoder, currentElement)); } // Add filters else if (tagName == FILTER_TAG) { std::vector filters; parseFilters(p, utf8Decoder, currentElement, filters); for (auto& item : filters) { appender->addFilter(item); } } else if (tagName == ERROR_HANDLER_TAG) { parseErrorHandler(p, utf8Decoder, currentElement, appender, doc, appenders); } else if (tagName == ROLLING_POLICY_TAG) { RollingPolicyPtr rollPolicy(parseRollingPolicy(p, utf8Decoder, currentElement)); RollingFileAppenderPtr rfa = LOG4CXX_NS::cast(appender); if (rfa != NULL) { rfa->setRollingPolicy(rollPolicy); } } else if (tagName == TRIGGERING_POLICY_TAG) { ObjectPtr policy(parseTriggeringPolicy(p, utf8Decoder, currentElement)); RollingFileAppenderPtr rfa = LOG4CXX_NS::cast(appender); TriggeringPolicyPtr policyPtr = LOG4CXX_NS::cast(policy); if (rfa != NULL) { rfa->setTriggeringPolicy(policyPtr); } else { auto smtpa = LOG4CXX_NS::cast(appender); if (smtpa != NULL) { auto evaluator = LOG4CXX_NS::cast(policy); smtpa->setEvaluator(evaluator); } } } else if (tagName == APPENDER_REF_TAG) { LogString refName = subst(getAttribute(utf8Decoder, currentElement, REF_ATTR)); if (appender->instanceof(AppenderAttachable::getStaticClass())) { AppenderAttachablePtr aa = LOG4CXX_NS::cast(appender); if (LogLog::isDebugEnabled()) { LogLog::debug(LOG4CXX_STR("Attaching appender named [") + refName + LOG4CXX_STR("] to appender named [") + appender->getName() + LOG4CXX_STR("].")); } aa->addAppender(findAppenderByReference(p, utf8Decoder, currentElement, doc, appenders)); } else { LogLog::error(LOG4CXX_STR("Requesting attachment of appender named [") + refName + LOG4CXX_STR("] to appender named [") + appender->getName() + LOG4CXX_STR("] which does not implement AppenderAttachable.")); } } } propSetter.activate(p); 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(LOG4CXX_STR("Could not create an Appender. Reported error follows."), oops); return 0; } } /** Used internally to parse an {@link ErrorHandler} element. */ void DOMConfigurator::parseErrorHandler(Pool& p, LOG4CXX_NS::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* element, AppenderPtr& appender, apr_xml_doc* doc, AppenderMap& appenders) { ErrorHandlerPtr eh; std::shared_ptr obj = OptionConverter::instantiateByClassName( subst(getAttribute(utf8Decoder, element, CLASS_ATTR)), ErrorHandler::getStaticClass(), 0); eh = LOG4CXX_NS::cast(obj); if (eh != 0) { eh->setAppender(appender); PropertySetter propSetter(eh); for (apr_xml_elem* currentElement = element->first_child; currentElement; currentElement = currentElement->next) { std::string tagName(currentElement->name); if (tagName == PARAM_TAG) { setParameter(p, utf8Decoder, currentElement, propSetter); } else if (tagName == APPENDER_REF_TAG) { eh->setBackupAppender(findAppenderByReference(p, utf8Decoder, currentElement, doc, appenders)); } else if (tagName == LOGGER_REF) { LogString loggerName(getAttribute(utf8Decoder, currentElement, REF_ATTR)); LoggerPtr logger = m_priv->repository->getLogger(loggerName, m_priv->loggerFactory); eh->setLogger(logger); } else if (tagName == ROOT_REF) { LoggerPtr root = m_priv->repository->getRootLogger(); eh->setLogger(root); } } propSetter.activate(p); std::shared_ptr appSkeleton = LOG4CXX_NS::cast(appender); if (appSkeleton != 0) { appSkeleton->setErrorHandler(eh); } } } /** Used internally to parse a filter element. */ void DOMConfigurator::parseFilters(Pool& p, LOG4CXX_NS::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* element, std::vector& filters) { LogString clazz = subst(getAttribute(utf8Decoder, element, CLASS_ATTR)); FilterPtr filter; std::shared_ptr obj = OptionConverter::instantiateByClassName(clazz, Filter::getStaticClass(), 0); filter = LOG4CXX_NS::cast(obj); if (filter != 0) { PropertySetter propSetter(filter); for (apr_xml_elem* currentElement = element->first_child; currentElement; currentElement = currentElement->next) { std::string tagName(currentElement->name); if (tagName == PARAM_TAG) { setParameter(p, utf8Decoder, currentElement, propSetter); } } propSetter.activate(p); filters.push_back(filter); } } /** Used internally to parse an category or logger element. */ void DOMConfigurator::parseLogger( LOG4CXX_NS::helpers::Pool& p, LOG4CXX_NS::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* loggerElement, apr_xml_doc* doc, AppenderMap& appenders) { // Create a new Logger object from the element. LogString loggerName = subst(getAttribute(utf8Decoder, loggerElement, NAME_ATTR)); if (LogLog::isDebugEnabled()) { LogLog::debug(LOG4CXX_STR("Retreiving an instance of ") + loggerName); } LoggerPtr logger = m_priv->repository->getLogger(loggerName, m_priv->loggerFactory); // Setting up a logger needs to be an atomic operation, in order // to protect potential log operations while logger // configuration is in progress. bool additivity = OptionConverter::toBoolean( subst(getAttribute(utf8Decoder, loggerElement, ADDITIVITY_ATTR)), true); if (LogLog::isDebugEnabled()) { LogLog::debug(LOG4CXX_STR("Setting [") + logger->getName() + LOG4CXX_STR("] additivity to [") + (additivity ? LogString(LOG4CXX_STR("true")) : LogString(LOG4CXX_STR("false"))) + LOG4CXX_STR("].")); } logger->setAdditivity(additivity); parseChildrenOfLoggerElement(p, utf8Decoder, loggerElement, logger, false, doc, appenders); } /** Used internally to parse the logger factory element. */ void DOMConfigurator::parseLoggerFactory( LOG4CXX_NS::helpers::Pool& p, LOG4CXX_NS::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* factoryElement) { LogString className(subst(getAttribute(utf8Decoder, factoryElement, CLASS_ATTR))); if (className.empty()) { LogLog::error(LOG4CXX_STR("Logger Factory tag class attribute not found.")); } else { if (LogLog::isDebugEnabled()) { LogLog::debug(LOG4CXX_STR("Desired logger factory: [") + className + LOG4CXX_STR("]")); } std::shared_ptr obj = OptionConverter::instantiateByClassName( className, LoggerFactory::getStaticClass(), 0); m_priv->loggerFactory = LOG4CXX_NS::cast(obj); PropertySetter propSetter(m_priv->loggerFactory); for (apr_xml_elem* currentElement = factoryElement->first_child; currentElement; currentElement = currentElement->next) { std::string tagName(currentElement->name); if (tagName == PARAM_TAG) { setParameter(p, utf8Decoder, currentElement, propSetter); } } } } /** Used internally to parse the root logger element. */ void DOMConfigurator::parseRoot( LOG4CXX_NS::helpers::Pool& p, LOG4CXX_NS::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* rootElement, apr_xml_doc* doc, AppenderMap& appenders) { LoggerPtr root = m_priv->repository->getRootLogger(); parseChildrenOfLoggerElement(p, utf8Decoder, rootElement, root, true, doc, appenders); } /** Used internally to parse the children of a logger element. */ void DOMConfigurator::parseChildrenOfLoggerElement( LOG4CXX_NS::helpers::Pool& p, LOG4CXX_NS::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* loggerElement, LoggerPtr logger, bool isRoot, apr_xml_doc* doc, AppenderMap& appenders) { PropertySetter propSetter(logger); std::vector newappenders; // Remove all existing appenders from logger. They will be // reconstructed if need be. logger->removeAllAppenders(); for (apr_xml_elem* currentElement = loggerElement->first_child; currentElement; currentElement = currentElement->next) { std::string tagName(currentElement->name); if (tagName == APPENDER_REF_TAG) { AppenderPtr appender = findAppenderByReference(p, utf8Decoder, currentElement, doc, appenders); LogString refName = subst(getAttribute(utf8Decoder, currentElement, REF_ATTR)); if (!LogLog::isDebugEnabled()) ; else if (appender != 0) { LogLog::debug(LOG4CXX_STR("Adding appender named [") + refName + LOG4CXX_STR("] to logger [") + logger->getName() + LOG4CXX_STR("].")); } else { LogLog::debug(LOG4CXX_STR("Appender named [") + refName + LOG4CXX_STR("] not found.")); } logger->addAppender(appender); } else if (tagName == LEVEL_TAG) { parseLevel(p, utf8Decoder, currentElement, logger, isRoot); } else if (tagName == PRIORITY_TAG) { parseLevel(p, utf8Decoder, currentElement, logger, isRoot); } else if (tagName == PARAM_TAG) { setParameter(p, utf8Decoder, currentElement, propSetter); } } propSetter.activate(p); } /** Used internally to parse a layout element. */ LayoutPtr DOMConfigurator::parseLayout ( LOG4CXX_NS::helpers::Pool& p, LOG4CXX_NS::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* layout_element) { LogString className(subst(getAttribute(utf8Decoder, layout_element, CLASS_ATTR))); if (LogLog::isDebugEnabled()) { LogLog::debug(LOG4CXX_STR("Parsing layout of class: \"") + className + LOG4CXX_STR("\"")); } try { ObjectPtr instance = ObjectPtr(Loader::loadClass(className).newInstance()); LayoutPtr layout = LOG4CXX_NS::cast(instance); PropertySetter propSetter(layout); for (apr_xml_elem* currentElement = layout_element->first_child; currentElement; currentElement = currentElement->next) { std::string tagName(currentElement->name); if (tagName == PARAM_TAG) { setParameter(p, utf8Decoder, currentElement, propSetter); } } propSetter.activate(p); return layout; } catch (Exception& oops) { LogLog::error(LOG4CXX_STR("Could not create the Layout. Reported error follows."), oops); return 0; } } /** Used internally to parse a triggering policy */ ObjectPtr DOMConfigurator::parseTriggeringPolicy ( LOG4CXX_NS::helpers::Pool& p, LOG4CXX_NS::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* layout_element) { LogString className = subst(getAttribute(utf8Decoder, layout_element, CLASS_ATTR)); if (LogLog::isDebugEnabled()) { LogLog::debug(LOG4CXX_STR("Parsing triggering policy of class: \"") + className + LOG4CXX_STR("\"")); } try { ObjectPtr instance = ObjectPtr(Loader::loadClass(className).newInstance()); PropertySetter propSetter(instance); for (apr_xml_elem* currentElement = layout_element->first_child; currentElement; currentElement = currentElement->next) { std::string tagName(currentElement->name); if (tagName == PARAM_TAG) { setParameter(p, utf8Decoder, currentElement, propSetter); } else if (tagName == FILTER_TAG) { std::vector filters; parseFilters(p, utf8Decoder, currentElement, filters); FilterBasedTriggeringPolicyPtr fbtp = LOG4CXX_NS::cast(instance); if (fbtp != NULL) { for (auto& item : filters) { fbtp->addFilter(item); } } } } propSetter.activate(p); return instance; } catch (Exception& oops) { LogLog::error(LOG4CXX_STR("Could not create the TriggeringPolicy. Reported error follows."), oops); return 0; } } /** Used internally to parse a triggering policy */ RollingPolicyPtr DOMConfigurator::parseRollingPolicy ( LOG4CXX_NS::helpers::Pool& p, LOG4CXX_NS::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* layout_element) { LogString className = subst(getAttribute(utf8Decoder, layout_element, CLASS_ATTR)); if (LogLog::isDebugEnabled()) { LogLog::debug(LOG4CXX_STR("Parsing rolling policy of class: \"") + className + LOG4CXX_STR("\"")); } try { ObjectPtr instance = ObjectPtr(Loader::loadClass(className).newInstance()); RollingPolicyPtr layout = LOG4CXX_NS::cast(instance); PropertySetter propSetter(layout); for (apr_xml_elem* currentElement = layout_element->first_child; currentElement; currentElement = currentElement->next) { std::string tagName(currentElement->name); if (tagName == PARAM_TAG) { setParameter(p, utf8Decoder, currentElement, propSetter); } } propSetter.activate(p); return layout; } catch (Exception& oops) { LogLog::error(LOG4CXX_STR("Could not create the RollingPolicy. Reported error follows."), oops); return 0; } } /** Used internally to parse a level element. */ void DOMConfigurator::parseLevel( LOG4CXX_NS::helpers::Pool& p, LOG4CXX_NS::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* element, LoggerPtr logger, bool isRoot) { LogString loggerName = logger->getName(); if (isRoot) { loggerName = LOG4CXX_STR("root"); } LogString levelStr(subst(getAttribute(utf8Decoder, element, VALUE_ATTR))); if (LogLog::isDebugEnabled()) { LogLog::debug(LOG4CXX_STR("Level value for ") + loggerName + LOG4CXX_STR(" is [") + levelStr + LOG4CXX_STR("].")); } if (StringHelper::equalsIgnoreCase(levelStr, LOG4CXX_STR("INHERITED"), LOG4CXX_STR("inherited")) || StringHelper::equalsIgnoreCase(levelStr, LOG4CXX_STR("NULL"), LOG4CXX_STR("null"))) { if (isRoot) { LogLog::error(LOG4CXX_STR("Root level cannot be inherited. Ignoring directive.")); } else { logger->setLevel(0); } } else { LogString className(subst(getAttribute(utf8Decoder, element, CLASS_ATTR))); if (className.empty()) { logger->setLevel(OptionConverter::toLevel(levelStr, Level::getDebug())); } else { if (LogLog::isDebugEnabled()) { LogLog::debug(LOG4CXX_STR("Desired Level sub-class: [") + className + LOG4CXX_STR("]")); } try { Level::LevelClass& levelClass = (Level::LevelClass&)Loader::loadClass(className); LevelPtr level = levelClass.toLevel(levelStr); logger->setLevel(level); } catch (Exception& oops) { LogLog::error( LOG4CXX_STR("Could not create level [") + levelStr + LOG4CXX_STR("]. Reported error follows."), oops); return; } catch (...) { LogLog::error( LOG4CXX_STR("Could not create level [") + levelStr); return; } } } if (LogLog::isDebugEnabled()) { LogLog::debug(loggerName + LOG4CXX_STR(" level set to ") + logger->getEffectiveLevel()->toString()); } } void DOMConfigurator::setParameter(LOG4CXX_NS::helpers::Pool& p, LOG4CXX_NS::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* elem, PropertySetter& propSetter) { LogString name(subst(getAttribute(utf8Decoder, elem, NAME_ATTR))); LogString value(subst(getAttribute(utf8Decoder, elem, VALUE_ATTR))); value = subst(value); propSetter.setProperty(name, value, p); } spi::ConfigurationStatus DOMConfigurator::doConfigure ( const File& filename #if LOG4CXX_ABI_VERSION <= 15 , spi::LoggerRepositoryPtr repository #else , const spi::LoggerRepositoryPtr& repository #endif ) { m_priv->repository = repository ? repository : LogManager::getLoggerRepository(); m_priv->repository->setConfigured(true); if (LogLog::isDebugEnabled()) { LogString msg(LOG4CXX_STR("DOMConfigurator configuring file ")); msg.append(filename.getPath()); msg.append(LOG4CXX_STR("...")); LogLog::debug(msg); } #if LOG4CXX_ABI_VERSION <= 15 m_priv->loggerFactory = std::make_shared(); #else m_priv->loggerFactory = std::make_shared(); #endif Pool p; apr_file_t* fd; log4cxx_status_t rv = filename.open(&fd, APR_READ, APR_OS_DEFAULT, p); if (rv != APR_SUCCESS) { // There is not technically an exception thrown here, but this behavior matches // what the PropertyConfigurator does IOException io(rv); LogString msg2(LOG4CXX_STR("Could not read configuration file [")); msg2.append(filename.getPath()); msg2.append(LOG4CXX_STR("]. ")); LOG4CXX_DECODE_CHAR(msg, io.what()); msg2.append(msg); LogLog::error(msg2); return spi::ConfigurationStatus::NotConfigured; } else { apr_xml_parser* parser = NULL; apr_xml_doc* doc = NULL; if (LogLog::isDebugEnabled()) { LogString debugMsg = LOG4CXX_STR("Loading configuration file [") + filename.getPath() + LOG4CXX_STR("]."); LogLog::debug(debugMsg); } rv = apr_xml_parse_file(p.getAPRPool(), &parser, &doc, fd, 2000); if (rv != APR_SUCCESS) { char errbuf[2000]; char errbufXML[2000]; LogString msg2(LOG4CXX_STR("Error parsing file [")); msg2.append(filename.getPath()); msg2.append(LOG4CXX_STR("], ")); apr_strerror(rv, errbuf, sizeof(errbuf)); LOG4CXX_DECODE_CHAR(lerrbuf, std::string(errbuf)); msg2.append(lerrbuf); if (parser) { apr_xml_parser_geterror(parser, errbufXML, sizeof(errbufXML)); LOG4CXX_DECODE_CHAR(lerrbufXML, std::string(errbufXML)); msg2.append(lerrbufXML); } LogLog::error(msg2); return spi::ConfigurationStatus::NotConfigured; } else { AppenderMap appenders; CharsetDecoderPtr utf8Decoder(CharsetDecoder::getUTF8Decoder()); parse(p, utf8Decoder, doc->root, doc, appenders); } } return spi::ConfigurationStatus::Configured; } // Read configuration options from \c filename. spi::ConfigurationStatus DOMConfigurator::configure(const File& filename) { return DOMConfigurator().doConfigure(filename, LogManager::getLoggerRepository()); } #if LOG4CXX_ABI_VERSION <= 15 spi::ConfigurationStatus DOMConfigurator::configure(const std::string& filename) { File file(filename); return DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository()); } #if LOG4CXX_WCHAR_T_API spi::ConfigurationStatus DOMConfigurator::configure(const std::wstring& filename) { File file(filename); return DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository()); } #endif #if LOG4CXX_UNICHAR_API || LOG4CXX_LOGCHAR_IS_UNICHAR spi::ConfigurationStatus DOMConfigurator::configure(const std::basic_string& filename) { File file(filename); return DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository()); } #endif #if LOG4CXX_CFSTRING_API spi::ConfigurationStatus DOMConfigurator::configure(const CFStringRef& filename) { File file(filename); return DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository()); } #endif spi::ConfigurationStatus DOMConfigurator::configureAndWatch(const std::string& filename) { return configureAndWatch(filename, FileWatchdog::DEFAULT_DELAY); } #if LOG4CXX_WCHAR_T_API spi::ConfigurationStatus DOMConfigurator::configureAndWatch(const std::wstring& filename) { return configureAndWatch(filename, FileWatchdog::DEFAULT_DELAY); } #endif #if LOG4CXX_UNICHAR_API || LOG4CXX_LOGCHAR_IS_UNICHAR spi::ConfigurationStatus DOMConfigurator::configureAndWatch(const std::basic_string& filename) { return configureAndWatch(filename, FileWatchdog::DEFAULT_DELAY); } #endif #if LOG4CXX_CFSTRING_API spi::ConfigurationStatus DOMConfigurator::configureAndWatch(const CFStringRef& filename) { return configureAndWatch(filename, FileWatchdog::DEFAULT_DELAY); } #endif spi::ConfigurationStatus DOMConfigurator::configureAndWatch(const std::string& filename, long delay) { return configureAndWatch(File(filename), delay); } #endif // LOG4CXX_ABI_VERSION <= 15 spi::ConfigurationStatus DOMConfigurator::configureAndWatch(const File& file, long delay) { if ( xdog ) { APRInitializer::unregisterCleanup(xdog); delete xdog; } spi::ConfigurationStatus status = DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository()); xdog = new XMLWatchdog(file); APRInitializer::registerCleanup(xdog); xdog->setDelay(0 < delay ? delay : FileWatchdog::DEFAULT_DELAY); xdog->start(); return status; } #if LOG4CXX_ABI_VERSION <= 15 #if LOG4CXX_WCHAR_T_API spi::ConfigurationStatus DOMConfigurator::configureAndWatch(const std::wstring& filename, long delay) { File file(filename); if ( xdog ) { APRInitializer::unregisterCleanup(xdog); delete xdog; } spi::ConfigurationStatus status = DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository()); xdog = new XMLWatchdog(file); APRInitializer::registerCleanup(xdog); xdog->setDelay(delay); xdog->start(); return status; } #endif #if LOG4CXX_UNICHAR_API || LOG4CXX_LOGCHAR_IS_UNICHAR spi::ConfigurationStatus DOMConfigurator::configureAndWatch(const std::basic_string& filename, long delay) { File file(filename); if ( xdog ) { APRInitializer::unregisterCleanup(xdog); delete xdog; } spi::ConfigurationStatus status = DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository()); xdog = new XMLWatchdog(file); APRInitializer::registerCleanup(xdog); xdog->setDelay(delay); xdog->start(); return status; } #endif #if LOG4CXX_CFSTRING_API spi::ConfigurationStatus DOMConfigurator::configureAndWatch(const CFStringRef& filename, long delay) { File file(filename); if ( xdog ) { APRInitializer::unregisterCleanup(xdog); delete xdog; } spi::ConfigurationStatus status = DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository()); xdog = new XMLWatchdog(file); APRInitializer::registerCleanup(xdog); xdog->setDelay(delay); xdog->start(); return status; } #endif #endif // LOG4CXX_ABI_VERSION <= 15 void DOMConfigurator::parse( Pool& p, LOG4CXX_NS::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* element, apr_xml_doc* doc, AppenderMap& appenders) { std::string rootElementName(element->name); if (rootElementName != CONFIGURATION_TAG) { if (rootElementName == OLD_CONFIGURATION_TAG) { //LogLog::warn(LOG4CXX_STR("The <")+String(OLD_CONFIGURATION_TAG)+ // LOG4CXX_STR("> element has been deprecated.")); //LogLog::warn(LOG4CXX_STR("Use the <")+String(CONFIGURATION_TAG)+ // LOG4CXX_STR("> element instead.")); } else { LogLog::error(LOG4CXX_STR("DOM element is - not a element.")); return; } } LogString debugAttrib = subst(getAttribute(utf8Decoder, element, INTERNAL_DEBUG_ATTR)); static const WideLife NULL_STRING(LOG4CXX_STR("NULL")); if (LogLog::isDebugEnabled()) { LogLog::debug(LOG4CXX_STR("debug attribute= \"") + debugAttrib + LOG4CXX_STR("\".")); } // if the log4j.dtd is not specified in the XML file, then the // "debug" attribute is returned as the empty string. if (!debugAttrib.empty() && debugAttrib != NULL_STRING.value()) { LogLog::setInternalDebugging(OptionConverter::toBoolean(debugAttrib, true)); } else if (LogLog::isDebugEnabled()) { LogLog::debug(LOG4CXX_STR("Ignoring internalDebug attribute.")); } LogString confDebug = subst(getAttribute(utf8Decoder, element, CONFIG_DEBUG_ATTR)); if (!confDebug.empty() && confDebug != NULL_STRING.value()) { LogLog::warn(LOG4CXX_STR("The \"configDebug\" attribute is deprecated.")); LogLog::warn(LOG4CXX_STR("Use the \"internalDebug\" attribute instead.")); LogLog::setInternalDebugging(OptionConverter::toBoolean(confDebug, true)); } LogString thresholdStr = subst(getAttribute(utf8Decoder, element, THRESHOLD_ATTR)); if (LogLog::isDebugEnabled()) { LogLog::debug(LOG4CXX_STR("Threshold =\"") + thresholdStr + LOG4CXX_STR("\".")); } if (!thresholdStr.empty() && thresholdStr != NULL_STRING.value()) { m_priv->repository->setThreshold(thresholdStr); } LogString threadSignalValue = subst(getAttribute(utf8Decoder, element, THREAD_CONFIG_ATTR)); if ( !threadSignalValue.empty() && threadSignalValue != NULL_STRING.value() ) { if ( threadSignalValue == LOG4CXX_STR("NoConfiguration") ) { helpers::ThreadUtility::configure( ThreadConfigurationType::NoConfiguration ); } else if ( threadSignalValue == LOG4CXX_STR("BlockSignalsOnly") ) { helpers::ThreadUtility::configure( ThreadConfigurationType::BlockSignalsOnly ); } else if ( threadSignalValue == LOG4CXX_STR("NameThreadOnly") ) { helpers::ThreadUtility::configure( ThreadConfigurationType::NameThreadOnly ); } else if ( threadSignalValue == LOG4CXX_STR("BlockSignalsAndNameThread") ) { helpers::ThreadUtility::configure( ThreadConfigurationType::BlockSignalsAndNameThread ); } } apr_xml_elem* currentElement; for (currentElement = element->first_child; currentElement; currentElement = currentElement->next) { std::string tagName(currentElement->name); if (tagName == CATEGORY_FACTORY_TAG) { parseLoggerFactory(p, utf8Decoder, currentElement); } } for (currentElement = element->first_child; currentElement; currentElement = currentElement->next) { std::string tagName(currentElement->name); if (tagName == CATEGORY || tagName == LOGGER) { parseLogger(p, utf8Decoder, currentElement, doc, appenders); } else if (tagName == ROOT_TAG) { parseRoot(p, utf8Decoder, currentElement, doc, appenders); } } } LogString DOMConfigurator::subst(const LogString& value) { try { return OptionConverter::substVars(value, m_priv->props); } catch (IllegalArgumentException& e) { LogLog::warn(LOG4CXX_STR("Could not perform variable substitution."), e); return value; } } LogString DOMConfigurator::getAttribute( LOG4CXX_NS::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* element, const std::string& attrName) { LogString attrValue; for (apr_xml_attr* attr = element->attr; attr; attr = attr->next) { if (attrName == attr->name) { ByteBuffer buf((char*) attr->value, strnlen_s(attr->value, MAX_ATTRIBUTE_NAME_LEN)); utf8Decoder->decode(buf, attrValue); } } return attrValue; } apache-log4cxx-1.3.1/src/main/cpp/charsetencoder.cpp0000644000175100001770000003532314721727031021674 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include #include #include #ifdef LOG4CXX_HAS_WCSTOMBS #include #endif using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(CharsetEncoder) namespace LOG4CXX_NS { namespace helpers { #if APR_HAS_XLATE /** * A character encoder implemented using apr_xlate. */ class APRCharsetEncoder : public CharsetEncoder { public: APRCharsetEncoder(const LogString& topage) : pool() { #if LOG4CXX_LOGCHAR_IS_WCHAR const char* frompage = "WCHAR_T"; #endif #if LOG4CXX_LOGCHAR_IS_UTF8 const char* frompage = "UTF-8"; #endif #if LOG4CXX_LOGCHAR_IS_UNICHAR const char* frompage = "UTF-16"; #endif std::string tpage(Transcoder::encodeCharsetName(topage)); apr_status_t stat = apr_xlate_open(&convset, tpage.c_str(), frompage, pool.getAPRPool()); if (stat != APR_SUCCESS) { throw IllegalArgumentException(topage); } } virtual ~APRCharsetEncoder() { } virtual log4cxx_status_t encode(const LogString& in, LogString::const_iterator& iter, ByteBuffer& out) { apr_status_t stat; size_t outbytes_left = out.remaining(); size_t initial_outbytes_left = outbytes_left; size_t position = out.position(); if (iter == in.end()) { std::lock_guard lock(mutex); stat = apr_xlate_conv_buffer(convset, NULL, NULL, out.data() + position, &outbytes_left); } else { LogString::size_type inOffset = (iter - in.begin()); apr_size_t inbytes_left = (in.size() - inOffset) * sizeof(LogString::value_type); apr_size_t initial_inbytes_left = inbytes_left; { std::lock_guard lock(mutex); stat = apr_xlate_conv_buffer(convset, (const char*) (in.data() + inOffset), &inbytes_left, out.data() + position, &outbytes_left); } iter += ((initial_inbytes_left - inbytes_left) / sizeof(LogString::value_type)); } out.position(out.position() + (initial_outbytes_left - outbytes_left)); return stat; } private: APRCharsetEncoder(const APRCharsetEncoder&); APRCharsetEncoder& operator=(const APRCharsetEncoder&); Pool pool; std::mutex mutex; apr_xlate_t* convset; }; #endif #if LOG4CXX_LOGCHAR_IS_WCHAR && LOG4CXX_HAS_WCSTOMBS /** * A character encoder implemented using wcstombs. */ class WcstombsCharsetEncoder : public CharsetEncoder { public: WcstombsCharsetEncoder() { } /** * Converts a wchar_t to the default external multibyte encoding. */ log4cxx_status_t encode(const LogString& in, LogString::const_iterator& iter, ByteBuffer& out) { log4cxx_status_t stat = APR_SUCCESS; if (iter != in.end()) { size_t outbytes_left = out.remaining(); size_t position = out.position(); std::wstring::size_type inOffset = (iter - in.begin()); enum { BUFSIZE = 256 }; wchar_t buf[BUFSIZE]; size_t chunkSize = BUFSIZE - 1; if (chunkSize * MB_LEN_MAX > outbytes_left) { chunkSize = outbytes_left / MB_LEN_MAX; } if (chunkSize > in.length() - inOffset) { chunkSize = in.length() - inOffset; } memset(buf, 0, BUFSIZE * sizeof(wchar_t)); memcpy(buf, in.data() + inOffset, chunkSize * sizeof(wchar_t)); size_t converted = wcstombs(out.data() + position, buf, outbytes_left); if (converted == (size_t) -1) { stat = APR_BADARG; // // if unconvertable character was encountered // repeatedly halve source to get fragment that // can be converted for (chunkSize /= 2; chunkSize > 0; chunkSize /= 2) { buf[chunkSize] = 0; converted = wcstombs(out.data() + position, buf, outbytes_left); if (converted != (size_t) -1) { iter += chunkSize; out.position(out.position() + converted); break; } } } else { iter += chunkSize; out.position(out.position() + converted); } } return stat; } private: WcstombsCharsetEncoder(const WcstombsCharsetEncoder&); WcstombsCharsetEncoder& operator=(const WcstombsCharsetEncoder&); }; #endif /** * Encodes a LogString to US-ASCII. */ class USASCIICharsetEncoder : public CharsetEncoder { public: USASCIICharsetEncoder() { } virtual log4cxx_status_t encode(const LogString& in, LogString::const_iterator& iter, ByteBuffer& out) { log4cxx_status_t stat = APR_SUCCESS; if (iter != in.end()) { while (out.remaining() > 0 && iter != in.end()) { LogString::const_iterator prev(iter); unsigned int sv = Transcoder::decode(in, iter); if (sv <= 0x7F) { out.put((char) sv); } else { iter = prev; stat = APR_BADARG; break; } } } return stat; } private: USASCIICharsetEncoder(const USASCIICharsetEncoder&); USASCIICharsetEncoder& operator=(const USASCIICharsetEncoder&); }; /** * Converts a LogString to ISO-8859-1. */ class ISOLatinCharsetEncoder : public CharsetEncoder { public: ISOLatinCharsetEncoder() { } virtual log4cxx_status_t encode(const LogString& in, LogString::const_iterator& iter, ByteBuffer& out) { log4cxx_status_t stat = APR_SUCCESS; if (iter != in.end()) { while (out.remaining() > 0 && iter != in.end()) { LogString::const_iterator prev(iter); unsigned int sv = Transcoder::decode(in, iter); if (sv <= 0xFF) { out.put((char) sv); } else { iter = prev; stat = APR_BADARG; break; } } } return stat; } private: ISOLatinCharsetEncoder(const ISOLatinCharsetEncoder&); ISOLatinCharsetEncoder& operator=(const ISOLatinCharsetEncoder&); }; /** * Encodes a LogString to a byte array when the encodings are identical. */ class TrivialCharsetEncoder : public CharsetEncoder { public: TrivialCharsetEncoder() { } virtual log4cxx_status_t encode(const LogString& in, LogString::const_iterator& iter, ByteBuffer& out) { if (iter != in.end()) { size_t requested = in.length() - (iter - in.begin()); if (requested > out.remaining() / sizeof(logchar)) { requested = out.remaining() / sizeof(logchar); } memcpy(out.current(), (const char*) in.data() + (iter - in.begin()), requested * sizeof(logchar)); iter += requested; out.position(out.position() + requested * sizeof(logchar)); } return APR_SUCCESS; } private: TrivialCharsetEncoder(const TrivialCharsetEncoder&); TrivialCharsetEncoder& operator=(const TrivialCharsetEncoder&); }; #if LOG4CXX_LOGCHAR_IS_UTF8 typedef TrivialCharsetEncoder UTF8CharsetEncoder; #else /** * Converts a LogString to UTF-8. */ class UTF8CharsetEncoder : public CharsetEncoder { public: UTF8CharsetEncoder() { } virtual log4cxx_status_t encode(const LogString& in, LogString::const_iterator& iter, ByteBuffer& out) { while (iter != in.end() && out.remaining() >= 8) { unsigned int sv = Transcoder::decode(in, iter); if (sv == 0xFFFF) { return APR_BADARG; } Transcoder::encodeUTF8(sv, out); } return APR_SUCCESS; } private: UTF8CharsetEncoder(const UTF8CharsetEncoder&); UTF8CharsetEncoder& operator=(const UTF8CharsetEncoder&); }; #endif /** * Encodes a LogString to UTF16-BE. */ class UTF16BECharsetEncoder : public CharsetEncoder { public: UTF16BECharsetEncoder() { } virtual log4cxx_status_t encode(const LogString& in, LogString::const_iterator& iter, ByteBuffer& out) { while (iter != in.end() && out.remaining() >= 4) { unsigned int sv = Transcoder::decode(in, iter); if (sv == 0xFFFF) { return APR_BADARG; } Transcoder::encodeUTF16BE(sv, out); } return APR_SUCCESS; } private: UTF16BECharsetEncoder(const UTF16BECharsetEncoder&); UTF16BECharsetEncoder& operator=(const UTF16BECharsetEncoder&); }; /** * Encodes a LogString to UTF16-LE. */ class UTF16LECharsetEncoder : public CharsetEncoder { public: UTF16LECharsetEncoder() { } virtual log4cxx_status_t encode(const LogString& in, LogString::const_iterator& iter, ByteBuffer& out) { while (iter != in.end() && out.remaining() >= 4) { unsigned int sv = Transcoder::decode(in, iter); if (sv == 0xFFFF) { return APR_BADARG; } Transcoder::encodeUTF16LE(sv, out); } return APR_SUCCESS; } private: UTF16LECharsetEncoder(const UTF16LECharsetEncoder&); UTF16LECharsetEncoder& operator=(const UTF16LECharsetEncoder&); }; /** * Charset encoder that uses current locale settings. */ class LocaleCharsetEncoder : public CharsetEncoder { public: LocaleCharsetEncoder() : state() { } log4cxx_status_t encode ( const LogString& in , LogString::const_iterator& iter , ByteBuffer& out ) override { log4cxx_status_t result = APR_SUCCESS; #if !LOG4CXX_CHARSET_EBCDIC char* current = out.current(); size_t remain = out.remaining(); if (std::mbsinit(&this->state)) // ByteBuffer not partially encoded? { // Copy single byte characters for (; iter != in.end() && ((unsigned int) *iter) < 0x80 && 0 < remain; iter++, remain--, current++) { *current = *iter; } } #endif // Encode characters that may require multiple bytes while (iter != in.end() && MB_CUR_MAX <= remain) { auto ch = Transcoder::decode(in, iter); auto n = std::wcrtomb(current, ch, &this->state); if (static_cast(-1) == n) // not a valid wide character? { result = APR_BADARG; break; } remain -= n; current += n; } out.position(current - out.data()); return result; } private: std::mbstate_t state; }; } // namespace helpers } //namespace log4cxx CharsetEncoder::CharsetEncoder() { } CharsetEncoder::~CharsetEncoder() { } CharsetEncoderPtr CharsetEncoder::getDefaultEncoder() { static WideLife encoder(createDefaultEncoder()); // // if invoked after static variable destruction // (if logging is called in the destructor of a static object) // then create a new decoder. // if (encoder.value() == 0) { return CharsetEncoderPtr( createDefaultEncoder() ); } return encoder; } CharsetEncoder* CharsetEncoder::createDefaultEncoder() { #if LOG4CXX_CHARSET_UTF8 return new UTF8CharsetEncoder(); #elif LOG4CXX_CHARSET_ISO88591 return new ISOLatinCharsetEncoder(); #elif LOG4CXX_CHARSET_USASCII return new USASCIICharsetEncoder(); #elif LOG4CXX_LOGCHAR_IS_WCHAR && LOG4CXX_HAS_WCSTOMBS return new WcstombsCharsetEncoder(); #else return new LocaleCharsetEncoder(); #endif } CharsetEncoderPtr CharsetEncoder::getUTF8Encoder() { return std::make_shared(); } CharsetEncoderPtr CharsetEncoder::getEncoder(const LogString& charset) { if (StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("UTF-8"), LOG4CXX_STR("utf-8")) || StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("CP65001"), LOG4CXX_STR("cp65001"))) { return std::make_shared(); } else if (StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("C"), LOG4CXX_STR("c")) || charset == LOG4CXX_STR("646") || StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("US-ASCII"), LOG4CXX_STR("us-ascii")) || StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("ISO646-US"), LOG4CXX_STR("iso646-US")) || StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("ANSI_X3.4-1968"), LOG4CXX_STR("ansi_x3.4-1968")) || StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("CP20127"), LOG4CXX_STR("cp20127"))) { return std::make_shared(); } else if (StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("ISO-8859-1"), LOG4CXX_STR("iso-8859-1")) || StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("ISO-LATIN-1"), LOG4CXX_STR("iso-latin-1")) || StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("CP1252"), LOG4CXX_STR("cp1252"))) { return std::make_shared(); } else if (StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("UTF-16BE"), LOG4CXX_STR("utf-16be")) || StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("UTF-16"), LOG4CXX_STR("utf-16")) || StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("CP1200"), LOG4CXX_STR("cp1200"))) { return std::make_shared(); } else if (StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("UTF-16LE"), LOG4CXX_STR("utf-16le"))) { return std::make_shared(); } else if (StringHelper::equalsIgnoreCase(charset, LOG4CXX_STR("LOCALE"), LOG4CXX_STR("locale"))) { return std::make_shared(); } #if APR_HAS_XLATE return std::make_shared(charset); #else throw IllegalArgumentException(charset); #endif } void CharsetEncoder::reset() { } void CharsetEncoder::flush(ByteBuffer& /* out */ ) { } void CharsetEncoder::encode(CharsetEncoderPtr& enc, const LogString& src, LogString::const_iterator& iter, ByteBuffer& dst) { log4cxx_status_t stat = enc->encode(src, iter, dst); if (stat != APR_SUCCESS && iter != src.end()) { #if LOG4CXX_LOGCHAR_IS_WCHAR || LOG4CXX_LOGCHAR_IS_UNICHAR iter++; #elif LOG4CXX_LOGCHAR_IS_UTF8 // advance past this character and all continuation characters while ((*(++iter) & 0xC0) == 0x80); #else #error logchar is unrecognized #endif dst.put(Transcoder::LOSSCHAR); } } bool CharsetEncoder::isTriviallyCopyable(const LogString& src, const CharsetEncoderPtr& enc) { bool result; #if !LOG4CXX_CHARSET_EBCDIC if (dynamic_cast(enc.get())) { result = src.end() == std::find_if(src.begin(), src.end() , [](const logchar& ch) -> bool { return 0x80 <= (unsigned int)ch; }); } else #endif result = !!dynamic_cast(enc.get()); return result; } apache-log4cxx-1.3.1/src/main/cpp/multiprocessrollingfileappender.cpp0000644000175100001770000004145314721727031025403 0ustar runnerdocker/* * 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. */ #include #include #include #ifndef MAX_FILE_LEN #define MAX_FILE_LEN 2048 #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::rolling; using namespace LOG4CXX_NS::helpers; using namespace LOG4CXX_NS::spi; struct MultiprocessRollingFileAppender::MultiprocessRollingFileAppenderPriv : public FileAppenderPriv { MultiprocessRollingFileAppenderPriv() : FileAppenderPriv(), fileLength(0) {} /** * Triggering policy. */ TriggeringPolicyPtr triggeringPolicy; /** * Rolling policy. */ RollingPolicyPtr rollingPolicy; /** * Length of current active log file. */ size_t fileLength; /** * save the loggingevent */ spi::LoggingEventPtr _event; }; #define _priv static_cast(m_priv.get()) IMPLEMENT_LOG4CXX_OBJECT(MultiprocessRollingFileAppender) /** * Construct a new instance. */ MultiprocessRollingFileAppender::MultiprocessRollingFileAppender() : FileAppender (std::make_unique()) { } /** * Prepare instance of use. */ void MultiprocessRollingFileAppender::activateOptions(Pool& p) { if (_priv->rollingPolicy == NULL) { auto fwrp = std::make_shared(); fwrp->setFileNamePattern(getFile() + LOG4CXX_STR(".%i")); _priv->rollingPolicy = fwrp; } // // if no explicit triggering policy and rolling policy is both. // if (_priv->triggeringPolicy == NULL) { TriggeringPolicyPtr trig = LOG4CXX_NS::cast(_priv->rollingPolicy); if (trig != NULL) { _priv->triggeringPolicy = trig; } } if (_priv->triggeringPolicy == NULL) { _priv->triggeringPolicy = std::make_shared(); } { std::lock_guard lock(_priv->mutex); _priv->triggeringPolicy->activateOptions(p); _priv->rollingPolicy->activateOptions(p); try { RolloverDescriptionPtr rollover1 = _priv->rollingPolicy->initialize(getFile(), getAppend(), p); if (rollover1 != NULL) { ActionPtr syncAction(rollover1->getSynchronous()); if (syncAction != NULL) { syncAction->execute(p); } _priv->fileName = rollover1->getActiveFileName(); _priv->fileAppend = rollover1->getAppend(); // // async action not yet implemented // ActionPtr asyncAction(rollover1->getAsynchronous()); if (asyncAction != NULL) { asyncAction->execute(p); } } File activeFile; activeFile.setPath(getFile()); if (getAppend()) { _priv->fileLength = activeFile.length(p); } else { _priv->fileLength = 0; } FileAppender::activateOptionsInternal(p); } catch (std::exception&) { LogLog::warn( LogString(LOG4CXX_STR("Exception will initializing RollingFileAppender named ")) + getName()); } } } void MultiprocessRollingFileAppender::releaseFileLock(apr_file_t* lock_file) { if (lock_file) { apr_status_t stat = apr_file_unlock(lock_file); if (stat != APR_SUCCESS) { LogLog::warn(LOG4CXX_STR("flock: unlock failed")); } apr_file_close(lock_file); lock_file = NULL; } } /** 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. */ bool MultiprocessRollingFileAppender::rollover(Pool& p) { std::lock_guard lock(_priv->mutex); return rolloverInternal(p); } bool MultiprocessRollingFileAppender::rolloverInternal(Pool& p) { // // can't roll without a policy // if (_priv->rollingPolicy != NULL) { { LogString fileName(getFile()); RollingPolicyBasePtr basePolicy = LOG4CXX_NS::cast(_priv->rollingPolicy); apr_time_t n = apr_time_now(); ObjectPtr obj = std::make_shared(n); LogString fileNamePattern; if (basePolicy) { if (basePolicy->getPatternConverterList().size()) { (*(basePolicy->getPatternConverterList().begin()))->format(obj, fileNamePattern, p); fileName = std::string(fileNamePattern); } } bool bAlreadyRolled = true; char szDirName[MAX_FILE_LEN] = {'\0'}; char szBaseName[MAX_FILE_LEN] = {'\0'}; char szUid[MAX_FILE_LEN] = {'\0'}; memcpy(szDirName, fileName.c_str(), fileName.size() > MAX_FILE_LEN ? MAX_FILE_LEN : fileName.size()); memcpy(szBaseName, fileName.c_str(), fileName.size() > MAX_FILE_LEN ? MAX_FILE_LEN : fileName.size()); apr_uid_t uid; apr_gid_t groupid; apr_status_t stat = apr_uid_current(&uid, &groupid, p.getAPRPool()); if (stat == APR_SUCCESS) { #ifdef _WIN32 snprintf(szUid, MAX_FILE_LEN, "%p", uid); #else snprintf(szUid, MAX_FILE_LEN, "%u", (unsigned int)uid); #endif } LOG4CXX_NS::filesystem::path path = szDirName; const auto lockname = path.parent_path() / (path.filename().string() + szUid + ".lock"); apr_file_t* lock_file; stat = apr_file_open(&lock_file, lockname.string().c_str(), APR_CREATE | APR_READ | APR_WRITE, APR_OS_DEFAULT, p.getAPRPool()); if (stat != APR_SUCCESS) { LogString err = LOG4CXX_STR("lockfile return error: open lockfile failed. "); err += (strerror(errno)); LogLog::warn(err); bAlreadyRolled = false; lock_file = NULL; } else { stat = apr_file_lock(lock_file, APR_FLOCK_EXCLUSIVE); if (stat != APR_SUCCESS) { LogString err = LOG4CXX_STR("apr_file_lock: lock failed. "); err += (strerror(errno)); LogLog::warn(err); bAlreadyRolled = false; } else { if (_priv->_event) { _priv->triggeringPolicy->isTriggeringEvent(this, _priv->_event, getFile(), getFileLength()); } } } if (bAlreadyRolled) { apr_finfo_t finfo1, finfo2; apr_status_t st1, st2; const WriterPtr writer = getWriter(); const FileOutputStreamPtr fos = LOG4CXX_NS::cast( writer ); if( !fos ){ LogLog::error( LOG4CXX_STR("Can't cast writer to FileOutputStream") ); return false; } apr_file_t* _fd = fos->getFilePtr(); st1 = apr_file_info_get(&finfo1, APR_FINFO_IDENT, _fd); if (st1 != APR_SUCCESS) { LogLog::warn(LOG4CXX_STR("apr_file_info_get failed")); } LogString fname = getFile(); st2 = apr_stat(&finfo2, fname.c_str(), APR_FINFO_IDENT, p.getAPRPool()); if (st2 != APR_SUCCESS) { LogLog::warn(LOG4CXX_STR("apr_stat failed.")); } bAlreadyRolled = ((st1 == APR_SUCCESS) && (st2 == APR_SUCCESS) && ((finfo1.device != finfo2.device) || (finfo1.inode != finfo2.inode))); } if (!bAlreadyRolled) { try { RolloverDescriptionPtr rollover1(_priv->rollingPolicy->rollover(this->getFile(), this->getAppend(), p)); if (rollover1 != NULL) { if (rollover1->getActiveFileName() == getFile()) { closeWriter(); bool success = true; if (rollover1->getSynchronous() != NULL) { success = false; try { success = rollover1->getSynchronous()->execute(p); } catch (std::exception& ex) { LogString msg(LOG4CXX_STR("Rollover of [")); msg.append(getFile()); msg.append(LOG4CXX_STR("] failed")); _priv->errorHandler->error(msg, ex, 0); } } bool appendToExisting = true; if (success) { appendToExisting = rollover1->getAppend(); if (appendToExisting) { _priv->fileLength = File().setPath(rollover1->getActiveFileName()).length(p); } else { _priv->fileLength = 0; } ActionPtr asyncAction(rollover1->getAsynchronous()); if (asyncAction != NULL) { try { asyncAction->execute(p); } catch (std::exception& ex) { LogString msg(LOG4CXX_STR("Rollover of [")); msg.append(getFile()); msg.append(LOG4CXX_STR("] failed")); _priv->errorHandler->error(msg, ex, 0); } } } setFileInternal(rollover1->getActiveFileName(), appendToExisting, _priv->bufferedIO, _priv->bufferSize, p); } else { closeWriter(); setFileInternal(rollover1->getActiveFileName()); // Call activateOptions to create any intermediate directories(if required) FileAppender::activateOptionsInternal(p); OutputStreamPtr os(new FileOutputStream( rollover1->getActiveFileName(), rollover1->getAppend())); WriterPtr newWriter(createWriter(os)); setWriterInternal(newWriter); bool success = true; if (rollover1->getSynchronous() != NULL) { success = false; try { success = rollover1->getSynchronous()->execute(p); } catch (std::exception& ex) { LogString msg(LOG4CXX_STR("Rollover of [")); msg.append(getFile()); msg.append(LOG4CXX_STR("] failed")); _priv->errorHandler->error(msg, ex, 0); } } if (success) { if (rollover1->getAppend()) { _priv->fileLength = File().setPath(rollover1->getActiveFileName()).length(p); } else { _priv->fileLength = 0; } // // async action not yet implemented // ActionPtr asyncAction(rollover1->getAsynchronous()); if (asyncAction != NULL) { asyncAction->execute(p); } } writeHeader(p); } releaseFileLock(lock_file); return true; } } catch (std::exception& ex) { LogString msg(LOG4CXX_STR("Rollover of [")); msg.append(getFile()); msg.append(LOG4CXX_STR("] failed")); _priv->errorHandler->error(msg, ex, 0); } } else { reopenLatestFile(p); } releaseFileLock(lock_file); } } return false; } /** * re-open current file when its own handler has been renamed */ void MultiprocessRollingFileAppender::reopenLatestFile(Pool& p) { closeWriter(); OutputStreamPtr os = std::make_shared(getFile(), true); WriterPtr newWriter(createWriter(os)); setFile(getFile()); setWriter(newWriter); _priv->fileLength = File().setPath(getFile()).length(p); writeHeader(p); } /** * {@inheritDoc} */ void MultiprocessRollingFileAppender::subAppend(const LoggingEventPtr& event, Pool& p) { // The rollover check must precede actual writing. This is the // only correct behavior for time driven triggers. if ( _priv->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 { _priv->_event = event; rolloverInternal(p); } catch (std::exception& ex) { LogString msg(LOG4CXX_STR("Rollover of [")); msg.append(getFile()); msg.append(LOG4CXX_STR("] failed")); _priv->errorHandler->error(msg, ex, 0); } } //do re-check before every write // apr_finfo_t finfo1, finfo2; apr_status_t st1, st2; const WriterPtr writer = getWriter(); const FileOutputStreamPtr fos = LOG4CXX_NS::cast( writer ); if( !fos ){ LogLog::error( LOG4CXX_STR("Can't cast writer to FileOutputStream") ); return; } apr_file_t* _fd = fos->getFilePtr(); st1 = apr_file_info_get(&finfo1, APR_FINFO_IDENT, _fd); if (st1 != APR_SUCCESS) { LogLog::warn(LOG4CXX_STR("apr_file_info_get failed")); } st2 = apr_stat(&finfo2, std::string(getFile()).c_str(), APR_FINFO_IDENT, p.getAPRPool()); if (st2 != APR_SUCCESS) { LogString err = "apr_stat failed. file:" + getFile(); LogLog::warn(err); } bool bAlreadyRolled = ((st1 == APR_SUCCESS) && (st2 == APR_SUCCESS) && ((finfo1.device != finfo2.device) || (finfo1.inode != finfo2.inode))); if (bAlreadyRolled) { reopenLatestFile(p); } FileAppender::subAppend(event, p); } /** * Get rolling policy. * @return rolling policy. */ RollingPolicyPtr MultiprocessRollingFileAppender::getRollingPolicy() const { return _priv->rollingPolicy; } /** * Get triggering policy. * @return triggering policy. */ TriggeringPolicyPtr MultiprocessRollingFileAppender::getTriggeringPolicy() const { return _priv->triggeringPolicy; } /** * Sets the rolling policy. * @param policy rolling policy. */ void MultiprocessRollingFileAppender::setRollingPolicy(const RollingPolicyPtr& policy) { _priv->rollingPolicy = policy; TimeBasedRollingPolicyPtr timeBased = LOG4CXX_NS::cast(policy); if( timeBased ){ timeBased->setMultiprocess(true); } } /** * Set triggering policy. * @param policy triggering policy. */ void MultiprocessRollingFileAppender::setTriggeringPolicy(const TriggeringPolicyPtr& policy) { _priv->triggeringPolicy = policy; } /** * Close appender. Waits for any asynchronous file compression actions to be completed. */ void MultiprocessRollingFileAppender::close() { FileAppender::close(); } namespace LOG4CXX_NS { namespace rolling { /** * Wrapper for OutputStream that will report all write * operations back to this class for file length calculations. */ class CountingOutputStream : public OutputStream { /** * Wrapped output stream. */ private: OutputStreamPtr os; /** * Rolling file appender to inform of stream writes. */ MultiprocessRollingFileAppender* rfa; public: /** * Constructor. * @param os output stream to wrap. * @param rfa rolling file appender to inform. */ CountingOutputStream( OutputStreamPtr& os1, MultiprocessRollingFileAppender* rfa1) : os(os1), rfa(rfa1) { } /** * {@inheritDoc} */ void close(Pool& p) { os->close(p); rfa = 0; } /** * {@inheritDoc} */ void flush(Pool& p) { os->flush(p); } /** * {@inheritDoc} */ void write(ByteBuffer& buf, Pool& p) { os->write(buf, p); if (rfa != 0) { rfa->setFileLength(File().setPath(rfa->getFile()).length(p)); } } OutputStream& getFileOutPutStreamPtr() { return *os; } }; } } /** 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. */ WriterPtr MultiprocessRollingFileAppender::createWriter(OutputStreamPtr& os) { OutputStreamPtr cos = std::make_shared(os, this); return FileAppender::createWriter(cos); } /** * Get byte length of current active log file. * @return byte length of current active log file. */ size_t MultiprocessRollingFileAppender::getFileLength() const { return _priv->fileLength; } void MultiprocessRollingFileAppender::setFileLength(size_t length) { _priv->fileLength = length; } /** * Increments estimated byte length of current active log file. * @param increment additional bytes written to log file. */ void MultiprocessRollingFileAppender::incrementFileLength(size_t increment) { _priv->fileLength += increment; } apache-log4cxx-1.3.1/src/main/cpp/level.cpp0000644000175100001770000001454414721727031020014 0ustar runnerdocker/* * 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. */ #include #include #include #include #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT_WITH_CUSTOM_CLASS(Level, LevelClass) LevelPtr Level::getOff() { static WideLife offLevel = std::make_shared(Level::OFF_INT, LOG4CXX_STR("OFF"), 0); return offLevel; } LevelPtr Level::getFatal() { static WideLife fatalLevel = std::make_shared(Level::FATAL_INT, LOG4CXX_STR("FATAL"), 0); return fatalLevel; } LevelPtr Level::getError() { static WideLife errorLevel = std::make_shared(Level::ERROR_INT, LOG4CXX_STR("ERROR"), 3); return errorLevel; } LevelPtr Level::getWarn() { static WideLife warnLevel = std::make_shared(Level::WARN_INT, LOG4CXX_STR("WARN"), 4); return warnLevel; } LevelPtr Level::getInfo() { static WideLife infoLevel = std::make_shared(Level::INFO_INT, LOG4CXX_STR("INFO"), 6); return infoLevel; } LevelPtr Level::getDebug() { static WideLife debugLevel = std::make_shared(Level::DEBUG_INT, LOG4CXX_STR("DEBUG"), 7); return debugLevel; } LevelPtr Level::getTrace() { static WideLife traceLevel = std::make_shared(Level::TRACE_INT, LOG4CXX_STR("TRACE"), 7); return traceLevel; } LevelPtr Level::getAll() { static WideLife allLevel = std::make_shared(Level::ALL_INT, LOG4CXX_STR("ALL"), 7); return allLevel; } Level::Level(int level1, const LogString& name1, int syslogEquivalent1) : level(level1), name(name1), syslogEquivalent(syslogEquivalent1) { } LevelPtr Level::toLevelLS(const LogString& sArg) { return toLevelLS(sArg, Level::getDebug()); } LogString Level::toString() const { return name; } LevelPtr Level::toLevel(int val) { return toLevel(val, Level::getDebug()); } const Level::DataPtr& Level::getData() { static WideLife data = std::make_shared(Data { getOff() , getFatal() , getError() , getWarn() , getInfo() , getDebug() , getTrace() , getAll() }); return data; } LevelPtr Level::toLevel(int val, const LevelPtr& defaultLevel) { switch (val) { case ALL_INT: return getAll(); case DEBUG_INT: return getDebug(); case TRACE_INT: return getTrace(); case INFO_INT: return getInfo(); case WARN_INT: return getWarn(); case ERROR_INT: return getError(); case FATAL_INT: return getFatal(); case OFF_INT: return getOff(); default: return defaultLevel; } } LevelPtr Level::toLevel(const std::string& sArg) { return toLevel(sArg, Level::getDebug()); } LevelPtr Level::toLevel(const std::string& sArg, const LevelPtr& defaultLevel) { LOG4CXX_DECODE_CHAR(s, sArg); return toLevelLS(s, defaultLevel); } void Level::toString(std::string& dst) const { Transcoder::encode(name, dst); } #if LOG4CXX_WCHAR_T_API LevelPtr Level::toLevel(const std::wstring& sArg) { return toLevel(sArg, Level::getDebug()); } LevelPtr Level::toLevel(const std::wstring& sArg, const LevelPtr& defaultLevel) { LOG4CXX_DECODE_WCHAR(s, sArg); return toLevelLS(s, defaultLevel); } void Level::toString(std::wstring& dst) const { Transcoder::encode(name, dst); } #endif #if LOG4CXX_UNICHAR_API || LOG4CXX_LOGCHAR_IS_UNICHAR LevelPtr Level::toLevel(const std::basic_string& sArg) { return toLevel(sArg, Level::getDebug()); } LevelPtr Level::toLevel(const std::basic_string& sArg, const LevelPtr& defaultLevel) { LOG4CXX_DECODE_UNICHAR(s, sArg); return toLevelLS(s, defaultLevel); } void Level::toString(std::basic_string& dst) const { Transcoder::encode(name, dst); } #endif #if LOG4CXX_CFSTRING_API LevelPtr Level::toLevel(const CFStringRef& sArg) { return toLevel(sArg, Level::getDebug()); } LevelPtr Level::toLevel(const CFStringRef& sArg, const LevelPtr& defaultLevel) { LogString s; Transcoder::decode(sArg, s); return toLevelLS(s, defaultLevel); } void Level::toString(CFStringRef& dst) const { dst = Transcoder::encode(name); } #endif LevelPtr Level::toLevelLS(const LogString& sArg, const LevelPtr& defaultLevel) { const LogString trimmed(StringHelper::trim(sArg)); const size_t len = trimmed.length(); if (len == 4) { if (StringHelper::equalsIgnoreCase(trimmed, LOG4CXX_STR("INFO"), LOG4CXX_STR("info"))) { return getInfo(); } if (StringHelper::equalsIgnoreCase(trimmed, LOG4CXX_STR("WARN"), LOG4CXX_STR("warn"))) { return getWarn(); } } else { if (len == 5) { if (StringHelper::equalsIgnoreCase(trimmed, LOG4CXX_STR("DEBUG"), LOG4CXX_STR("debug"))) { return getDebug(); } if (StringHelper::equalsIgnoreCase(trimmed, LOG4CXX_STR("TRACE"), LOG4CXX_STR("trace"))) { return getTrace(); } if (StringHelper::equalsIgnoreCase(trimmed, LOG4CXX_STR("ERROR"), LOG4CXX_STR("error"))) { return getError(); } if (StringHelper::equalsIgnoreCase(trimmed, LOG4CXX_STR("FATAL"), LOG4CXX_STR("fatal"))) { return getFatal(); } } else { if (len == 3) { if (StringHelper::equalsIgnoreCase(trimmed, LOG4CXX_STR("OFF"), LOG4CXX_STR("off"))) { return getOff(); } if (StringHelper::equalsIgnoreCase(trimmed, LOG4CXX_STR("ALL"), LOG4CXX_STR("all"))) { return getAll(); } } } } return defaultLevel; } bool Level::equals(const LevelPtr& level1) const { return level1 && this->level == level1->level; } bool Level::isGreaterOrEqual(const LevelPtr& level1) const { return level1 && this->level >= level1->level; } apache-log4cxx-1.3.1/src/main/cpp/stringhelper.cpp0000644000175100001770000001031314721727031021401 0ustar runnerdocker/* * 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. */ #define __STDC_CONSTANT_MACROS #include #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; bool StringHelper::equalsIgnoreCase(const LogString& s1, const logchar* upper, const logchar* lower) { for (LogString::const_iterator iter = s1.begin(); iter != s1.end(); iter++, upper++, lower++) { if (*iter != *upper && *iter != * lower) { return false; } } return (*upper == 0); } bool StringHelper::equalsIgnoreCase(const LogString& s1, const LogString& upper, const LogString& lower) { LogString::const_iterator u = upper.begin(); LogString::const_iterator l = lower.begin(); LogString::const_iterator iter = s1.begin(); for (; iter != s1.end() && u != upper.end() && l != lower.end(); iter++, u++, l++) { if (*iter != *u && *iter != *l) { return false; } } return u == upper.end() && iter == s1.end(); } LogString StringHelper::toLowerCase(const LogString& s) { LogString d; std::transform(s.begin(), s.end(), std::insert_iterator(d, d.begin()), tolower); return d; } LogString StringHelper::trim(const LogString& s) { LogString::size_type pos = s.find_first_not_of(' '); if (pos == std::string::npos) { return LogString(); } LogString::size_type n = s.find_last_not_of(' ') - pos + 1; return s.substr(pos, n); } bool StringHelper::startsWith(const LogString& s, const LogString& prefix) { if (s.length() < prefix.length()) { return false; } return s.compare(0, prefix.length(), prefix) == 0; } bool StringHelper::endsWith(const LogString& s, const LogString& suffix) { if (suffix.length() <= s.length()) { return s.compare(s.length() - suffix.length(), suffix.length(), suffix) == 0; } return false; } int StringHelper::toInt(const LogString& s) { #if LOG4CXX_LOGCHAR_IS_UNICHAR std::string as; Transcoder::encode(s, as); return std::stoi(as); #else return std::stoi(s); #endif } int64_t StringHelper::toInt64(const LogString& s) { #if LOG4CXX_LOGCHAR_IS_UNICHAR std::string as; Transcoder::encode(s, as); return std::stoll(as); #else return std::stoll(s); #endif } void StringHelper::toString(int n, Pool& pool, LogString& dst) { #if LOG4CXX_LOGCHAR_IS_WCHAR dst.append(std::to_wstring(n)); #else Transcoder::decode(std::to_string(n), dst); #endif } void StringHelper::toString(bool val, LogString& dst) { if (val) { dst.append(LOG4CXX_STR("true")); } else { dst.append(LOG4CXX_STR("false")); } } void StringHelper::toString(int64_t n, Pool& pool, LogString& dst) { #if LOG4CXX_LOGCHAR_IS_WCHAR dst.append(std::to_wstring(n)); #else Transcoder::decode(std::to_string(n), dst); #endif } void StringHelper::toString(size_t n, Pool& pool, LogString& dst) { #if LOG4CXX_LOGCHAR_IS_WCHAR dst.append(std::to_wstring(n)); #else Transcoder::decode(std::to_string(n), dst); #endif } LogString StringHelper::format(const LogString& pattern, const std::vector& params) { LogString result; int i = 0; while (pattern[i] != 0) { if (pattern[i] == 0x7B /* '{' */ && pattern[i + 1] >= 0x30 /* '0' */ && pattern[i + 1] <= 0x39 /* '9' */ && pattern[i + 2] == 0x7D /* '}' */) { int arg = pattern[i + 1] - 0x30 /* '0' */; result = result + params[arg]; i += 3; } else { result = result + pattern[i]; i++; } } return result; } apache-log4cxx-1.3.1/src/main/cpp/stringtokenizer.cpp0000644000175100001770000000417414721727031022144 0ustar runnerdocker/* * 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. */ #include #include #include #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; struct StringTokenizer::StringTokenizerPrivate{ StringTokenizerPrivate(const LogString& str, const LogString& delim1) : src(str), delim(delim1), pos(0){} LogString src; LogString delim; size_t pos; }; StringTokenizer::StringTokenizer(const LogString& str, const LogString& delim1) : m_priv(std::make_unique(str, delim1)) { } StringTokenizer::~StringTokenizer() { } bool StringTokenizer::hasMoreTokens() const { return (m_priv->pos != LogString::npos && m_priv->src.find_first_not_of(m_priv->delim, m_priv->pos) != LogString::npos); } LogString StringTokenizer::nextToken() { if (m_priv->pos != LogString::npos) { size_t nextPos = m_priv->src.find_first_not_of(m_priv->delim, m_priv->pos); if (nextPos != LogString::npos) { m_priv->pos = m_priv->src.find_first_of(m_priv->delim, nextPos); if (m_priv->pos == LogString::npos) { return m_priv->src.substr(nextPos); } return m_priv->src.substr(nextPos, m_priv->pos - nextPos); } } throw NoSuchElementException(); #if LOG4CXX_RETURN_AFTER_THROW return LogString(); #endif } apache-log4cxx-1.3.1/src/main/cpp/patternconverter.cpp0000644000175100001770000000331214721727031022301 0ustar runnerdocker/* * 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. */ #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::pattern; IMPLEMENT_LOG4CXX_OBJECT(PatternConverter) PatternConverter::PatternConverter( std::unique_ptr priv) : m_priv(std::move(priv)) { } PatternConverter::PatternConverter(const LogString& name, const LogString& style) : m_priv(std::make_unique(name, style)) { } PatternConverter::~PatternConverter() { } LogString PatternConverter::getName() const { return m_priv->name; } LogString PatternConverter::getStyleClass(const LOG4CXX_NS::helpers::ObjectPtr& /* e */) const { return m_priv->style; } void PatternConverter::append(LogString& toAppendTo, const std::string& src) { LOG4CXX_DECODE_CHAR(decoded, src); toAppendTo.append(decoded); } apache-log4cxx-1.3.1/src/main/cpp/fileoutputstream.cpp0000644000175100001770000000622514721727031022316 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; struct FileOutputStream::FileOutputStreamPrivate { FileOutputStreamPrivate() : fileptr(nullptr) {} Pool pool; apr_file_t* fileptr; }; IMPLEMENT_LOG4CXX_OBJECT(FileOutputStream) FileOutputStream::FileOutputStream(const LogString& filename, bool append) : m_priv(std::make_unique()) { m_priv->fileptr = open(filename, append, m_priv->pool); } FileOutputStream::FileOutputStream(const logchar* filename, bool append) : m_priv(std::make_unique()) { m_priv->fileptr = open(filename, append, m_priv->pool); } apr_file_t* FileOutputStream::open(const LogString& filename, bool append, Pool& pool) { apr_fileperms_t perm = APR_OS_DEFAULT; apr_int32_t flags = APR_WRITE | APR_CREATE; if (append) { flags |= APR_APPEND; } else { flags |= APR_TRUNCATE; } File fn; fn.setPath(filename); apr_file_t* fileptr = 0; apr_status_t stat = fn.open(&fileptr, flags, perm, pool); if (stat != APR_SUCCESS) { throw IOException(filename, stat); } return fileptr; } FileOutputStream::~FileOutputStream() { if (m_priv->fileptr != NULL && !APRInitializer::isDestructed) { apr_file_close(m_priv->fileptr); } } void FileOutputStream::close(Pool& /* p */) { if (m_priv->fileptr != NULL) { apr_status_t stat = apr_file_close(m_priv->fileptr); if (stat != APR_SUCCESS) { throw IOException(stat); } m_priv->fileptr = NULL; } } void FileOutputStream::flush(Pool& /* p */) { } void FileOutputStream::write(ByteBuffer& buf, Pool& /* p */ ) { if (m_priv->fileptr == NULL) { throw NullPointerException(LOG4CXX_STR("FileOutputStream")); } size_t nbytes = buf.remaining(); size_t pos = buf.position(); const char* data = buf.data(); while (nbytes > 0) { apr_status_t stat = apr_file_write( m_priv->fileptr, data + pos, &nbytes); if (stat != APR_SUCCESS) { throw IOException(stat); } pos += nbytes; buf.position(pos); nbytes = buf.remaining(); } } apr_file_t* FileOutputStream::getFilePtr() const{ return m_priv->fileptr; } apache-log4cxx-1.3.1/src/main/cpp/telnetappender.cpp0000644000175100001770000002034114721727031021707 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #include #include #include #include #if LOG4CXX_EVENTS_AT_EXIT #include #endif using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; using namespace LOG4CXX_NS::net; typedef helpers::SocketPtr Connection; LOG4CXX_LIST_DEF(ConnectionList, Connection); IMPLEMENT_LOG4CXX_OBJECT(TelnetAppender) struct TelnetAppender::TelnetAppenderPriv : public AppenderSkeletonPrivate { TelnetAppenderPriv( int port, int maxConnections ) : AppenderSkeletonPrivate(), port(port), connections(maxConnections), encoding(LOG4CXX_STR("UTF-8")), encoder(CharsetEncoder::getUTF8Encoder()), activeConnections(0) #if LOG4CXX_EVENTS_AT_EXIT , atExitRegistryRaii([this]{stopAcceptingConnections();}) #endif { } ~TelnetAppenderPriv() { stopAcceptingConnections(); } int port; ConnectionList connections; LogString encoding; LOG4CXX_NS::helpers::CharsetEncoderPtr encoder; std::unique_ptr serverSocket; std::thread sh; size_t activeConnections; #if LOG4CXX_EVENTS_AT_EXIT helpers::AtExitRegistry::Raii atExitRegistryRaii; #endif void stopAcceptingConnections() { { std::lock_guard lock(this->mutex); if (!this->serverSocket || this->closed) return; this->closed = true; } // Interrupt accept() try { this->serverSocket->close(); } catch (Exception&) { } if (this->sh.joinable()) this->sh.join(); } }; #define _priv static_cast(m_priv.get()) /** The default telnet server port */ const int TelnetAppender::DEFAULT_PORT = 23; /** The maximum number of concurrent connections */ const int TelnetAppender::MAX_CONNECTIONS = 20; TelnetAppender::TelnetAppender() : AppenderSkeleton (std::make_unique(DEFAULT_PORT, MAX_CONNECTIONS)) { } TelnetAppender::~TelnetAppender() { finalize(); } void TelnetAppender::activateOptions(Pool& /* p */) { if (_priv->serverSocket == NULL) { _priv->serverSocket = ServerSocket::create(_priv->port); _priv->serverSocket->setSoTimeout(1000); } if (!_priv->sh.joinable()) _priv->sh = ThreadUtility::instance()->createThread( LOG4CXX_STR("TelnetAppender"), &TelnetAppender::acceptConnections, this ); } void TelnetAppender::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("PORT"), LOG4CXX_STR("port"))) { setPort(OptionConverter::toInt(value, DEFAULT_PORT)); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("MAXCONNECTIONS"), LOG4CXX_STR("maxconnections"))) { setMaxConnections(OptionConverter::toInt(value, MAX_CONNECTIONS)); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("ENCODING"), LOG4CXX_STR("encoding"))) { setEncoding(value); } else { AppenderSkeleton::setOption(option, value); } } LogString TelnetAppender::getEncoding() const { std::lock_guard lock(_priv->mutex); return _priv->encoding; } void TelnetAppender::setEncoding(const LogString& value) { std::lock_guard lock(_priv->mutex); _priv->encoder = CharsetEncoder::getEncoder(value); _priv->encoding = value; } void TelnetAppender::close() { _priv->stopAcceptingConnections(); std::lock_guard lock(_priv->mutex); SocketPtr nullSocket; for (auto& item : _priv->connections) { if (item) { item->close(); item = nullSocket; } } _priv->activeConnections = 0; } void TelnetAppender::write(ByteBuffer& buf) { for (auto& item :_priv->connections) { if (item) { try { ByteBuffer b(buf.current(), buf.remaining()); item->write(b); } catch (Exception&) { // The client has closed the connection, remove it from our list: item.reset(); _priv->activeConnections--; } } } } void TelnetAppender::writeStatus(const SocketPtr& socket, const LogString& msg, Pool& p) { size_t bytesSize = msg.size() * 2; char* bytes = p.pstralloc(bytesSize); LogString::const_iterator msgIter(msg.begin()); ByteBuffer buf(bytes, bytesSize); while (msgIter != msg.end()) { _priv->encoder->encode(msg, msgIter, buf); buf.flip(); socket->write(buf); buf.clear(); } } void TelnetAppender::append(const spi::LoggingEventPtr& event, Pool& p) { size_t count = _priv->activeConnections; if (count > 0) { LogString msg; if (_priv->layout) _priv->layout->format(msg, event, p); else msg = event->getMessage(); msg.append(LOG4CXX_STR("\r\n")); size_t bytesSize = msg.size() * 2; char* bytes = p.pstralloc(bytesSize); LogString::const_iterator msgIter(msg.begin()); ByteBuffer buf(bytes, bytesSize); std::lock_guard lock(_priv->mutex); while (msgIter != msg.end()) { log4cxx_status_t stat = _priv->encoder->encode(msg, msgIter, buf); buf.flip(); write(buf); buf.clear(); if (CharsetEncoder::isError(stat)) { LogString unrepresented(1, 0x3F /* '?' */); LogString::const_iterator unrepresentedIter(unrepresented.begin()); stat = _priv->encoder->encode(unrepresented, unrepresentedIter, buf); buf.flip(); write(buf); buf.clear(); msgIter++; } } } } void TelnetAppender::acceptConnections() { // main loop; is left when This->closed is != 0 after an accept() while (true) { try { SocketPtr newClient = _priv->serverSocket->accept(); bool done = _priv->closed; if (done) { Pool p; writeStatus(newClient, LOG4CXX_STR("Log closed.\r\n"), p); newClient->close(); break; } size_t count = _priv->activeConnections; if (count >= _priv->connections.size()) { Pool p; writeStatus(newClient, LOG4CXX_STR("Too many connections.\r\n"), p); newClient->close(); } else { // // find unoccupied connection // std::lock_guard lock(_priv->mutex); for (auto& item : _priv->connections) { if (!item) { item = newClient; _priv->activeConnections++; break; } } Pool p; LogString oss(LOG4CXX_STR("TelnetAppender v1.0 (")); StringHelper::toString((int) count + 1, p, oss); oss += LOG4CXX_STR(" active connections)\r\n\r\n"); writeStatus(newClient, oss, p); } } catch (InterruptedIOException&) { if (_priv->closed) { break; } } catch (Exception& e) { if (!_priv->closed) { LogLog::error(LOG4CXX_STR("Encountered error while in SocketHandler loop."), e); } else { break; } } } } int TelnetAppender::getPort() const { return _priv->port; } void TelnetAppender::setPort(int port1) { _priv->port = port1; } int TelnetAppender::getMaxConnections() const { return static_cast(_priv->connections.size()); } void TelnetAppender::setMaxConnections(int newValue) { std::lock_guard lock(_priv->mutex); if (_priv->connections.size() < newValue) _priv->connections.resize(newValue); else while (newValue < _priv->connections.size()) { auto item = _priv->connections.back(); _priv->connections.pop_back(); if (item) { item->close(); --_priv->activeConnections; } } } bool TelnetAppender::requiresLayout() const { return false; } apache-log4cxx-1.3.1/src/main/cpp/triggeringpolicy.cpp0000644000175100001770000000202014721727031022250 0ustar runnerdocker/* * 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. */ #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::rolling; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(TriggeringPolicy) TriggeringPolicy::~TriggeringPolicy() { } apache-log4cxx-1.3.1/src/main/cpp/gzcompressaction.cpp0000644000175100001770000001102114721727031022262 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::rolling; using namespace LOG4CXX_NS::helpers; #define priv static_cast(m_priv.get()) struct GZCompressAction::GZCompressActionPrivate : public ActionPrivate { GZCompressActionPrivate( const File& toRename, const File& renameTo, bool deleteSource): source(toRename), destination(renameTo), deleteSource(deleteSource) {} const File source; File destination; bool deleteSource; bool throwIOExceptionOnForkFailure = true; }; IMPLEMENT_LOG4CXX_OBJECT(GZCompressAction) GZCompressAction::GZCompressAction(const File& src, const File& dest, bool del) : Action(std::make_unique( src, dest, del)) { } GZCompressAction::~GZCompressAction() {} bool GZCompressAction::execute(LOG4CXX_NS::helpers::Pool& p) const { if (priv->source.exists(p)) { apr_pool_t* aprpool = p.getAPRPool(); apr_procattr_t* attr; apr_status_t stat = apr_procattr_create(&attr, aprpool); if (stat != APR_SUCCESS) { throw IOException(stat); } stat = apr_procattr_io_set(attr, APR_NO_PIPE, APR_FULL_BLOCK, APR_FULL_BLOCK); if (stat != APR_SUCCESS) { throw IOException(stat); } stat = apr_procattr_cmdtype_set(attr, APR_PROGRAM_PATH); if (stat != APR_SUCCESS) { throw IOException(stat); } // // set child process output to destination file // apr_file_t* child_out; apr_int32_t flags = APR_FOPEN_READ | APR_FOPEN_WRITE | APR_FOPEN_CREATE | APR_FOPEN_TRUNCATE; stat = priv->destination.open(&child_out, flags, APR_OS_DEFAULT, p); if (stat != APR_SUCCESS) { throw IOException(priv->destination.getName(), stat); } stat = apr_procattr_child_out_set(attr, child_out, NULL); if (stat != APR_SUCCESS) { throw IOException(stat); } // // redirect the child's error stream to this processes' error stream // apr_file_t* child_err; stat = apr_file_open_stderr(&child_err, aprpool); if (stat == APR_SUCCESS) { stat = apr_procattr_child_err_set(attr, child_err, NULL); if (stat != APR_SUCCESS) { throw IOException(stat); } } priv->destination.setAutoDelete(true); const char** args = (const char**) apr_palloc(aprpool, 4 * sizeof(*args)); int i = 0; args[i++] = "gzip"; args[i++] = "-c"; args[i++] = Transcoder::encode(priv->source.getPath(), p); args[i++] = NULL; apr_proc_t pid; stat = apr_proc_create(&pid, "gzip", args, NULL, attr, aprpool); if (stat != APR_SUCCESS) { LogLog::warn(LOG4CXX_STR("Failed to fork gzip during log rotation; leaving log file uncompressed")); if (priv->throwIOExceptionOnForkFailure) throw IOException(LOG4CXX_STR("gzip"), stat); /* If we fail here (to create the gzip child process), * skip the compression and consider the rotation to be * otherwise successful. The caller has already rotated * the log file (`source` here refers to the * uncompressed, rotated path, and `destination` the * same path with `.gz` appended). Remove the empty * destination file and leave source as-is. */ stat = apr_file_close(child_out); return true; } apr_proc_wait(&pid, NULL, NULL, APR_WAIT); stat = apr_file_close(child_out); if (stat != APR_SUCCESS) { throw IOException(stat); } priv->destination.setAutoDelete(false); if (priv->deleteSource) { priv->source.deleteFile(p); } return true; } return false; } void GZCompressAction::setThrowIOExceptionOnForkFailure(bool throwIO){ priv->throwIOExceptionOnForkFailure = throwIO; } apache-log4cxx-1.3.1/src/main/cpp/bytearrayinputstream.cpp0000644000175100001770000000365514721727031023204 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; using namespace std; struct ByteArrayInputStream::ByteArrayInputStreamPriv { ByteArrayInputStreamPriv(const ByteList& bytes) : buf(bytes), pos(0) {} ByteList buf; size_t pos; }; IMPLEMENT_LOG4CXX_OBJECT(ByteArrayInputStream) ByteArrayInputStream::ByteArrayInputStream(const std::vector& bytes) : m_priv(std::make_unique(bytes)) { } ByteArrayInputStream::~ByteArrayInputStream() { } void ByteArrayInputStream::close() { } int ByteArrayInputStream::read(ByteBuffer& dst) { if (m_priv->pos >= m_priv->buf.size()) { return -1; } else { size_t bytesCopied = min(dst.remaining(), m_priv->buf.size() - m_priv->pos); std::memcpy(dst.current(), &m_priv->buf[m_priv->pos], bytesCopied); m_priv->pos += bytesCopied; dst.position(dst.position() + bytesCopied); return (int)bytesCopied; } } apache-log4cxx-1.3.1/src/main/cpp/hexdump.cpp0000644000175100001770000000654214721727031020356 0ustar runnerdocker/* * 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. */ #include /* Prevent error C2491: 'std::numpunct<_Elem>::id': definition of dllimport static data member not allowed */ #if defined(_MSC_VER) && (LOG4CXX_UNICHAR_API || LOG4CXX_LOGCHAR_IS_UNICHAR) #define __FORCE_INSTANCE #endif #include #include #include #include #include #include using namespace LOG4CXX_NS; typedef std::basic_stringstream LogStream; LogString LOG4CXX_NS::hexdump(const void* bytes, uint32_t len, HexdumpFlags flags){ LogString ret; const uint8_t* bytes_u8 = static_cast(bytes); LogStream sstream; #if LOG4CXX_LOGCHAR_IS_WCHAR const wchar_t fill_char = L'0'; const wchar_t space_fill_char = L' '; #else const logchar fill_char = '0'; const logchar space_fill_char = ' '; #endif if(flags & HexdumpFlags::AddStartingNewline){ sstream << LOG4CXX_EOL; } for(uint32_t offset = 0; offset < len; offset += 16){ if(offset != 0){ sstream << LOG4CXX_EOL; } // Print out the offset sstream << std::hex << std::setw(8) << std::setfill(fill_char) << offset << std::resetiosflags(std::ios_base::fmtflags(0)); sstream << std::setw(0) << LOG4CXX_STR(" "); // Print out the first 8 bytes for(int byte = 0; byte < 8; byte++){ if(offset + byte >= len){ sstream << LOG4CXX_STR(" "); if(byte != 8){ sstream << LOG4CXX_STR(" "); } continue; } sstream << std::hex << std::setw(2) << std::setfill(fill_char) << static_cast(bytes_u8[offset + byte]) << std::resetiosflags(std::ios_base::fmtflags(0)); sstream << std::setfill(space_fill_char); if(byte != 8){ sstream << LOG4CXX_STR(" "); } } sstream << LOG4CXX_STR(" "); // Print out the last 8 bytes for(int byte = 8; byte < 16; byte++){ if(offset + byte >= len){ sstream << LOG4CXX_STR(" "); if(byte != 15){ sstream << LOG4CXX_STR(" "); } continue; } sstream << std::hex << std::setw(2) << std::setfill(fill_char) << static_cast(bytes_u8[offset + byte]) << std::resetiosflags(std::ios_base::fmtflags(0)); if(byte != 15){ sstream << LOG4CXX_STR(" "); } } // Print out the ASCII text sstream << LOG4CXX_STR(" |"); for(int byte = 0; byte < 16; byte++){ if(offset + byte >= len){ break; } if(std::isprint(bytes_u8[offset + byte])){ logchar to_append = bytes_u8[offset + byte]; sstream << to_append; }else{ sstream << LOG4CXX_STR("."); } } sstream << LOG4CXX_STR("|"); } if(flags & HexdumpFlags::AddEndingNewline){ sstream << LOG4CXX_EOL; } return sstream.str(); } apache-log4cxx-1.3.1/src/main/cpp/andfilter.cpp0000644000175100001770000000435114721727031020650 0ustar runnerdocker/* * 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. */ #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::filter; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; #define priv static_cast(m_priv.get()) struct AndFilter::AndFilterPrivate : public FilterPrivate { AndFilterPrivate() : FilterPrivate(), headFilter(), tailFilter(), acceptOnMatch(true) {} LOG4CXX_NS::spi::FilterPtr headFilter; LOG4CXX_NS::spi::FilterPtr tailFilter; bool acceptOnMatch; }; IMPLEMENT_LOG4CXX_OBJECT(AndFilter) AndFilter::AndFilter() : Filter( std::make_unique() ) { } AndFilter::~AndFilter() {} void AndFilter::addFilter(const FilterPtr& filter) { if (priv->headFilter == NULL) { priv->headFilter = filter; priv->tailFilter = filter; } else { priv->tailFilter->setNext(filter); } } void AndFilter::setAcceptOnMatch(bool newValue) { priv->acceptOnMatch = newValue; } Filter::FilterDecision AndFilter::decide( const spi::LoggingEventPtr& event) const { bool accepted = true; FilterPtr f(priv->headFilter); while (f != NULL) { accepted = accepted && (Filter::ACCEPT == f->decide(event)); f = f->getNext(); } if (accepted) { if (priv->acceptOnMatch) { return Filter::ACCEPT; } return Filter::DENY; } return Filter::NEUTRAL; } apache-log4cxx-1.3.1/src/main/cpp/classnamepatternconverter.cpp0000644000175100001770000000362714721727031024201 0ustar runnerdocker/* * 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. */ #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::pattern; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(ClassNamePatternConverter) ClassNamePatternConverter::ClassNamePatternConverter( const std::vector& options) : NamePatternConverter(LOG4CXX_STR("Class Name"), LOG4CXX_STR("class name"), options) { } PatternConverterPtr ClassNamePatternConverter::newInstance( const std::vector& options) { if (options.size() == 0) { static WideLife def = std::make_shared(options); return def; } return std::make_shared(options); } void ClassNamePatternConverter::format( const LoggingEventPtr& event, LogString& toAppendTo, Pool& /* p */) const { int initialLength = (int)toAppendTo.length(); append(toAppendTo, event->getLocationInformation().getClassName()); abbreviate(initialLength, toAppendTo); } apache-log4cxx-1.3.1/src/main/cpp/filterbasedtriggeringpolicy.cpp0000644000175100001770000000601114721727031024461 0ustar runnerdocker/* * 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. */ #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::rolling; using namespace LOG4CXX_NS::spi; IMPLEMENT_LOG4CXX_OBJECT(FilterBasedTriggeringPolicy) struct FilterBasedTriggeringPolicy::FilterBasedTriggeringPolicyPrivate{ /** * The first filter in the filter chain. Set to null initially. */ LOG4CXX_NS::spi::FilterPtr headFilter; /** * The last filter in the filter chain. */ LOG4CXX_NS::spi::FilterPtr tailFilter; }; FilterBasedTriggeringPolicy::FilterBasedTriggeringPolicy() : m_priv(std::make_unique()) { } FilterBasedTriggeringPolicy::~FilterBasedTriggeringPolicy() { } bool FilterBasedTriggeringPolicy::isTriggeringEvent( Appender* /* appender */, const LOG4CXX_NS::spi::LoggingEventPtr& event, const LogString& /* filename */, size_t /* fileLength */ ) { if (m_priv->headFilter == NULL) { return false; } for (LOG4CXX_NS::spi::FilterPtr f = m_priv->headFilter; f != NULL; f = f->getNext()) { switch (f->decide(event)) { case Filter::DENY: return false; case Filter::ACCEPT: return true; case Filter::NEUTRAL: break; } } return true; } /** * Add a filter to end of the filter list. * @param newFilter filter to add to end of list. */ void FilterBasedTriggeringPolicy::addFilter(const LOG4CXX_NS::spi::FilterPtr& newFilter) { if (m_priv->headFilter == NULL) { m_priv->headFilter = newFilter; m_priv->tailFilter = newFilter; } else { m_priv->tailFilter->setNext(newFilter); m_priv->tailFilter = newFilter; } } void FilterBasedTriggeringPolicy::clearFilters() { LOG4CXX_NS::spi::FilterPtr empty; m_priv->headFilter = empty; m_priv->tailFilter = empty; } LOG4CXX_NS::spi::FilterPtr& FilterBasedTriggeringPolicy::getFilter() { return m_priv->headFilter; } /** * Prepares the instance for use. */ void FilterBasedTriggeringPolicy::activateOptions(LOG4CXX_NS::helpers::Pool& p) { for (LOG4CXX_NS::spi::FilterPtr f = m_priv->headFilter; f != NULL; f = f->getNext()) { f->activateOptions(p); } } void FilterBasedTriggeringPolicy::setOption(const LogString& /* option */, const LogString& /* value */ ) { } apache-log4cxx-1.3.1/src/main/cpp/xmlsocketappender.cpp0000644000175100001770000001047114721727031022430 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; using namespace LOG4CXX_NS::net; using namespace LOG4CXX_NS::xml; struct XMLSocketAppender::XMLSocketAppenderPriv : public SocketAppenderSkeletonPriv { XMLSocketAppenderPriv(int defaultPort, int reconnectionDelay) : SocketAppenderSkeletonPriv(defaultPort, reconnectionDelay) {} XMLSocketAppenderPriv(InetAddressPtr address, int defaultPort, int reconnectionDelay) : SocketAppenderSkeletonPriv( address, defaultPort, reconnectionDelay ) {} XMLSocketAppenderPriv(const LogString& host, int port, int delay) : SocketAppenderSkeletonPriv( host, port, delay ) {} LOG4CXX_NS::helpers::WriterPtr writer; }; IMPLEMENT_LOG4CXX_OBJECT(XMLSocketAppender) #define _priv static_cast(m_priv.get()) // The default port number of remote logging server (4560) int XMLSocketAppender::DEFAULT_PORT = 4560; // The default reconnection delay (30000 milliseconds or 30 seconds). int XMLSocketAppender::DEFAULT_RECONNECTION_DELAY = 30000; const int XMLSocketAppender::MAX_EVENT_LEN = 1024; XMLSocketAppender::XMLSocketAppender() : SocketAppenderSkeleton(std::make_unique(DEFAULT_PORT, DEFAULT_RECONNECTION_DELAY)) { _priv->layout = std::make_shared(); } XMLSocketAppender::XMLSocketAppender(InetAddressPtr address1, int port1) : SocketAppenderSkeleton(std::make_unique(address1, port1, DEFAULT_RECONNECTION_DELAY)) { _priv->layout = std::make_shared(); Pool p; activateOptions(p); } XMLSocketAppender::XMLSocketAppender(const LogString& host, int port1) : SocketAppenderSkeleton(std::make_unique(host, port1, DEFAULT_RECONNECTION_DELAY)) { _priv->layout = std::make_shared(); Pool p; activateOptions(p); } XMLSocketAppender::~XMLSocketAppender() { finalize(); } int XMLSocketAppender::getDefaultDelay() const { return DEFAULT_RECONNECTION_DELAY; } int XMLSocketAppender::getDefaultPort() const { return DEFAULT_PORT; } void XMLSocketAppender::setSocket(LOG4CXX_NS::helpers::SocketPtr& socket, Pool& p) { OutputStreamPtr os = std::make_shared(socket); CharsetEncoderPtr charset(CharsetEncoder::getUTF8Encoder()); std::lock_guard lock(_priv->mutex); _priv->writer = std::make_shared(os, charset); } void XMLSocketAppender::cleanUp(Pool& p) { if (_priv->writer) { try { _priv->writer->close(p); _priv->writer = nullptr; } catch (std::exception&) { } } } void XMLSocketAppender::append(const spi::LoggingEventPtr& event, LOG4CXX_NS::helpers::Pool& p) { if (_priv->writer) { LogString output; _priv->layout->format(output, event, p); try { _priv->writer->write(output, p); _priv->writer->flush(p); } catch (std::exception& e) { _priv->writer = nullptr; LogLog::warn(LOG4CXX_STR("Detected problem with connection: "), e); if (getReconnectionDelay() > 0) { fireConnector(); } } } } apache-log4cxx-1.3.1/src/main/cpp/serversocket.cpp0000644000175100001770000000305014721727031021412 0ustar runnerdocker/* * 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. */ #include #include #include using namespace LOG4CXX_NS::helpers; /** Creates a server socket on a specified port. */ ServerSocket::ServerSocket(std::unique_ptr priv) : m_priv(std::move(priv)) { } ServerSocket::~ServerSocket() { close(); } void ServerSocket::close() { } /** Retrive setting for SO_TIMEOUT. */ int ServerSocket::getSoTimeout() const { return m_priv->timeout; } /** Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. */ void ServerSocket::setSoTimeout(int newVal) { m_priv->timeout = newVal; } ServerSocketUniquePtr ServerSocket::create(int port){ return std::make_unique(port); } apache-log4cxx-1.3.1/src/main/cpp/rollingpolicy.cpp0000644000175100001770000000164014721727031021564 0ustar runnerdocker/* * 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. */ #include using namespace LOG4CXX_NS::rolling; IMPLEMENT_LOG4CXX_OBJECT(RollingPolicy) apache-log4cxx-1.3.1/src/main/cpp/datagramsocket.cpp0000644000175100001770000000462014721727031021670 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(DatagramSocket) DatagramSocket::DatagramSocket(std::unique_ptr priv) : m_priv(std::move(priv)) {} DatagramSocket::~DatagramSocket() { try { close(); } catch (SocketException&) { } } /** Close the socket.*/ void DatagramSocket::close() { } InetAddressPtr DatagramSocket::getInetAddress() const { return m_priv->address; } InetAddressPtr DatagramSocket::getLocalAddress() const { return m_priv->localAddress; } int DatagramSocket::getLocalPort() const { return m_priv->localPort; } int DatagramSocket::getPort() const { return m_priv->port; } bool DatagramSocket::isBound() const { return m_priv->localPort != 0; } bool DatagramSocket::isConnected() const { return m_priv->port != 0; } DatagramSocketUniquePtr DatagramSocket::create(){ return std::make_unique(); } DatagramSocketUniquePtr DatagramSocket::create(int localPort1){ auto sock = std::make_unique(localPort1); InetAddressPtr bindAddr = InetAddress::anyAddress(); sock->bind(localPort1, bindAddr); return sock; } DatagramSocketUniquePtr DatagramSocket::create(int localPort1, InetAddressPtr localAddress1){ auto sock = std::make_unique(localPort1, localAddress1); sock->bind(localPort1, localAddress1); return sock; } apache-log4cxx-1.3.1/src/main/cpp/file.cpp0000644000175100001770000001470214721727031017620 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; struct File::FilePrivate{ FilePrivate() : autoDelete(false) {} FilePrivate(LogString path) : path(path), autoDelete(false) {} FilePrivate(LogString path, bool autoDelete) : path(path), autoDelete(autoDelete) {} LogString path; bool autoDelete; }; File::File() : m_priv(std::make_unique()) { } template static LogString decodeLS(const S* src) { LogString dst; if (src != 0) { Transcoder::decode(src, dst); } return dst; } template static LogString decodeLS(const std::basic_string& src) { LogString dst; Transcoder::decode(src, dst); return dst; } File::File(const std::string& name1) : m_priv(std::make_unique(decodeLS(name1))) { } File::File(const char* name1) : m_priv(std::make_unique(decodeLS(name1))) { } #if LOG4CXX_WCHAR_T_API File::File(const std::wstring& name1) : m_priv(std::make_unique(decodeLS(name1))) { } File::File(const wchar_t* name1) : m_priv(std::make_unique(decodeLS(name1))) { } #endif #if LOG4CXX_UNICHAR_API || LOG4CXX_LOGCHAR_IS_UNICHAR File::File(const std::basic_string& name1) : m_priv(std::make_unique(decodeLS(name1))) { } File::File(const UniChar* name1) : m_priv(std::make_unique(decodeLS(name1))) { } #endif #if LOG4CXX_CFSTRING_API File::File(const CFStringRef& name1) : m_priv(std::make_unique(decodeLS(name1))) { } #endif File::File(const File& src) : m_priv(std::make_unique(src.m_priv->path, src.m_priv->autoDelete)) { } File& File::operator=(const File& src) { if (this == &src) { return *this; } m_priv->path.assign(src.m_priv->path); m_priv->autoDelete = src.m_priv->autoDelete; return *this; } File::~File() { if(m_priv->autoDelete){ Pool p; deleteFile(p); } } LogString File::getPath() const { return m_priv->path; } File& File::setPath(const LogString& newName) { m_priv->path.assign(newName); return *this; } LogString File::getName() const { const logchar slashes[] = { 0x2F, 0x5C, 0 }; size_t lastSlash = m_priv->path.find_last_of(slashes); if (lastSlash != LogString::npos) { return m_priv->path.substr(lastSlash + 1); } return m_priv->path; } char* File::getPath(Pool& p) const { int style = APR_FILEPATH_ENCODING_UNKNOWN; apr_filepath_encoding(&style, p.getAPRPool()); char* retval = NULL; if (style == APR_FILEPATH_ENCODING_UTF8) { retval = Transcoder::encodeUTF8(m_priv->path, p); } else { retval = Transcoder::encode(m_priv->path, p); } return retval; } log4cxx_status_t File::open(apr_file_t** file, int flags, int perm, Pool& p) const { return apr_file_open(file, getPath(p), flags, perm, p.getAPRPool()); } bool File::exists(Pool& p) const { apr_finfo_t finfo; apr_status_t rv = apr_stat(&finfo, getPath(p), 0, p.getAPRPool()); return rv == APR_SUCCESS; } char* File::convertBackSlashes(char* src) { for (char* c = src; *c != 0; c++) { if (*c == '\\') { *c = '/'; } } return src; } bool File::deleteFile(Pool& p) const { apr_status_t rv = apr_file_remove(convertBackSlashes(getPath(p)), p.getAPRPool()); return rv == APR_SUCCESS; } bool File::renameTo(const File& dest, Pool& p) const { apr_status_t rv = apr_file_rename(convertBackSlashes(getPath(p)), convertBackSlashes(dest.getPath(p)), p.getAPRPool()); return rv == APR_SUCCESS; } size_t File::length(Pool& pool) const { apr_finfo_t finfo; apr_status_t rv = apr_stat(&finfo, getPath(pool), APR_FINFO_SIZE, pool.getAPRPool()); if (rv == APR_SUCCESS) { return (size_t) finfo.size; } return 0; } log4cxx_time_t File::lastModified(Pool& pool) const { apr_finfo_t finfo; apr_status_t rv = apr_stat(&finfo, getPath(pool), APR_FINFO_MTIME, pool.getAPRPool()); if (rv == APR_SUCCESS) { return finfo.mtime; } return 0; } std::vector File::list(Pool& p) const { apr_dir_t* dir; apr_finfo_t entry; std::vector filenames; apr_status_t stat = apr_dir_open(&dir, convertBackSlashes(getPath(p)), p.getAPRPool()); if (stat == APR_SUCCESS) { int style = APR_FILEPATH_ENCODING_UNKNOWN; apr_filepath_encoding(&style, p.getAPRPool()); stat = apr_dir_read(&entry, APR_FINFO_DIRENT, dir); while (stat == APR_SUCCESS) { if (entry.name != NULL) { LogString filename; if (style == APR_FILEPATH_ENCODING_UTF8) { Transcoder::decodeUTF8(entry.name, filename); } else { Transcoder::decode(entry.name, filename); } filenames.push_back(filename); } stat = apr_dir_read(&entry, APR_FINFO_DIRENT, dir); } stat = apr_dir_close(dir); } return filenames; } LogString File::getParent(Pool&) const { LogString::size_type slashPos = m_priv->path.rfind(LOG4CXX_STR('/')); LogString::size_type backPos = m_priv->path.rfind(LOG4CXX_STR('\\')); if (slashPos == LogString::npos) { slashPos = backPos; } else { if (backPos != LogString::npos && backPos > slashPos) { slashPos = backPos; } } LogString parent; if (slashPos != LogString::npos && slashPos > 0) { parent.assign(m_priv->path, 0, slashPos); } return parent; } bool File::mkdirs(Pool& p) const { apr_status_t stat = apr_dir_make_recursive(convertBackSlashes(getPath(p)), APR_OS_DEFAULT, p.getAPRPool()); return stat == APR_SUCCESS; } void File::setAutoDelete(bool autoDelete){ m_priv->autoDelete = autoDelete; } bool File::getAutoDelete() const{ return m_priv->autoDelete; } apache-log4cxx-1.3.1/src/main/cpp/integer.cpp0000644000175100001770000000206414721727031020334 0ustar runnerdocker/* * 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. */ #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(Integer) Integer::Integer() : val(0) { } Integer::Integer(int val1) : val(val1) { } Integer::~Integer() { } apache-log4cxx-1.3.1/src/main/cpp/patternlayout.cpp0000644000175100001770000002251314721727031021613 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::pattern; struct PatternLayout::PatternLayoutPrivate { PatternLayoutPrivate() : expectedPatternLength(100) {} PatternLayoutPrivate(const LogString& pattern) : conversionPattern(pattern) , expectedPatternLength(100) {} /** * Conversion pattern. */ LogString conversionPattern; /** * Pattern converters. */ LoggingEventPatternConverterList patternConverters; /** * Field widths and alignment corresponding to pattern converters. */ FormattingInfoList patternFields; LogString m_fatalColor = LOG4CXX_STR("\\x1B[35m"); //magenta LogString m_errorColor = LOG4CXX_STR("\\x1B[31m"); //red LogString m_warnColor = LOG4CXX_STR("\\x1B[33m"); //yellow LogString m_infoColor = LOG4CXX_STR("\\x1B[32m"); //green LogString m_debugColor = LOG4CXX_STR("\\x1B[36m"); //cyan; LogString m_traceColor = LOG4CXX_STR("\\x1B[34m"); //blue; // Expected length of a formatted event excluding the message text size_t expectedPatternLength; }; IMPLEMENT_LOG4CXX_OBJECT(PatternLayout) PatternLayout::PatternLayout() : m_priv(std::make_unique()) { } /** Constructs a PatternLayout using the supplied conversion pattern. */ PatternLayout::PatternLayout(const LogString& pattern) : m_priv(std::make_unique(pattern)) { Pool pool; activateOptions(pool); } PatternLayout::~PatternLayout() {} void PatternLayout::setConversionPattern(const LogString& pattern) { m_priv->conversionPattern = pattern; Pool pool; activateOptions(pool); } void PatternLayout::format(LogString& output, const spi::LoggingEventPtr& event, Pool& pool) const { output.reserve(m_priv->expectedPatternLength + event->getMessage().size()); std::vector::const_iterator formatterIter = m_priv->patternFields.begin(); for (std::vector::const_iterator converterIter = m_priv->patternConverters.begin(); converterIter != m_priv->patternConverters.end(); converterIter++, formatterIter++) { int startField = (int)output.length(); (*converterIter)->format(event, output, pool); (*formatterIter)->format(startField, output); } } void PatternLayout::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("CONVERSIONPATTERN"), LOG4CXX_STR("conversionpattern"))) { m_priv->conversionPattern = OptionConverter::convertSpecialChars(value); }else if(StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("ERRORCOLOR"), LOG4CXX_STR("errorcolor"))){ m_priv->m_errorColor = value; if (LogLog::isDebugEnabled()) { LogString msg(LOG4CXX_STR("Setting error color to ")); msg += value; LogLog::debug(msg); } }else if(StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("FATALCOLOR"), LOG4CXX_STR("fatalcolor"))){ m_priv->m_fatalColor = value; }else if(StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("WARNCOLOR"), LOG4CXX_STR("warncolor"))){ m_priv->m_warnColor = value; }else if(StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("INFOCOLOR"), LOG4CXX_STR("infocolor"))){ m_priv->m_infoColor = value; }else if(StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("DEBUGCOLOR"), LOG4CXX_STR("debugcolor"))){ m_priv->m_debugColor = value; }else if(StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("TRACECOLOR"), LOG4CXX_STR("tracecolor"))){ m_priv->m_traceColor = value; } } void PatternLayout::activateOptions(Pool&) { LogString pat(m_priv->conversionPattern); if (pat.empty()) { pat = LOG4CXX_STR("%m%n"); } m_priv->patternConverters.erase(m_priv->patternConverters.begin(), m_priv->patternConverters.end()); m_priv->patternFields.erase(m_priv->patternFields.begin(), m_priv->patternFields.end()); std::vector converters; PatternParser::parse(pat, converters, m_priv->patternFields, getFormatSpecifiers()); // // strip out any pattern converters that don't handle LoggingEvents // // for (auto const& converterItem : converters) { if (auto eventConverter = LOG4CXX_NS::cast(converterItem)) { m_priv->patternConverters.push_back(eventConverter); } } m_priv->expectedPatternLength = getFormattedEventCharacterCount() * 2; } #define RULES_PUT(spec, cls) \ specs.insert(PatternMap::value_type(LogString(LOG4CXX_STR(spec)), cls ::newInstance)) LOG4CXX_NS::pattern::PatternMap PatternLayout::getFormatSpecifiers() { PatternMap specs; RULES_PUT("c", LoggerPatternConverter); RULES_PUT("logger", LoggerPatternConverter); RULES_PUT("C", ClassNamePatternConverter); RULES_PUT("class", ClassNamePatternConverter); specs.insert(PatternMap::value_type(LogString(LOG4CXX_STR("Y")), std::bind(&PatternLayout::createColorStartPatternConverter, this, std::placeholders::_1))); RULES_PUT("y", ColorEndPatternConverter); RULES_PUT("d", DatePatternConverter); RULES_PUT("date", DatePatternConverter); RULES_PUT("f", ShortFileLocationPatternConverter); RULES_PUT("F", FileLocationPatternConverter); RULES_PUT("file", FileLocationPatternConverter); RULES_PUT("l", FullLocationPatternConverter); RULES_PUT("L", LineLocationPatternConverter); RULES_PUT("line", LineLocationPatternConverter); RULES_PUT("m", MessagePatternConverter); RULES_PUT("message", MessagePatternConverter); RULES_PUT("n", LineSeparatorPatternConverter); RULES_PUT("M", MethodLocationPatternConverter); RULES_PUT("method", MethodLocationPatternConverter); RULES_PUT("p", LevelPatternConverter); RULES_PUT("level", LevelPatternConverter); RULES_PUT("r", RelativeTimePatternConverter); RULES_PUT("relative", RelativeTimePatternConverter); RULES_PUT("t", ThreadPatternConverter); RULES_PUT("thread", ThreadPatternConverter); RULES_PUT("T", ThreadUsernamePatternConverter); RULES_PUT("threadname", ThreadUsernamePatternConverter); RULES_PUT("x", NDCPatternConverter); RULES_PUT("ndc", NDCPatternConverter); RULES_PUT("X", PropertiesPatternConverter); RULES_PUT("J", MDCPatternConverter); RULES_PUT("properties", PropertiesPatternConverter); RULES_PUT("throwable", ThrowableInformationPatternConverter); return specs; } LogString PatternLayout::getConversionPattern() const { return m_priv->conversionPattern; } pattern::PatternConverterPtr PatternLayout::createColorStartPatternConverter(const std::vector& options){ std::shared_ptr colorPatternConverter = std::make_shared(); colorPatternConverter->setErrorColor(m_priv->m_errorColor); colorPatternConverter->setFatalColor(m_priv->m_fatalColor); colorPatternConverter->setWarnColor(m_priv->m_warnColor); colorPatternConverter->setInfoColor(m_priv->m_infoColor); colorPatternConverter->setDebugColor(m_priv->m_debugColor); colorPatternConverter->setTraceColor(m_priv->m_traceColor); return colorPatternConverter; } apache-log4cxx-1.3.1/src/main/cpp/ndc.cpp0000644000175100001770000001464114721727031017447 0ustar runnerdocker/* * 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. */ #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; NDC::NDC(const std::string& message) { push(message); } NDC::~NDC() { pop(); } const LogString& NDC::getMessage(const DiagnosticContext& ctx) { return ctx.first; } const LogString& NDC::getFullMessage(const DiagnosticContext& ctx) { return ctx.second; } void NDC::clear() { ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { Stack& stack = data->getStack(); while (!stack.empty()) { stack.pop(); } data->recycle(); } } NDC::Stack* NDC::cloneStack() { ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { Stack& stack = data->getStack(); if (!stack.empty()) { return new Stack(stack); } } return new Stack(); } void NDC::inherit(NDC::Stack* stack) { if (stack != NULL) { ThreadSpecificData::inherit(*stack); delete stack; } } bool NDC::get(LogString& dest) { ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { Stack& stack = data->getStack(); if (!stack.empty()) { dest.append(getFullMessage(stack.top())); return true; } data->recycle(); } return false; } int NDC::getDepth() { int size = 0; ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { size = (int)data->getStack().size(); if (size == 0) { data->recycle(); } } return size; } LogString NDC::pop() { ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { Stack& stack = data->getStack(); if (!stack.empty()) { LogString value(getMessage(stack.top())); stack.pop(); data->recycle(); return value; } data->recycle(); } return LogString(); } bool NDC::pop(std::string& dst) { bool retval = false; ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { Stack& stack = data->getStack(); if (!stack.empty()) { Transcoder::encode(getMessage(stack.top()), dst); stack.pop(); retval = true; } data->recycle(); } return retval; } LogString NDC::peek() { ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { Stack& stack = data->getStack(); if (!stack.empty()) { return getMessage(stack.top()); } data->recycle(); } return LogString(); } bool NDC::peek(std::string& dst) { ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { Stack& stack = data->getStack(); if (!stack.empty()) { Transcoder::encode(getMessage(stack.top()), dst); return true; } data->recycle(); } return false; } void NDC::pushLS(const LogString& message) { ThreadSpecificData::push(message); } void NDC::push(const std::string& message) { LOG4CXX_DECODE_CHAR(msg, message); pushLS(msg); } void NDC::remove() { clear(); } bool NDC::empty() { bool empty = true; ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { Stack& stack = data->getStack(); empty = stack.empty(); if (empty) { data->recycle(); } } return empty; } #if LOG4CXX_WCHAR_T_API NDC::NDC(const std::wstring& message) { push(message); } void NDC::push(const std::wstring& message) { LOG4CXX_DECODE_WCHAR(msg, message); pushLS(msg); } bool NDC::pop(std::wstring& dst) { ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { Stack& stack = data->getStack(); if (!stack.empty()) { Transcoder::encode(getMessage(stack.top()), dst); stack.pop(); data->recycle(); return true; } data->recycle(); } return false; } bool NDC::peek(std::wstring& dst) { ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { Stack& stack = data->getStack(); if (!stack.empty()) { Transcoder::encode(getMessage(stack.top()), dst); return true; } data->recycle(); } return false; } #endif #if LOG4CXX_UNICHAR_API NDC::NDC(const std::basic_string& message) { push(message); } void NDC::push(const std::basic_string& message) { LOG4CXX_DECODE_UNICHAR(msg, message); pushLS(msg); } bool NDC::pop(std::basic_string& dst) { ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { Stack& stack = data->getStack(); if (!stack.empty()) { Transcoder::encode(getMessage(stack.top()), dst); stack.pop(); data->recycle(); return true; } data->recycle(); } return false; } bool NDC::peek(std::basic_string& dst) { ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { Stack& stack = data->getStack(); if (!stack.empty()) { Transcoder::encode(getMessage(stack.top()), dst); return true; } data->recycle(); } return false; } #endif #if LOG4CXX_CFSTRING_API NDC::NDC(const CFStringRef& message) { push(message); } void NDC::push(const CFStringRef& message) { LOG4CXX_DECODE_CFSTRING(msg, message); pushLS(msg); } bool NDC::pop(CFStringRef& dst) { ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { Stack& stack = data->getStack(); if (!stack.empty()) { dst = Transcoder::encode(getMessage(stack.top())); stack.pop(); data->recycle(); return true; } data->recycle(); } return false; } bool NDC::peek(CFStringRef& dst) { ThreadSpecificData* data = ThreadSpecificData::getCurrentData(); if (data != 0) { Stack& stack = data->getStack(); if (!stack.empty()) { dst = Transcoder::encode(getMessage(stack.top())); return true; } data->recycle(); } return false; } #endif apache-log4cxx-1.3.1/src/main/cpp/CMakeLists.txt0000644000175100001770000001760714721727031020744 0ustar runnerdocker# # 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. # # Options option(LOG4CXX_ABI_CHECK "Check for ABI changes" OFF) # Build the log4cxx library add_library(log4cxx) if(${log4cxx_ABI_VER} GREATER 15) set_target_properties(log4cxx PROPERTIES CXX_VISIBILITY_PRESET hidden) endif() if(BUILD_SHARED_LIBS) target_compile_definitions(log4cxx PRIVATE LOG4CXX) if(UNIX AND NOT APPLE) # Make defined symbols non-preemptible, which can optimize relocation processing target_link_options(log4cxx PRIVATE "LINKER:-Bsymbolic") endif() else() target_compile_definitions(log4cxx PUBLIC LOG4CXX_STATIC) endif() add_dependencies(log4cxx log4cxx-include) set(extra_classes "") if(LOG4CXX_NETWORKING_SUPPORT) list(APPEND extra_classes datagrampacket.cpp datagramsocket.cpp aprdatagramsocket.cpp serversocket.cpp aprserversocket.cpp socket.cpp aprsocket.cpp telnetappender.cpp socketappenderskeleton.cpp socketoutputstream.cpp xmlsocketappender.cpp syslogwriter.cpp syslogappender.cpp ) endif() if(LOG4CXX_DOMCONFIGURATOR_SUPPORT) list(APPEND extra_classes domconfigurator.cpp ) endif() if(LOG4CXX_MULTIPROCESS_ROLLING_FILE_APPENDER) target_compile_definitions(log4cxx PRIVATE LOG4CXX_MULTI_PROCESS) list(APPEND extra_classes multiprocessrollingfileappender.cpp ) endif() if(${ENABLE_FMT_LAYOUT}) list(APPEND extra_classes fmtlayout.cpp ) endif() target_sources(log4cxx PRIVATE action.cpp andfilter.cpp appenderattachableimpl.cpp appenderskeleton.cpp aprinitializer.cpp asyncappender.cpp basicconfigurator.cpp bufferedwriter.cpp bytearrayinputstream.cpp bytearrayoutputstream.cpp bytebuffer.cpp cacheddateformat.cpp charsetdecoder.cpp charsetencoder.cpp class.cpp classnamepatternconverter.cpp classregistration.cpp colorstartpatternconverter.cpp colorendpatternconverter.cpp configurator.cpp consoleappender.cpp cyclicbuffer.cpp date.cpp dateformat.cpp datepatternconverter.cpp dbappender.cpp defaultconfigurator.cpp defaultloggerfactory.cpp defaultrepositoryselector.cpp exception.cpp fallbackerrorhandler.cpp file.cpp fileappender.cpp filedatepatternconverter.cpp fileinputstream.cpp filelocationpatternconverter.cpp fileoutputstream.cpp filerenameaction.cpp filewatchdog.cpp filter.cpp filterbasedtriggeringpolicy.cpp fixedwindowrollingpolicy.cpp formattinginfo.cpp fulllocationpatternconverter.cpp gzcompressaction.cpp hexdump.cpp hierarchy.cpp htmllayout.cpp inetaddress.cpp inputstream.cpp inputstreamreader.cpp integer.cpp integerpatternconverter.cpp jsonlayout.cpp layout.cpp level.cpp levelmatchfilter.cpp levelpatternconverter.cpp levelrangefilter.cpp linelocationpatternconverter.cpp lineseparatorpatternconverter.cpp literalpatternconverter.cpp loader.cpp locale.cpp locationinfo.cpp locationinfofilter.cpp logger.cpp loggermatchfilter.cpp loggerpatternconverter.cpp loggingevent.cpp loggingeventpatternconverter.cpp loglog.cpp logmanager.cpp logstream.cpp manualtriggeringpolicy.cpp mapfilter.cpp mdc.cpp messagebuffer.cpp messagepatternconverter.cpp methodlocationpatternconverter.cpp nameabbreviator.cpp namepatternconverter.cpp ndc.cpp mdcpatternconverter.cpp ndcpatternconverter.cpp nteventlogappender.cpp odbcappender.cpp onlyonceerrorhandler.cpp optionconverter.cpp outputdebugstringappender.cpp outputstream.cpp outputstreamwriter.cpp patternconverter.cpp patternlayout.cpp patternparser.cpp pool.cpp properties.cpp propertiespatternconverter.cpp propertyconfigurator.cpp propertyresourcebundle.cpp propertysetter.cpp reader.cpp relativetimedateformat.cpp relativetimepatternconverter.cpp resourcebundle.cpp rollingfileappender.cpp rollingpolicy.cpp rollingpolicybase.cpp rolloverdescription.cpp rootlogger.cpp shortfilelocationpatternconverter.cpp simpledateformat.cpp simplelayout.cpp sizebasedtriggeringpolicy.cpp smtpappender.cpp strftimedateformat.cpp stringhelper.cpp stringmatchfilter.cpp stringtokenizer.cpp system.cpp systemerrwriter.cpp systemoutwriter.cpp threadlocal.cpp threadpatternconverter.cpp threadusernamepatternconverter.cpp threadspecificdata.cpp threadutility.cpp throwableinformationpatternconverter.cpp timebasedrollingpolicy.cpp timezone.cpp transcoder.cpp transform.cpp triggeringpolicy.cpp writer.cpp writerappender.cpp xmllayout.cpp zipcompressaction.cpp ${extra_classes} ) if(LOG4CXX_EVENTS_AT_EXIT) target_sources(log4cxx PRIVATE atexitregistry.cpp ) endif(LOG4CXX_EVENTS_AT_EXIT) if(WIN32) target_sources(log4cxx PRIVATE visualstudio.natvis ) endif(WIN32) set(LOG4CXX_LIB_NAME "log4cxx" CACHE STRING "Main library base name") set_target_properties(log4cxx PROPERTIES VERSION ${LIBLOG4CXX_LIB_VERSION} SOVERSION ${LIBLOG4CXX_LIB_SOVERSION} OUTPUT_NAME ${LOG4CXX_LIB_NAME} PDB_NAME ${LOG4CXX_LIB_NAME} COMPILE_PDB_NAME ${LOG4CXX_LIB_NAME} EXPORT_NAME ${LOG4CXX_LIB_NAME} ) get_directory_property( FILESYSTEM_IMPL DIRECTORY "${LOG4CXX_SOURCE_DIR}/src/main/include" DEFINITION FILESYSTEM_IMPL ) if("${FILESYSTEM_IMPL}" STREQUAL "std::filesystem" OR "${FILESYSTEM_IMPL}" STREQUAL "std::experimental::filesystem" ) target_link_libraries(log4cxx PUBLIC $<$,$,9.0>>:stdc++fs>) endif() if(${ENABLE_FMT_LAYOUT}) target_link_libraries(log4cxx PUBLIC fmt::fmt) endif() if(LOG4CXX_ABI_CHECK) if(NOT "log4cxx" STREQUAL "${LOG4CXX_NS}") message(FATAL_ERROR "ABI compatability can only be checked if LOG4CXX_NS=log4cxx, but LOG4CXX_NS=${LOG4CXX_NS}.") endif() message("Getting dependencies for ABI compatability check...") # Get the latest version of abi-dumper and abi-compliance-checker include(FetchContent) FetchContent_Declare(abi-dumper GIT_REPOSITORY https://github.com/lvc/abi-dumper.git GIT_TAG 1.2 ) FetchContent_GetProperties(abi-dumper) if(NOT abi-dumper_POPULATED) FetchContent_Populate(abi-dumper) endif() FetchContent_Declare(abi-compliance-checker GIT_REPOSITORY https://github.com/lvc/abi-compliance-checker.git GIT_TAG f60ce442c33f1d5cda1cec7cfddee24af1777572 ) FetchContent_GetProperties(abi-compliance-checker) if(NOT abi-compliance-checker_POPULATED) FetchContent_Populate(abi-compliance-checker) endif() set(abi-dumper-script ${abi-dumper_SOURCE_DIR}/abi-dumper.pl) set(abi-compliance-script ${abi-compliance-checker_SOURCE_DIR}/abi-compliance-checker.pl) add_custom_target(dump-abi ALL COMMAND perl ${abi-dumper-script} -o new-abi.dump -skip-cxx -vnum ${log4cxx_ABI_VER} $ DEPENDS log4cxx COMMENT "Dumping ABI symbols") add_custom_target(compare-abi ALL COMMAND perl ${abi-compliance-script} -skip-internal-symbols "\\d\\(fmt\\)" -skip-internal-types "\\(fmt\\)::" -l log4cxx -old ${LOG4CXX_SOURCE_DIR}/src/main/abi-symbols/abi.dump -new new-abi.dump DEPENDS dump-abi COMMENT "Comparing ABI symbols") endif(LOG4CXX_ABI_CHECK) apache-log4cxx-1.3.1/src/main/cpp/hierarchy.cpp0000644000175100001770000002703514721727031020662 0ustar runnerdocker/* * 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. */ #include #if LOG4CXX_ABI_VERSION <= 15 #include #endif #include #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; typedef std::map LoggerMap; typedef std::map ProvisionNodeMap; struct Hierarchy::HierarchyPrivate { HierarchyPrivate() : configured(false) , emittedNoAppenderWarning(false) , emittedNoResourceBundleWarning(false) , thresholdInt(Level::ALL_INT) { } helpers::Pool pool; mutable std::recursive_mutex mutex; mutable std::mutex configuredMutex; bool configured; bool emittedNoAppenderWarning; bool emittedNoResourceBundleWarning; int thresholdInt; spi::HierarchyEventListenerList listeners; LoggerPtr root; LevelPtr threshold; LoggerMap loggers; ProvisionNodeMap provisionNodes; std::vector allAppenders; mutable std::mutex listenerMutex; }; IMPLEMENT_LOG4CXX_OBJECT(Hierarchy) Hierarchy::Hierarchy() : m_priv(std::make_unique()) { } Hierarchy::~Hierarchy() { std::lock_guard lock(m_priv->mutex); for (auto& item : m_priv->loggers) { if (auto& pLogger = item.second) { pLogger->removeHierarchy(); pLogger->removeAllAppenders(); } } if (m_priv->root) { m_priv->root->removeHierarchy(); m_priv->root->removeAllAppenders(); } } void Hierarchy::addHierarchyEventListener(const spi::HierarchyEventListenerPtr& listener) { std::lock_guard lock(m_priv->listenerMutex); if (std::find(m_priv->listeners.begin(), m_priv->listeners.end(), listener) != m_priv->listeners.end()) { LogLog::warn(LOG4CXX_STR("Ignoring attempt to add an existent listener.")); } else { m_priv->listeners.push_back(listener); } } void Hierarchy::removeHierarchyEventListener(const spi::HierarchyEventListenerPtr& listener) { std::lock_guard lock(m_priv->listenerMutex); auto found = std::find(m_priv->listeners.begin(), m_priv->listeners.end(), listener); if(found != m_priv->listeners.end()){ m_priv->listeners.erase(found); } } void Hierarchy::clear() { std::lock_guard lock(m_priv->mutex); m_priv->loggers.clear(); } void Hierarchy::emitNoAppenderWarning(const Logger* logger) { bool emitWarning = false; { std::lock_guard lock(m_priv->mutex); emitWarning = !m_priv->emittedNoAppenderWarning; m_priv->emittedNoAppenderWarning = true; } // No appender in hierarchy, warn user only once. if (emitWarning) { LogLog::warn(((LogString) LOG4CXX_STR("No appender could be found for logger (")) + logger->getName() + LOG4CXX_STR(").")); LogLog::warn(LOG4CXX_STR("Please initialize the log4cxx system properly.")); } } LoggerPtr Hierarchy::exists(const LogString& name) { std::lock_guard lock(m_priv->mutex); LoggerPtr logger; LoggerMap::iterator it = m_priv->loggers.find(name); if (it != m_priv->loggers.end()) { logger = it->second; } return logger; } void Hierarchy::setThreshold(const LevelPtr& l) { if (l != 0) { std::lock_guard lock(m_priv->mutex); setThresholdInternal(l); } } void Hierarchy::setThreshold(const LogString& levelStr) { LevelPtr l(Level::toLevelLS(levelStr, 0)); if (l != 0) { setThreshold(l); } else { LogLog::warn(((LogString) LOG4CXX_STR("No level could be found named \"")) + levelStr + LOG4CXX_STR("\".")); } } void Hierarchy::setThresholdInternal(const LevelPtr& l) { m_priv->thresholdInt = l->toInt(); m_priv->threshold = l; if (m_priv->thresholdInt != Level::ALL_INT) { m_priv->configured = true; } } void Hierarchy::fireAddAppenderEvent(const Logger* logger, const Appender* appender) { setConfigured(true); HierarchyEventListenerList clonedList; { std::lock_guard lock(m_priv->listenerMutex); clonedList = m_priv->listeners; } for (auto& item : clonedList) item->addAppenderEvent(logger, appender); } void Hierarchy::fireRemoveAppenderEvent(const Logger* logger, const Appender* appender) { HierarchyEventListenerList clonedList; { std::lock_guard lock(m_priv->listenerMutex); clonedList = m_priv->listeners; } for (auto& item : clonedList) item->removeAppenderEvent(logger, appender); } LevelPtr Hierarchy::getThreshold() const { return m_priv->threshold ? m_priv->threshold : Level::getAll(); } LoggerPtr Hierarchy::getLogger(const LogString& name) { #if LOG4CXX_ABI_VERSION <= 15 static WideLife defaultFactory = std::make_shared(); #else static WideLife defaultFactory = std::make_shared(); #endif return getLogger(name, defaultFactory); } LoggerPtr Hierarchy::getLogger(const LogString& name, const spi::LoggerFactoryPtr& factory) { auto root = getRootLogger(); std::lock_guard lock(m_priv->mutex); LoggerMap::iterator it = m_priv->loggers.find(name); LoggerPtr result; if (it != m_priv->loggers.end()) { result = it->second; } if (!result && factory) { #if LOG4CXX_ABI_VERSION <= 15 LoggerPtr logger(factory->makeNewLoggerInstance(m_priv->pool, name)); #else LoggerPtr logger(factory->makeNewLoggerInstance(name)); #endif logger->setHierarchy(this); m_priv->loggers.insert(LoggerMap::value_type(name, logger)); ProvisionNodeMap::iterator it2 = m_priv->provisionNodes.find(name); if (it2 != m_priv->provisionNodes.end()) { updateChildren(it2->second, logger); m_priv->provisionNodes.erase(it2); } updateParents(logger, root); result = logger; } return result; } LoggerList Hierarchy::getCurrentLoggers() const { std::lock_guard lock(m_priv->mutex); LoggerList v; for (auto& item : m_priv->loggers) { if (auto pLogger = item.second) v.push_back(pLogger); } return v; } LoggerPtr Hierarchy::getRootLogger() const { std::lock_guard lock(m_priv->mutex); if (!m_priv->root) { m_priv->root = std::make_shared(Level::getDebug()); m_priv->root->setHierarchy(const_cast(this)); } return m_priv->root; } bool Hierarchy::isDisabled(int level) const { return m_priv->thresholdInt > level; } void Hierarchy::ensureIsConfigured(std::function configurator) { std::lock_guard lock(m_priv->configuredMutex); if (!m_priv->configured) { configurator(); m_priv->configured = true; } } void Hierarchy::resetConfiguration() { std::lock_guard lock(m_priv->mutex); if (m_priv->root) { m_priv->root->setLevel(Level::getDebug()); m_priv->root->setResourceBundle(0); } setThresholdInternal(Level::getAll()); shutdownInternal(); for (auto& item : m_priv->loggers) { if (auto pLogger = item.second) { pLogger->setLevel(0); pLogger->setAdditivity(true); pLogger->setResourceBundle(0); } } } void Hierarchy::shutdown() { std::lock_guard lock(m_priv->mutex); shutdownInternal(); } void Hierarchy::shutdownInternal() { m_priv->configured = false; // begin by closing nested appenders if (m_priv->root) m_priv->root->closeNestedAppenders(); for (auto& item : m_priv->loggers) { if (auto pLogger = item.second) pLogger->closeNestedAppenders(); } // then, remove all appenders if (m_priv->root) m_priv->root->removeAllAppenders(); for (auto& item : m_priv->loggers) { if (auto pLogger = item.second) pLogger->removeAllAppenders(); } } void Hierarchy::updateParents(const LoggerPtr& logger, const LoggerPtr& root) { const LogString name(logger->getName()); size_t length = name.size(); bool parentFound = false; // if name = "w.x.y.z", loop through "w.x.y", "w.x" and "w", but not "w.x.y.z" for (size_t i = name.find_last_of(0x2E /* '.' */, length - 1); (i != LogString::npos) && (i != 0); i = name.find_last_of(0x2E /* '.' */, i - 1)) { LogString substr = name.substr(0, i); LoggerMap::iterator it = m_priv->loggers.find(substr); if (it != m_priv->loggers.end()) { parentFound = true; logger->setParent( it->second ); break; // no need to update the ancestors of the closest ancestor } else { ProvisionNodeMap::iterator it2 = m_priv->provisionNodes.find(substr); if (it2 != m_priv->provisionNodes.end()) { it2->second.push_back(logger); } else { ProvisionNode node(1, logger); m_priv->provisionNodes.insert( ProvisionNodeMap::value_type(substr, node)); } } } // If we could not find any existing parents, then link with root. if (!parentFound) { logger->setParent( root ); } } void Hierarchy::updateChildren(ProvisionNode& pn, const LoggerPtr& logger) { for (auto& l : pn) { // Unless this child already points to a correct (lower) parent, // make logger.parent point to l.parent and l.parent to logger. if (!StringHelper::startsWith(l->getParent()->getName(), logger->getName())) { logger->setParent( l->getParent() ); l->setParent( logger ); } } } void Hierarchy::updateChildren(const Logger* parent) { for (auto& item : m_priv->loggers) { for (auto l = item.second; l; l = l->getParent()) { if (l->getParent().get() == parent) { item.second->updateThreshold(); break; } } } } void Hierarchy::setConfigured(bool newValue) { std::unique_lock lock(m_priv->configuredMutex, std::try_to_lock); if (lock.owns_lock()) // Not being auto-configured? m_priv->configured = newValue; } bool Hierarchy::isConfigured() { std::lock_guard lock(m_priv->configuredMutex); // Blocks while auto-configuration is active return m_priv->configured; } HierarchyPtr Hierarchy::create() { HierarchyPtr ret(new Hierarchy); return ret; } void Hierarchy::clearAppenders() { m_priv->allAppenders.clear(); } void Hierarchy::addAppender(AppenderPtr appender) { m_priv->allAppenders.push_back(appender); } bool Hierarchy::removeLogger(const LogString& name, bool ifNotUsed) { auto parentRefCount = [this](const LoggerPtr& child) -> int { int result = 0; for (auto& node : m_priv->provisionNodes) { if (node.second.end() != std::find(node.second.begin(), node.second.end(), child)) ++result; } return result; }; bool result = false; std::lock_guard lock(m_priv->mutex); auto it = m_priv->loggers.find(name); if (it == m_priv->loggers.end()) ; else if (ifNotUsed && 1 + parentRefCount(it->second) < it->second.use_count()) ; else { for (auto& node : m_priv->provisionNodes) { for (size_t i = node.second.size(); 0 < i; ) { if (node.second[--i] == it->second) node.second.erase(node.second.begin() + i); } } m_priv->loggers.erase(it); result = true; } return result; } apache-log4cxx-1.3.1/src/main/cpp/relativetimepatternconverter.cpp0000644000175100001770000000344514721727031024723 0ustar runnerdocker/* * 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. */ #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::pattern; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(RelativeTimePatternConverter) RelativeTimePatternConverter::RelativeTimePatternConverter() : LoggingEventPatternConverter(LOG4CXX_STR("Time"), LOG4CXX_STR("time")) { } PatternConverterPtr RelativeTimePatternConverter::newInstance( const std::vector& /* options */) { static WideLife def = std::make_shared(); return def; } void RelativeTimePatternConverter::format( const LoggingEventPtr& event, LogString& toAppendTo, Pool& p) const { log4cxx_time_t delta = (event->getTimeStamp() - LoggingEvent::getStartTime()) / 1000; StringHelper::toString(delta, p, toAppendTo); } apache-log4cxx-1.3.1/src/main/cpp/rollingpolicybase.cpp0000644000175100001770000001255714721727031022430 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::rolling; using namespace LOG4CXX_NS::helpers; using namespace LOG4CXX_NS::pattern; IMPLEMENT_LOG4CXX_OBJECT(RollingPolicyBase) RollingPolicyBase::RollingPolicyBase() : m_priv(std::make_unique()) { } RollingPolicyBase::RollingPolicyBase( std::unique_ptr priv ) : m_priv(std::move(priv)){ } RollingPolicyBase::~RollingPolicyBase() { } void RollingPolicyBase::activateOptions(LOG4CXX_NS::helpers::Pool& /* pool */) { if (m_priv->fileNamePatternStr.length() > 0) { parseFileNamePattern(); } else { LogString msg(LOG4CXX_STR("The FileNamePattern option must be set before using FixedWindowRollingPolicy.")); LogString ref1(LOG4CXX_STR("See also http://logging.apache.org/log4j/codes.html#tbr_fnp_not_set")); LogLog::warn(msg); LogLog::warn(ref1); throw IllegalStateException(); } } void RollingPolicyBase::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("FILENAMEPATTERN"), LOG4CXX_STR("filenamepattern"))) { m_priv->fileNamePatternStr = value; }else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("CREATEINTERMEDIATEDIRECTORIES"), LOG4CXX_STR("createintermediatedirectories"))) { m_priv->createIntermediateDirectories = OptionConverter::toBoolean(value, false); } } void RollingPolicyBase::setFileNamePattern(const LogString& fnp) { m_priv->fileNamePatternStr = fnp; } LogString RollingPolicyBase::getFileNamePattern() const { return m_priv->fileNamePatternStr; } /** * Parse file name pattern. */ void RollingPolicyBase::parseFileNamePattern() { m_priv->patternConverters.erase(m_priv->patternConverters.begin(), m_priv->patternConverters.end()); m_priv->patternFields.erase(m_priv->patternFields.begin(), m_priv->patternFields.end()); PatternParser::parse(m_priv->fileNamePatternStr, m_priv->patternConverters, m_priv->patternFields, getFormatSpecifiers()); } /** * 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. */ void RollingPolicyBase::formatFileName( const ObjectPtr& obj, LogString& toAppendTo, Pool& pool) const { std::vector::const_iterator formatterIter = m_priv->patternFields.begin(); for (std::vector::const_iterator converterIter = m_priv->patternConverters.begin(); converterIter != m_priv->patternConverters.end(); converterIter++, formatterIter++) { auto startField = toAppendTo.length(); (*converterIter)->format(obj, toAppendTo, pool); (*formatterIter)->format((int)startField, toAppendTo); } } PatternConverterPtr RollingPolicyBase::getIntegerPatternConverter() const { for (std::vector::const_iterator converterIter = m_priv->patternConverters.begin(); converterIter != m_priv->patternConverters.end(); converterIter++) { IntegerPatternConverterPtr intPattern; PatternConverterPtr patternptr = (*converterIter); intPattern = LOG4CXX_NS::cast(patternptr); if (intPattern != NULL) { return *converterIter; } } PatternConverterPtr noMatch; return noMatch; } PatternConverterPtr RollingPolicyBase::getDatePatternConverter() const { for (std::vector::const_iterator converterIter = m_priv->patternConverters.begin(); converterIter != m_priv->patternConverters.end(); converterIter++) { DatePatternConverterPtr datePattern; PatternConverterPtr patternptr = (*converterIter); datePattern = LOG4CXX_NS::cast(patternptr); if (datePattern != NULL) { return *converterIter; } } PatternConverterPtr noMatch; return noMatch; } bool RollingPolicyBase::getCreateIntermediateDirectories() const{ return m_priv->createIntermediateDirectories; } void RollingPolicyBase::setCreateIntermediateDirectories(bool createIntermediate){ m_priv->createIntermediateDirectories = createIntermediate; } PatternConverterList RollingPolicyBase::getPatternConverterList() const { return m_priv->patternConverters; } apache-log4cxx-1.3.1/src/main/cpp/loglog.cpp0000644000175100001770000001045314721727031020163 0ustar runnerdocker/* * 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. */ #include #include #include #include #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; struct LogLog::LogLogPrivate { LogLogPrivate() : debugEnabled(false), quietMode(false){} ~LogLogPrivate() { quietMode = true; // Prevent output after deletion by onexit processing chain. } bool debugEnabled; /** In quietMode not even errors generate any output. */ bool quietMode; std::mutex mutex; }; LogLog::LogLog() : m_priv(std::make_unique()) { LogString log4cxxDebug = OptionConverter::getSystemProperty(LOG4CXX_STR("LOG4CXX_DEBUG"), LOG4CXX_STR("false")); m_priv->debugEnabled = OptionConverter::toBoolean(log4cxxDebug, false); } LogLog::~LogLog(){} LogLog& LogLog::getInstance() { static WideLife internalLogger; return internalLogger; } bool LogLog::isDebugEnabled() { auto p = getInstance().m_priv.get(); return p && !p->quietMode // Not deleted by onexit processing? && p->debugEnabled; } void LogLog::setInternalDebugging(bool debugEnabled1) { auto p = getInstance().m_priv.get(); if (p && !p->quietMode) // Not deleted by onexit processing? p->debugEnabled = debugEnabled1; } void LogLog::debug(const LogString& msg) { auto p = getInstance().m_priv.get(); if (p && !p->quietMode) // Not deleted by onexit processing? { if (!p->debugEnabled) { return; } std::lock_guard lock(p->mutex); emit(msg); } } void LogLog::debug(const LogString& msg, const std::exception& e) { auto p = getInstance().m_priv.get(); if (p && !p->quietMode) // Not deleted by onexit processing? { if (!p->debugEnabled) return; std::lock_guard lock(p->mutex); emit(msg); emit(e); } } void LogLog::error(const LogString& msg) { auto p = getInstance().m_priv.get(); if (p && !p->quietMode) // Not deleted by onexit processing? { std::lock_guard lock(p->mutex); emit(msg); } } void LogLog::error(const LogString& msg, const std::exception& e) { auto p = getInstance().m_priv.get(); if (p && !p->quietMode) // Not deleted by onexit processing? { std::lock_guard lock(p->mutex); emit(msg); emit(e); } } void LogLog::setQuietMode(bool quietMode1) { auto p = getInstance().m_priv.get(); std::lock_guard lock(p->mutex); p->quietMode = quietMode1; } void LogLog::warn(const LogString& msg) { auto p = getInstance().m_priv.get(); if (p && !p->quietMode) // Not deleted by onexit processing? { std::lock_guard lock(p->mutex); emit(msg); } } void LogLog::warn(const LogString& msg, const std::exception& e) { auto p = getInstance().m_priv.get(); if (p && !p->quietMode) // Not deleted by onexit processing? { std::lock_guard lock(p->mutex); emit(msg); emit(e); } } void LogLog::emit(const LogString& msg) { LogString out(LOG4CXX_STR("log4cxx: ")); out.append(msg); out.append(1, (logchar) 0x0A); SystemErrWriter::write(out); } void LogLog::emit(const std::exception& ex) { LogString out(LOG4CXX_STR("log4cxx: ")); const char* raw = ex.what(); if (raw != 0) { Transcoder::decode(raw, out); } else { out.append(LOG4CXX_STR("std::exception::what() == null")); } out.append(1, (logchar) 0x0A); SystemErrWriter::write(out); } apache-log4cxx-1.3.1/src/main/cpp/loggermatchfilter.cpp0000644000175100001770000000537514721727031022411 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::filter; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; #define priv static_cast(m_priv.get()) struct LoggerMatchFilter::LoggerMatchFilterPrivate : public FilterPrivate { LoggerMatchFilterPrivate() : FilterPrivate(), acceptOnMatch(true), loggerToMatch(LOG4CXX_STR("root")) {} bool acceptOnMatch; LogString loggerToMatch; }; IMPLEMENT_LOG4CXX_OBJECT(LoggerMatchFilter) LoggerMatchFilter::LoggerMatchFilter() : Filter(std::make_unique()) { } LoggerMatchFilter::~LoggerMatchFilter() {} void LoggerMatchFilter::setLoggerToMatch(const LogString& value) { priv->loggerToMatch = value; } LogString LoggerMatchFilter::getLoggerToMatch() const { return priv->loggerToMatch; } void LoggerMatchFilter::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("LOGGERTOMATCH"), LOG4CXX_STR("loggertomatch"))) { setLoggerToMatch(value); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("ACCEPTONMATCH"), LOG4CXX_STR("acceptonmatch"))) { priv->acceptOnMatch = OptionConverter::toBoolean(value, priv->acceptOnMatch); } } Filter::FilterDecision LoggerMatchFilter::decide( const spi::LoggingEventPtr& event) const { bool matchOccured = priv->loggerToMatch == event->getLoggerName(); if (matchOccured) { if (priv->acceptOnMatch) { return Filter::ACCEPT; } else { return Filter::DENY; } } else { return Filter::NEUTRAL; } } void LoggerMatchFilter::setAcceptOnMatch(bool acceptOnMatch1) { priv->acceptOnMatch = acceptOnMatch1; } bool LoggerMatchFilter::getAcceptOnMatch() const { return priv->acceptOnMatch; } apache-log4cxx-1.3.1/src/main/cpp/threadusernamepatternconverter.cpp0000644000175100001770000000330714721727031025235 0ustar runnerdocker/* * 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. */ #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::pattern; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(ThreadUsernamePatternConverter) ThreadUsernamePatternConverter::ThreadUsernamePatternConverter() : LoggingEventPatternConverter(LOG4CXX_STR("Thread Name"), LOG4CXX_STR("Thread Name")) { } PatternConverterPtr ThreadUsernamePatternConverter::newInstance( const std::vector& /* options */) { static WideLife def = std::make_shared(); return def; } void ThreadUsernamePatternConverter::format( const LoggingEventPtr& event, LogString& toAppendTo, Pool& /* p */) const { toAppendTo.append(event->getThreadUserName()); } apache-log4cxx-1.3.1/src/main/cpp/locationinfo.cpp0000644000175100001770000001002114721727031021353 0ustar runnerdocker/* * 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. */ #include #include #include using namespace ::LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; /** When location information is not available the constant NA is returned. Current value of this string constant is ?. */ const char* const LocationInfo::NA = "?"; const char* const LocationInfo::NA_METHOD = "?::?"; const LocationInfo& LocationInfo::getLocationUnavailable() { static const WideLife unavailable; return unavailable; } /** * Constructor. * @remarks Used by LOG4CXX_LOCATION to generate * location info for current code site */ LocationInfo::LocationInfo( const char* const fileName1, const char* const shortFileName1, const char* const methodName1, int lineNumber1 ) : lineNumber( lineNumber1 ), fileName( fileName1 ? fileName1 : LocationInfo::NA ), shortFileName(shortFileName1 ? shortFileName1 : LocationInfo::NA ), methodName( methodName1 ? methodName1 : LocationInfo::NA_METHOD ) { } /** * Default constructor. */ LocationInfo::LocationInfo() : lineNumber( -1 ), fileName(LocationInfo::NA), shortFileName(LocationInfo::NA), methodName(LocationInfo::NA_METHOD) { } /** * Copy constructor. * @param src source location */ LocationInfo::LocationInfo( const LocationInfo& src ) : lineNumber( src.lineNumber ), fileName( src.fileName ), shortFileName( src.shortFileName ), methodName( src.methodName ) { } /** * Assignment operator. * @param src source location */ LocationInfo& LocationInfo::operator = ( const LocationInfo& src ) { fileName = src.fileName; shortFileName = src.shortFileName; methodName = src.methodName; lineNumber = src.lineNumber; return * this; } /** * Resets location info to default state. */ void LocationInfo::clear() { fileName = NA; shortFileName = NA; methodName = NA_METHOD; lineNumber = -1; } /** * Return the file name of the caller. * @returns file name, may be null. */ const char* LocationInfo::getFileName() const { return fileName; } const char* LocationInfo::getShortFileName() const{ return shortFileName; } /** * Returns the line number of the caller. * @returns line number, -1 if not available. */ int LocationInfo::getLineNumber() const { return lineNumber; } /** Returns the method name of the caller. */ const std::string LocationInfo::getMethodName() const { std::string tmp(methodName); size_t parenPos = tmp.find('('); if (parenPos != std::string::npos) { tmp.erase(parenPos); } size_t colonPos = tmp.rfind("::"); if (colonPos != std::string::npos) { tmp.erase(0, colonPos + 2); } else { size_t spacePos = tmp.find(' '); if (spacePos != std::string::npos) { tmp.erase(0, spacePos + 1); } } return tmp; } const std::string LocationInfo::getClassName() const { std::string tmp(methodName); size_t parenPos = tmp.find('('); if (parenPos != std::string::npos) { tmp.erase(parenPos); } size_t colonPos = tmp.rfind("::"); if (colonPos != std::string::npos) { tmp.erase(colonPos); size_t spacePos = tmp.find_last_of(' '); if (spacePos != std::string::npos) { tmp.erase(0, spacePos + 1); } return tmp; } tmp.erase(0, tmp.length() ); return tmp; } apache-log4cxx-1.3.1/src/main/cpp/transcoder.cpp0000644000175100001770000003262614721727031021052 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #include #include #include #include #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include #if LOG4CXX_CFSTRING_API #include #endif using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; void Transcoder::decodeUTF8(const std::string& src, LogString& dst) { std::string::const_iterator iter = src.begin(); while (iter != src.end()) { unsigned int sv = decode(src, iter); if (sv != 0xFFFF) { encode(sv, dst); } else { dst.append(1, LOSSCHAR); iter++; } } } void Transcoder::encodeUTF8(const LogString& src, std::string& dst) { #if LOG4CXX_LOGCHAR_IS_UTF8 dst.append(src); #else LogString::const_iterator iter = src.begin(); while (iter != src.end()) { unsigned int sv = decode(src, iter); if (sv != 0xFFFF) { encode(sv, dst); } else { dst.append(1, LOSSCHAR); iter++; } } #endif } char* Transcoder::encodeUTF8(const LogString& src, Pool& p) { #if LOG4CXX_LOGCHAR_IS_UTF8 return p.pstrdup(src); #else std::string tmp; encodeUTF8(src, tmp); return p.pstrdup(tmp); #endif } void Transcoder::encodeUTF8(unsigned int sv, ByteBuffer& dst) { size_t bytes = encodeUTF8(sv, dst.current()); dst.position(dst.position() + bytes); } size_t Transcoder::encodeUTF8(unsigned int ch, char* dst) { if (ch < 0x80) { dst[0] = (char) ch; return 1; } else if (ch < 0x800) { dst[0] = (char) (0xC0 + (ch >> 6)); dst[1] = (char) (0x80 + (ch & 0x3F)); return 2; } else if (ch < 0x10000) { dst[0] = (char) (0xE0 + (ch >> 12)); dst[1] = (char) (0x80 + ((ch >> 6) & 0x3F)); dst[2] = (char) (0x80 + (ch & 0x3F)); return 3; } else if (ch <= 0x10FFFF) { dst[0] = (char) (0xF0 + (ch >> 18)); dst[1] = (char) (0x80 + ((ch >> 12) & 0x3F)); dst[2] = (char) (0x80 + ((ch >> 6) & 0x3F)); dst[3] = (char) (0x80 + (ch & 0x3F)); return 4; } else { // // output UTF-8 encoding of 0xFFFF // dst[0] = (char) 0xEF; dst[1] = (char) 0xBF; dst[2] = (char) 0xBF; return 3; } } void Transcoder::encodeUTF16BE(unsigned int sv, ByteBuffer& dst) { size_t bytes = encodeUTF16BE(sv, dst.current()); dst.position(dst.position() + bytes); } size_t Transcoder::encodeUTF16BE(unsigned int ch, char* dst) { if (ch <= 0xFFFF) { dst[0] = (char) (ch >> 8); dst[1] = (char) (ch & 0xFF); return 2; } if (ch <= 0x10FFFF) { unsigned char w = (unsigned char) ((ch >> 16) - 1); dst[0] = (char) (0xD8 + (w >> 2)); dst[1] = (char) (((w & 0x03) << 6) + ((ch >> 10) & 0x3F)); dst[2] = (char) (0xDC + ((ch & 0x30) >> 4)); dst[3] = (char) (ch & 0xFF); return 4; } dst[0] = dst[1] = (char) 0xFF; return 2; } void Transcoder::encodeUTF16LE(unsigned int sv, ByteBuffer& dst) { size_t bytes = encodeUTF16LE(sv, dst.current()); dst.position(dst.position() + bytes); } size_t Transcoder::encodeUTF16LE(unsigned int ch, char* dst) { if (ch <= 0xFFFF) { dst[1] = (char) (ch >> 8); dst[0] = (char) (ch & 0xFF); return 2; } if (ch <= 0x10FFFF) { unsigned char w = (unsigned char) ((ch >> 16) - 1); dst[1] = (char) (0xD8 + (w >> 2)); dst[0] = (char) (((w & 0x03) << 6) + ((ch >> 10) & 0x3F)); dst[3] = (char) (0xDC + ((ch & 0x30) >> 4)); dst[2] = (char) (ch & 0xFF); return 4; } dst[0] = dst[1] = (char) 0xFF; return 2; } unsigned int Transcoder::decode(const std::string& src, std::string::const_iterator& iter) { std::string::const_iterator start(iter); unsigned char ch1 = *(iter++); if (ch1 <= 0x7F) { return ch1; } // // should not have continuation character here // if ((ch1 & 0xC0) != 0x80 && iter != src.end()) { unsigned char ch2 = *(iter++); // // should be continuation if ((ch2 & 0xC0) != 0x80) { iter = start; return 0xFFFF; } if ((ch1 & 0xE0) == 0xC0) { if ((ch2 & 0xC0) == 0x80) { unsigned int rv = ((ch1 & 0x1F) << 6) + (ch2 & 0x3F); if (rv >= 0x80) { return rv; } } iter = start; return 0xFFFF; } if (iter != src.end()) { unsigned char ch3 = *(iter++); // // should be continuation // if ((ch3 & 0xC0) != 0x80) { iter = start; return 0xFFFF; } if ((ch1 & 0xF0) == 0xE0) { unsigned rv = ((ch1 & 0x0F) << 12) + ((ch2 & 0x3F) << 6) + (ch3 & 0x3F); if (rv <= 0x800) { iter = start; return 0xFFFF; } return rv; } if (iter != src.end()) { unsigned char ch4 = *(iter++); if ((ch4 & 0xC0) != 0x80) { iter = start; return 0xFFFF; } unsigned int rv = ((ch1 & 0x07) << 18) + ((ch2 & 0x3F) << 12) + ((ch3 & 0x3F) << 6) + (ch4 & 0x3F); if (rv > 0xFFFF) { return rv; } } } } iter = start; return 0xFFFF; } void Transcoder::encode(unsigned int sv, std::string& dst) { char tmp[8]; size_t bytes = encodeUTF8(sv, tmp); dst.append(tmp, bytes); } void Transcoder::decode(const std::string& src, LogString& dst) { #if LOG4CXX_CHARSET_UTF8 && LOG4CXX_LOGCHAR_IS_UTF8 dst.append(src); #else static CharsetDecoderPtr decoder(CharsetDecoder::getDefaultDecoder()); dst.reserve(dst.size() + src.size()); std::string::const_iterator iter = src.begin(); #if !LOG4CXX_CHARSET_EBCDIC for (; iter != src.end() && ((unsigned char) *iter) < 0x80; iter++) { dst.append(1, *iter); } #endif if (iter != src.end()) { size_t offset = iter - src.begin(); ByteBuffer buf(const_cast(src.data() + offset), src.size() - offset); while (buf.remaining() > 0) { log4cxx_status_t stat = decoder->decode(buf, dst); if (CharsetDecoder::isError(stat)) { dst.append(1, LOSSCHAR); buf.position(buf.position() + 1); } } decoder->decode(buf, dst); } #endif } char* Transcoder::encode(const LogString& src, Pool& p) { #if LOG4CXX_CHARSET_UTF8 && LOG4CXX_LOGCHAR_IS_UTF8 return p.pstrdup(src); #else std::string tmp; encode(src, tmp); return p.pstrdup(tmp); #endif } void Transcoder::encode(const LogString& src, std::string& dst) { #if LOG4CXX_CHARSET_UTF8 && LOG4CXX_LOGCHAR_IS_UTF8 dst.append(src); #else static CharsetEncoderPtr encoder(CharsetEncoder::getDefaultEncoder()); dst.reserve(dst.size() + src.size()); LogString::const_iterator iter = src.begin(); #if !LOG4CXX_CHARSET_EBCDIC for (; iter != src.end() && ((unsigned int) *iter) < 0x80; iter++) { dst.append(1, *iter); } #endif if (iter != src.end()) { char buf[BUFSIZE]; ByteBuffer out(buf, BUFSIZE); while (iter != src.end()) { log4cxx_status_t stat = encoder->encode(src, iter, out); out.flip(); dst.append(out.data(), out.limit()); out.clear(); if (CharsetEncoder::isError(stat)) { dst.append(1, LOSSCHAR); iter++; } } encoder->encode(src, iter, out); } #endif } template static unsigned int decodeUTF16(const String& in, Iterator& iter) { unsigned int ch1 = *iter; // // if not surrogate pair // if (ch1 < 0xD800 || ch1 > 0xDFFF) { // // then advance iterator and return wchar_t value // if (ch1 != 0xFFFF) { iter++; } return ch1; } else if (ch1 < 0xDC00) { // // started with high-surrogate value // if there is an additional wchar_t Iterator iter2 = iter + 1; if (iter2 != in.end()) { unsigned int ch2 = *iter2; // // if it is a matching low surrogate then // advance the iterator and return the scalar value if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) { iter += 2; return (ch1 - 0xD800) * 0x400 + (ch2 - 0xDC00) + 0x10000; } } } // // unrecognized value, do not advance iterator // return 0xFFFF; } template static void encodeUTF16(unsigned int sv, String& dst) { if (sv < 0x10000) { dst.append(1, sv); } else { unsigned char u = (unsigned char) (sv >> 16); unsigned char w = (unsigned char) (u - 1); unsigned short hs = (0xD800 + ((w & 0xF) << 6) + ((sv & 0xFFFF) >> 10)); unsigned short ls = (0xDC00 + (sv & 0x3FF)); dst.append(1, hs); dst.append(1, ls); } } #if LOG4CXX_WCHAR_T_API || LOG4CXX_LOGCHAR_IS_WCHAR_T || defined(WIN32) || defined(_WIN32) void Transcoder::decode(const std::wstring& src, LogString& dst) { #if LOG4CXX_LOGCHAR_IS_WCHAR_T dst.append(src, len); #else std::wstring::const_iterator i = src.begin(); while (i != src.end()) { unsigned int cp = decode(src, i); if (cp != 0xFFFF) { encode(cp, dst); } else { dst.append(1, LOSSCHAR); i++; } } #endif } void Transcoder::encode(const LogString& src, std::wstring& dst) { #if LOG4CXX_LOGCHAR_IS_WCHAR_T dst.append(src); #else for (LogString::const_iterator i = src.begin(); i != src.end();) { unsigned int cp = Transcoder::decode(src, i); if (cp != 0xFFFF) { encode(cp, dst); } else { dst.append(1, LOSSCHAR); i++; } } #endif } wchar_t* Transcoder::wencode(const LogString& src, Pool& p) { #if LOG4CXX_LOGCHAR_IS_WCHAR_T std::wstring& tmp = src; #else std::wstring tmp; encode(src, tmp); #endif wchar_t* dst = (wchar_t*) p.palloc((tmp.length() + 1) * sizeof(wchar_t)); dst[tmp.length()] = 0; std::memcpy(dst, tmp.data(), tmp.length() * sizeof(wchar_t)); return dst; } unsigned int Transcoder::decode(const std::wstring& in, std::wstring::const_iterator& iter) { #if defined(__STDC_ISO_10646__) return *(iter++); #else return decodeUTF16(in, iter); #endif } void Transcoder::encode(unsigned int sv, std::wstring& dst) { #if defined(__STDC_ISO_10646__) dst.append(1, sv); #else if (sizeof(wchar_t) == 4) { dst.append(1, sv); } else { encodeUTF16(sv, dst); } #endif } #endif #if LOG4CXX_UNICHAR_API || LOG4CXX_LOGCHAR_IS_UNICHAR void Transcoder::decode(const std::basic_string& src, LogString& dst) { #if LOG4CXX_LOGCHAR_IS_UNICHAR dst.append(src); #else for (std::basic_string::const_iterator i = src.begin(); i != src.end();) { unsigned int cp = decode(src, i); encode(cp, dst); } #endif } void Transcoder::encode(const LogString& src, std::basic_string& dst) { #if LOG4CXX_LOGCHAR_IS_UNICHAR dst.append(src); #else for (LogString::const_iterator i = src.begin(); i != src.end();) { unsigned int cp = decode(src, i); encode(cp, dst); } #endif } unsigned int Transcoder::decode(const std::basic_string& in, std::basic_string::const_iterator& iter) { return decodeUTF16(in, iter); } void Transcoder::encode(unsigned int sv, std::basic_string& dst) { encodeUTF16(sv, dst); } #endif #if LOG4CXX_CFSTRING_API void Transcoder::decode(const CFStringRef& src, LogString& dst) { auto length = CFStringGetLength(src); #if defined(_DEBUG) if (LogLog::isDebugEnabled()) { Pool pool; LogString msg(LOG4CXX_STR("Transcoder::decodeCFString")); msg += LOG4CXX_STR(" length "); StringHelper::toString((size_t)length, pool, msg); LogLog::debug(msg); } #endif if (length > 0) { std::vector tmp(length); CFStringGetCharacters(src, CFRangeMake(0, length), &tmp[0]); for (auto i = tmp.begin(); i != tmp.end(); ) { unsigned int cp = decodeUTF16(tmp, i); encode(cp, dst); } } } CFStringRef Transcoder::encode(const LogString& src) { std::basic_string tmp; for (auto ch : src) encodeUTF16(ch, tmp); return CFStringCreateWithCharacters(kCFAllocatorDefault, tmp.data(), tmp.size()); } #endif // #if LOG4CXX_CFSTRING_API logchar Transcoder::decode(char val) { #if LOG4CXX_CHARSET_EBCDIC LogString dst; Transcoder::decode(std::string(1, val), dst); return dst[0]; #else return val; #endif } LogString Transcoder::decode(const char* val) { #if LOG4CXX_LOGCHAR_IS_UTF8 && !LOG4CXX_CHARSET_EBCDIC return val; #else LogString dst; Transcoder::decode(val, dst); return dst; #endif } std::string Transcoder::encodeCharsetName(const LogString& val) { char asciiTable[] = { ' ', '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~' }; std::string out; for (auto& item : val) { if (item >= 0x20 && item < 0x7F) { out.append(1, asciiTable[item - 0x20]); } else { out.append(1, LOSSCHAR); } } return out; } apache-log4cxx-1.3.1/src/main/cpp/smtpappender.cpp0000644000175100001770000004357714721727031021417 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #include #include #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; using namespace LOG4CXX_NS::net; using namespace LOG4CXX_NS::spi; #if LOG4CXX_HAVE_LIBESMTP #include #include #endif namespace LOG4CXX_NS { namespace net { // // The following two classes implement an C++ SMTP wrapper over libesmtp. // The same signatures could be implemented over different SMTP implementations // or libesmtp could be combined with libgmime to enable support for non-ASCII // content. #if LOG4CXX_HAVE_LIBESMTP /** * SMTP Session. */ class SMTPSession { public: /** * Create new instance. */ SMTPSession(const LogString& smtpHost, int smtpPort, const LogString& smtpUsername, const LogString& smtpPassword, Pool& p) : session(0), authctx(0), user(toAscii(smtpUsername, p)), pwd(toAscii(smtpPassword, p)) { auth_client_init(); session = smtp_create_session(); if (session == 0) { throw Exception("Could not initialize session."); } std::string host(toAscii(smtpHost, p)); host.append(1, ':'); host.append(p.itoa(smtpPort)); smtp_set_server(session, host.c_str()); authctx = auth_create_context(); auth_set_mechanism_flags(authctx, AUTH_PLUGIN_PLAIN, 0); auth_set_interact_cb(authctx, authinteract, (void*) this); if (*user || *pwd) { smtp_auth_set_context(session, authctx); } } ~SMTPSession() { smtp_destroy_session(session); auth_destroy_context(authctx); } void send(Pool& p) { int status = smtp_start_session(session); if (!status) { size_t bufSize = 128; char* buf = p.pstralloc(bufSize); smtp_strerror(smtp_errno(), buf, bufSize); throw Exception(buf); } } operator smtp_session_t() { return session; } static char* toAscii(const LogString& str, Pool& p) { char* buf = p.pstralloc(str.length() + 1); char* current = buf; for (unsigned int c : str) { if (c > 0x7F) { c = '?'; } *current++ = c; } *current = 0; return buf; } private: SMTPSession(SMTPSession&); SMTPSession& operator=(SMTPSession&); smtp_session_t session; auth_context_t authctx; char* user; char* pwd; /** * This method is called if the SMTP server requests authentication. */ static int authinteract(auth_client_request_t request, char** result, int fields, void* arg) { SMTPSession* pThis = (SMTPSession*) arg; for (int i = 0; i < fields; i++) { int flag = request[i].flags & 0x07; if (flag == AUTH_USER) { result[i] = pThis->user; } else if (flag == AUTH_PASS) { result[i] = pThis->pwd; } } return 1; } }; /** * A message in an SMTP session. */ class SMTPMessage { public: SMTPMessage(SMTPSession& session, const LogString& from, const LogString& to, const LogString& cc, const LogString& bcc, const LogString& subject, const LogString msg, Pool& p) { message = smtp_add_message(session); current_len = msg.length(); body = current = toMessage(msg, p); messagecbState = 0; smtp_set_reverse_path(message, toAscii(from, p)); addRecipients(to, "To", p); addRecipients(cc, "Cc", p); addRecipients(bcc, "Bcc", p); if (!subject.empty()) { smtp_set_header(message, "Subject", toAscii(subject, p)); } smtp_set_messagecb(message, messagecb, this); } ~SMTPMessage() { } private: SMTPMessage(const SMTPMessage&); SMTPMessage& operator=(const SMTPMessage&); smtp_message_t message; const char* body; const char* current; size_t current_len; int messagecbState; void addRecipients(const LogString& addresses, const char* field, Pool& p) { if (!addresses.empty()) { char* str = p.pstrdup(toAscii(addresses, p));; smtp_set_header(message, field, NULL, str); char* last; for (char* next = apr_strtok(str, ",", &last); next; next = apr_strtok(NULL, ",", &last)) { smtp_add_recipient(message, next); } } } static const char* toAscii(const LogString& str, Pool& p) { return SMTPSession::toAscii(str, p); } /** * Message bodies can only contain US-ASCII characters and * CR and LFs can only occur together. */ static const char* toMessage(const LogString& str, Pool& p) { // // count the number of carriage returns and line feeds // int feedCount = 0; for (size_t pos = str.find_first_of(LOG4CXX_STR("\n\r")); pos != LogString::npos; pos = str.find_first_of(LOG4CXX_STR("\n\r"), ++pos)) { feedCount++; } // // allocate sufficient space for the modified message char* retval = p.pstralloc(str.length() + feedCount + 1); char* current = retval; char* startOfLine = current; unsigned int ignoreChar = 0; // // iterator through message // for (unsigned int c : str) { // // replace non-ASCII characters with '?' // if (c > 0x7F) { *current++ = 0x3F; // '?' } else if (c == 0x0A || c == 0x0D) { // // replace any stray CR or LF with CRLF // reset start of line if (c == ignoreChar && current == startOfLine) ignoreChar = 0; else { *current++ = 0x0D; *current++ = 0x0A; startOfLine = current; ignoreChar = (c == 0x0A ? 0x0D : 0x0A); } } else { // // truncate any lines to 1000 characters (including CRLF) // as required by RFC. if (current < startOfLine + 998) { *current++ = (char) c; } } } *current = 0; return retval; } /** * Callback for message. */ static const char* messagecb(void** ctx, int* len, void* arg) { *ctx = 0; const char* retval = 0; SMTPMessage* pThis = (SMTPMessage*) arg; // rewind message if (len == NULL) { pThis->current = pThis->body; } else { // we are asked for headers, but we don't have any if ((pThis->messagecbState)++ == 0) { return NULL; } if (pThis->current) { *len = strnlen_s(pThis->current, pThis->current_len); } retval = pThis->current; pThis->current = 0; } return retval; } }; #endif class LOG4CXX_EXPORT DefaultEvaluator : public virtual spi::TriggeringEventEvaluator, public virtual helpers::Object { public: DECLARE_LOG4CXX_OBJECT(DefaultEvaluator) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(DefaultEvaluator) LOG4CXX_CAST_ENTRY(spi::TriggeringEventEvaluator) END_LOG4CXX_CAST_MAP() DefaultEvaluator(); /** Is this event the e-mail triggering event?

This method returns true, if the event level has ERROR level or higher. Otherwise it returns false. */ bool isTriggeringEvent(const spi::LoggingEventPtr& event) override; private: DefaultEvaluator(const DefaultEvaluator&); DefaultEvaluator& operator=(const DefaultEvaluator&); }; // class DefaultEvaluator } } IMPLEMENT_LOG4CXX_OBJECT(DefaultEvaluator) IMPLEMENT_LOG4CXX_OBJECT(SMTPAppender) struct SMTPAppender::SMTPPriv : public AppenderSkeletonPrivate { SMTPPriv() : AppenderSkeletonPrivate(), smtpPort(25), bufferSize(512), locationInfo(false), cb(bufferSize), evaluator(new DefaultEvaluator()) {} SMTPPriv(spi::TriggeringEventEvaluatorPtr evaluator) : AppenderSkeletonPrivate(), smtpPort(25), bufferSize(512), locationInfo(false), cb(bufferSize), evaluator(evaluator) {} LogString to; LogString cc; LogString bcc; LogString from; LogString subject; LogString smtpHost; LogString smtpUsername; LogString smtpPassword; int smtpPort; int bufferSize; // 512 bool locationInfo; helpers::CyclicBuffer cb; spi::TriggeringEventEvaluatorPtr evaluator; }; #define _priv static_cast(m_priv.get()) DefaultEvaluator::DefaultEvaluator() { } bool DefaultEvaluator::isTriggeringEvent(const spi::LoggingEventPtr& event) { return event->getLevel()->isGreaterOrEqual(Level::getError()); } SMTPAppender::SMTPAppender() : AppenderSkeleton (std::make_unique()) { } /** Use evaluator passed as parameter as the TriggeringEventEvaluator for this SMTPAppender. */ SMTPAppender::SMTPAppender(spi::TriggeringEventEvaluatorPtr evaluator) : AppenderSkeleton (std::make_unique(evaluator)) { } SMTPAppender::~SMTPAppender() { finalize(); } bool SMTPAppender::requiresLayout() const { return true; } LogString SMTPAppender::getFrom() const { return _priv->from; } void SMTPAppender::setFrom(const LogString& newVal) { _priv->from = newVal; } LogString SMTPAppender::getSubject() const { return _priv->subject; } void SMTPAppender::setSubject(const LogString& newVal) { _priv->subject = newVal; } LogString SMTPAppender::getSMTPHost() const { return _priv->smtpHost; } void SMTPAppender::setSMTPHost(const LogString& newVal) { _priv->smtpHost = newVal; } int SMTPAppender::getSMTPPort() const { return _priv->smtpPort; } void SMTPAppender::setSMTPPort(int newVal) { _priv->smtpPort = newVal; } bool SMTPAppender::getLocationInfo() const { return _priv->locationInfo; } void SMTPAppender::setLocationInfo(bool newVal) { _priv->locationInfo = newVal; } LogString SMTPAppender::getSMTPUsername() const { return _priv->smtpUsername; } void SMTPAppender::setSMTPUsername(const LogString& newVal) { _priv->smtpUsername = newVal; } LogString SMTPAppender::getSMTPPassword() const { return _priv->smtpPassword; } void SMTPAppender::setSMTPPassword(const LogString& newVal) { _priv->smtpPassword = newVal; } void SMTPAppender::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("BUFFERSIZE"), LOG4CXX_STR("buffersize"))) { setBufferSize(OptionConverter::toInt(value, 512)); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("EVALUATORCLASS"), LOG4CXX_STR("evaluatorclass"))) { setEvaluatorClass(value); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("FROM"), LOG4CXX_STR("from"))) { setFrom(value); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("SMTPHOST"), LOG4CXX_STR("smtphost"))) { setSMTPHost(value); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("SMTPUSERNAME"), LOG4CXX_STR("smtpusername"))) { setSMTPUsername(value); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("SMTPPASSWORD"), LOG4CXX_STR("smtppassword"))) { setSMTPPassword(value); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("SUBJECT"), LOG4CXX_STR("subject"))) { setSubject(value); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("TO"), LOG4CXX_STR("to"))) { setTo(value); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("CC"), LOG4CXX_STR("cc"))) { setCc(value); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("BCC"), LOG4CXX_STR("bcc"))) { setBcc(value); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("SMTPPORT"), LOG4CXX_STR("smtpport"))) { setSMTPPort(OptionConverter::toInt(value, 25)); } else { AppenderSkeleton::setOption(option, value); } } bool SMTPAppender::asciiCheck(const LogString& value, const LogString& field) { for (unsigned int item : value) { if (0x7F < item) { LogLog::warn(field + LOG4CXX_STR(" contains non-ASCII character")); return false; } } return true; } /** Activate the specified options, such as the smtp host, the recipient, from, etc. */ void SMTPAppender::activateOptions(Pool& p) { bool activate = true; if (_priv->layout == 0) { _priv->errorHandler->error(LOG4CXX_STR("No layout set for appender named [") + _priv->name + LOG4CXX_STR("].")); activate = false; } if (_priv->evaluator == 0) { _priv->errorHandler->error(LOG4CXX_STR("No TriggeringEventEvaluator is set for appender [") + _priv->name + LOG4CXX_STR("].")); activate = false; } if (_priv->smtpHost.empty()) { _priv->errorHandler->error(LOG4CXX_STR("No smtpHost is set for appender [") + _priv->name + LOG4CXX_STR("].")); activate = false; } if (_priv->to.empty() && _priv->cc.empty() && _priv->bcc.empty()) { _priv->errorHandler->error(LOG4CXX_STR("No recipient address is set for appender [") + _priv->name + LOG4CXX_STR("].")); activate = false; } activate &= asciiCheck(_priv->to, LOG4CXX_STR("to")); activate &= asciiCheck(_priv->cc, LOG4CXX_STR("cc")); activate &= asciiCheck(_priv->bcc, LOG4CXX_STR("bcc")); activate &= asciiCheck(_priv->from, LOG4CXX_STR("from")); #if !LOG4CXX_HAVE_LIBESMTP _priv->errorHandler->error(LOG4CXX_STR("log4cxx built without SMTP support.")); activate = false; #endif if (activate) { AppenderSkeleton::activateOptions(p); } } /** Perform SMTPAppender specific appending actions, mainly adding the event to a cyclic buffer and checking if the event triggers an e-mail to be sent. */ void SMTPAppender::append(const spi::LoggingEventPtr& event, Pool& p) { if (!checkEntryConditions()) { return; } // Get a copy of this thread's diagnostic context event->LoadDC(); _priv->cb.add(event); if (_priv->evaluator->isTriggeringEvent(event)) { sendBuffer(p); } } /** This method determines if there is a sense in attempting to append.

It checks whether there is a set output target and also if there is a set layout. If these checks fail, then the boolean value false is returned. */ bool SMTPAppender::checkEntryConditions() { #if LOG4CXX_HAVE_LIBESMTP if ((_priv->to.empty() && _priv->cc.empty() && _priv->bcc.empty()) || _priv->from.empty() || _priv->smtpHost.empty()) { _priv->errorHandler->error(LOG4CXX_STR("Message not configured.")); return false; } if (_priv->evaluator == 0) { _priv->errorHandler->error(LOG4CXX_STR("No TriggeringEventEvaluator is set for appender [") + _priv->name + LOG4CXX_STR("].")); return false; } if (_priv->layout == 0) { _priv->errorHandler->error(LOG4CXX_STR("No layout set for appender named [") + _priv->name + LOG4CXX_STR("].")); return false; } return true; #else return false; #endif } void SMTPAppender::close() { _priv->closed = true; } LogString SMTPAppender::getTo() const { return _priv->to; } void SMTPAppender::setTo(const LogString& addressStr) { _priv->to = addressStr; } LogString SMTPAppender::getCc() const { return _priv->cc; } void SMTPAppender::setCc(const LogString& addressStr) { _priv->cc = addressStr; } LogString SMTPAppender::getBcc() const { return _priv->bcc; } void SMTPAppender::setBcc(const LogString& addressStr) { _priv->bcc = addressStr; } /** Send the contents of the cyclic buffer as an e-mail message. */ void SMTPAppender::sendBuffer(Pool& p) { #if LOG4CXX_HAVE_LIBESMTP // Note: this code already owns the monitor for this // appender. This frees us from needing to synchronize on 'cb'. try { LogString sbuf; _priv->layout->appendHeader(sbuf, p); int len = _priv->cb.length(); for (int i = 0; i < len; i++) { LoggingEventPtr event = _priv->cb.get(); _priv->layout->format(sbuf, event, p); } _priv->layout->appendFooter(sbuf, p); SMTPSession session(_priv->smtpHost, _priv->smtpPort, _priv->smtpUsername, _priv->smtpPassword, p); SMTPMessage message(session, _priv->from, _priv->to, _priv->cc, _priv->bcc, _priv->subject, sbuf, p); session.send(p); } catch (std::exception& e) { _priv->errorHandler->error(LOG4CXX_STR("Error occured while sending e-mail to [") + _priv->smtpHost + LOG4CXX_STR("]."), e, 0); } #endif } /** Returns value of the EvaluatorClass option. */ LogString SMTPAppender::getEvaluatorClass() { return _priv->evaluator == 0 ? LogString() : _priv->evaluator->getClass().getName(); } LOG4CXX_NS::spi::TriggeringEventEvaluatorPtr SMTPAppender::getEvaluator() const { return _priv->evaluator; } void SMTPAppender::setEvaluator(LOG4CXX_NS::spi::TriggeringEventEvaluatorPtr& trigger) { _priv->evaluator = trigger; } /** The BufferSize option takes a positive integer representing the maximum number of logging events to collect in a cyclic buffer. When the BufferSize is reached, oldest events are deleted as new events are added to the buffer. By default the size of the cyclic buffer is 512 events. */ void SMTPAppender::setBufferSize(int sz) { _priv->bufferSize = sz; _priv->cb.resize(sz); } /** The EvaluatorClass option takes a string value representing the name of the class implementing the {@link TriggeringEventEvaluator} interface. A corresponding object will be instantiated and assigned as the triggering event evaluator for the SMTPAppender. */ void SMTPAppender::setEvaluatorClass(const LogString& value) { ObjectPtr obj = ObjectPtr(Loader::loadClass(value).newInstance()); _priv->evaluator = LOG4CXX_NS::cast(obj); } int SMTPAppender::getBufferSize() const { return _priv->bufferSize; } apache-log4cxx-1.3.1/src/main/cpp/levelpatternconverter.cpp0000644000175100001770000000464414721727031023342 0ustar runnerdocker/* * 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. */ #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::pattern; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(LevelPatternConverter) LevelPatternConverter::LevelPatternConverter() : LoggingEventPatternConverter(LOG4CXX_STR("Level"), LOG4CXX_STR("level")) { } PatternConverterPtr LevelPatternConverter::newInstance( const std::vector& /* options */) { static WideLife def = std::make_shared(); return def; } void LevelPatternConverter::format( const LoggingEventPtr& event, LogString& toAppendTo, LOG4CXX_NS::helpers::Pool& /* p */) const { toAppendTo.append(event->getLevel()->toString()); } /** * {@inheritDoc} */ LogString LevelPatternConverter::getStyleClass(const ObjectPtr& obj) const { LoggingEventPtr e = LOG4CXX_NS::cast(obj); if (e != NULL) { int lint = e->getLevel()->toInt(); switch (lint) { case Level::TRACE_INT: return LOG4CXX_STR("level trace"); case Level::DEBUG_INT: return LOG4CXX_STR("level debug"); case Level::INFO_INT: return LOG4CXX_STR("level info"); case Level::WARN_INT: return LOG4CXX_STR("level warn"); case Level::ERROR_INT: return LOG4CXX_STR("level error"); case Level::FATAL_INT: return LOG4CXX_STR("level fatal"); default: return LogString(LOG4CXX_STR("level ")) + e->getLevel()->toString(); } } return LOG4CXX_STR("level"); } apache-log4cxx-1.3.1/src/main/cpp/locale.cpp0000644000175100001770000000377714721727031020152 0ustar runnerdocker/* * 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. */ #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; struct Locale::LocalePrivate { LocalePrivate(const LogString& language1) : language(language1) { } LocalePrivate(const LogString& language1, const LogString& country1) : language(language1), country(country1) { } LocalePrivate(const LogString& language1, const LogString& country1, const LogString& variant1) : language(language1), country(country1), variant(variant1) { } const LogString language; const LogString country; const LogString variant; }; Locale::Locale(const LogString& language1) : m_priv(std::make_unique(language1)) { } Locale::Locale(const LogString& language1, const LogString& country1) : m_priv(std::make_unique(language1, country1)) { } Locale::Locale(const LogString& language1, const LogString& country1, const LogString& variant1) : m_priv(std::make_unique(language1, country1, variant1)) { } Locale::~Locale() {} const LogString& Locale::getLanguage() const { return m_priv->language; } const LogString& Locale::getCountry() const { return m_priv->country; } const LogString& Locale::getVariant() const { return m_priv->variant; } apache-log4cxx-1.3.1/src/main/cpp/syslogappender.cpp0000644000175100001770000002574414721727031021750 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include #include #define LOG_UNDEF -1 using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; using namespace LOG4CXX_NS::net; IMPLEMENT_LOG4CXX_OBJECT(SyslogAppender) #define _priv static_cast(m_priv.get()) SyslogAppender::SyslogAppender() : AppenderSkeleton (std::make_unique()) { this->initSyslogFacilityStr(); } SyslogAppender::SyslogAppender(const LayoutPtr& layout1, int syslogFacility1) : AppenderSkeleton (std::make_unique(layout1, syslogFacility1)) { this->initSyslogFacilityStr(); } SyslogAppender::SyslogAppender(const LayoutPtr& layout1, const LogString& syslogHost1, int syslogFacility1) : AppenderSkeleton (std::make_unique(layout1, syslogHost1, syslogFacility1)) { this->initSyslogFacilityStr(); setSyslogHost(syslogHost1); } SyslogAppender::~SyslogAppender() { finalize(); } /** Release any resources held by this SyslogAppender.*/ void SyslogAppender::close() { _priv->closed = true; if (_priv->sw) { _priv->sw = nullptr; } } void SyslogAppender::initSyslogFacilityStr() { _priv->facilityStr = getFacilityString(_priv->syslogFacility); if (_priv->facilityStr.empty()) { Pool p; LogString msg(LOG4CXX_STR("\"")); StringHelper::toString(_priv->syslogFacility, p, msg); msg.append(LOG4CXX_STR("\" is an unknown syslog facility. Defaulting to \"USER\".")); LogLog::error(msg); _priv->syslogFacility = LOG_USER; _priv->facilityStr = LOG4CXX_STR("user:"); } else { _priv->facilityStr += LOG4CXX_STR(":"); } } /** Returns the specified syslog facility as a lower-case String, e.g. "kern", "user", etc. */ LogString SyslogAppender::getFacilityString( int syslogFacility) { switch (syslogFacility) { case LOG_KERN: return LOG4CXX_STR("kern"); case LOG_USER: return LOG4CXX_STR("user"); case LOG_MAIL: return LOG4CXX_STR("mail"); case LOG_DAEMON: return LOG4CXX_STR("daemon"); case LOG_AUTH: return LOG4CXX_STR("auth"); case LOG_SYSLOG: return LOG4CXX_STR("syslog"); case LOG_LPR: return LOG4CXX_STR("lpr"); case LOG_NEWS: return LOG4CXX_STR("news"); case LOG_UUCP: return LOG4CXX_STR("uucp"); case LOG_CRON: return LOG4CXX_STR("cron"); #ifdef LOG_AUTHPRIV case LOG_AUTHPRIV: return LOG4CXX_STR("authpriv"); #endif #ifdef LOG_FTP case LOG_FTP: return LOG4CXX_STR("ftp"); #endif case LOG_LOCAL0: return LOG4CXX_STR("local0"); case LOG_LOCAL1: return LOG4CXX_STR("local1"); case LOG_LOCAL2: return LOG4CXX_STR("local2"); case LOG_LOCAL3: return LOG4CXX_STR("local3"); case LOG_LOCAL4: return LOG4CXX_STR("local4"); case LOG_LOCAL5: return LOG4CXX_STR("local5"); case LOG_LOCAL6: return LOG4CXX_STR("local6"); case LOG_LOCAL7: return LOG4CXX_STR("local7"); default: return LogString(); } } int SyslogAppender::getFacility( const LogString& s) { if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("KERN"), LOG4CXX_STR("kern"))) { return LOG_KERN; } else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("USER"), LOG4CXX_STR("user"))) { return LOG_USER; } else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("MAIL"), LOG4CXX_STR("mail"))) { return LOG_MAIL; } else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("DAEMON"), LOG4CXX_STR("daemon"))) { return LOG_DAEMON; } else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("AUTH"), LOG4CXX_STR("auth"))) { return LOG_AUTH; } else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("SYSLOG"), LOG4CXX_STR("syslog"))) { return LOG_SYSLOG; } else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("LPR"), LOG4CXX_STR("lpr"))) { return LOG_LPR; } else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("NEWS"), LOG4CXX_STR("news"))) { return LOG_NEWS; } else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("UUCP"), LOG4CXX_STR("uucp"))) { return LOG_UUCP; } else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("CRON"), LOG4CXX_STR("cron"))) { return LOG_CRON; } #ifdef LOG_AUTHPRIV else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("AUTHPRIV"), LOG4CXX_STR("authpriv"))) { return LOG_AUTHPRIV; } #endif #ifdef LOG_FTP else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("FTP"), LOG4CXX_STR("ftp"))) { return LOG_FTP; } #endif else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("LOCAL0"), LOG4CXX_STR("local0"))) { return LOG_LOCAL0; } else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("LOCAL1"), LOG4CXX_STR("local1"))) { return LOG_LOCAL1; } else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("LOCAL2"), LOG4CXX_STR("local2"))) { return LOG_LOCAL2; } else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("LOCAL3"), LOG4CXX_STR("local3"))) { return LOG_LOCAL3; } else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("LOCAL4"), LOG4CXX_STR("local4"))) { return LOG_LOCAL4; } else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("LOCAL5"), LOG4CXX_STR("local5"))) { return LOG_LOCAL5; } else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("LOCAL6"), LOG4CXX_STR("local6"))) { return LOG_LOCAL6; } else if (StringHelper::equalsIgnoreCase(s, LOG4CXX_STR("LOCAL7"), LOG4CXX_STR("local7"))) { return LOG_LOCAL7; } else { return LOG_UNDEF; } } void SyslogAppender::append(const spi::LoggingEventPtr& event, Pool& p) { if (!isAsSevereAsThreshold(event->getLevel())) { return; } LogString msg; std::string encoded; _priv->layout->format(msg, event, p); Transcoder::encode(msg, encoded); // Split up the message if it is over maxMessageLength in size. // According to RFC 3164, the max message length is 1024, however // newer systems(such as syslog-ng) can go up to 8k in size for their // messages. We will append (x/y) at the end of each message // to indicate how far through the message we are std::vector packets; if ( msg.size() > _priv->maxMessageLength ) { LogString::iterator start = msg.begin(); while ( start != msg.end() ) { LogString::iterator end = start + _priv->maxMessageLength - 12; if ( end > msg.end() ) { end = msg.end(); } LogString newMsg = LogString( start, end ); packets.push_back( newMsg ); start = end; } int current = 1; for (auto& item : packets) { char buf[12]; apr_snprintf( buf, sizeof(buf), "(%d/%d)", current, (int)packets.size() ); LOG4CXX_DECODE_CHAR(str, buf); item.append( str ); ++current; } } else { packets.push_back( msg ); } // On the local host, we can directly use the system function 'syslog' // if it is available #if LOG4CXX_HAVE_SYSLOG if (_priv->sw == 0) { for (auto const& item : packets) { // use of "%s" to avoid a security hole ::syslog(_priv->syslogFacility | event->getLevel()->getSyslogEquivalent(), "%s", item.c_str()); } return; } #endif // We must not attempt to append if sw is null. if (_priv->sw == 0) { _priv->errorHandler->error(LOG4CXX_STR("No syslog host is set for SyslogAppedender named \"") + _priv->name + LOG4CXX_STR("\".")); return; } for (auto const& item : packets) { LogString sbuf(1, 0x3C /* '<' */); StringHelper::toString((_priv->syslogFacility | event->getLevel()->getSyslogEquivalent()), p, sbuf); sbuf.append(1, (logchar) 0x3E /* '>' */); if (_priv->facilityPrinting) { sbuf.append(_priv->facilityStr); } sbuf.append(item); _priv->sw->write(sbuf); } } void SyslogAppender::activateOptions(Pool&) { } void SyslogAppender::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("SYSLOGHOST"), LOG4CXX_STR("sysloghost"))) { setSyslogHost(value); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("FACILITY"), LOG4CXX_STR("facility"))) { setFacility(value); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("MAXMESSAGELENGTH"), LOG4CXX_STR("maxmessagelength"))) { setMaxMessageLength(OptionConverter::toInt(value, 1024)); } else { AppenderSkeleton::setOption(option, value); } } void SyslogAppender::setSyslogHost(const LogString& syslogHost1) { if (_priv->sw != 0) { _priv->sw = nullptr; } LogString slHost = syslogHost1; int slHostPort = -1; LogString::size_type colonPos = 0; colonPos = slHost.rfind(':'); if (colonPos != LogString::npos) { slHostPort = StringHelper::toInt(slHost.substr(colonPos + 1)); // Erase the :port part of the host name slHost.erase( colonPos ); } // On the local host, we can directly use the system function 'syslog' // if it is available (cf. append) #if LOG4CXX_HAVE_SYSLOG if (syslogHost1 != LOG4CXX_STR("localhost") && syslogHost1 != LOG4CXX_STR("127.0.0.1") && !syslogHost1.empty()) #endif { if (slHostPort >= 0) { _priv->sw = std::make_unique(slHost, slHostPort); } else { _priv->sw = std::make_unique(slHost); } } _priv->syslogHost = slHost; _priv->syslogHostPort = slHostPort; } void SyslogAppender::setFacility(const LogString& facilityName) { if (facilityName.empty()) { return; } _priv->syslogFacility = getFacility(facilityName); if (_priv->syslogFacility == LOG_UNDEF) { LogLog::error(LOG4CXX_STR("[") + facilityName + LOG4CXX_STR("] is an unknown syslog facility. Defaulting to [USER].")); _priv->syslogFacility = LOG_USER; } this->initSyslogFacilityStr(); } const LogString& SyslogAppender::getSyslogHost() const { return _priv->syslogHost; } LogString SyslogAppender::getFacility() const { return getFacilityString(_priv->syslogFacility); } void SyslogAppender::setFacilityPrinting(bool facilityPrinting1) { _priv->facilityPrinting = facilityPrinting1; } bool SyslogAppender::getFacilityPrinting() const { return _priv->facilityPrinting; } void SyslogAppender::setMaxMessageLength(int maxMessageLength1) { _priv->maxMessageLength = maxMessageLength1; } int SyslogAppender::getMaxMessageLength() const { return _priv->maxMessageLength; } apache-log4cxx-1.3.1/src/main/cpp/mapfilter.cpp0000644000175100001770000000666114721727031020671 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::filter; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; #define priv static_cast(m_priv.get()) struct MapFilter::MapFilterPrivate : public FilterPrivate { MapFilterPrivate() : FilterPrivate(), acceptOnMatch(true), mustMatchAll(false) {} bool acceptOnMatch; bool mustMatchAll; // true = AND; false = OR KeyVals keyVals; }; IMPLEMENT_LOG4CXX_OBJECT(MapFilter) MapFilter::MapFilter() : Filter(std::make_unique()) { } MapFilter::~MapFilter() {} void MapFilter::setOption( const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("ACCEPTONMATCH"), LOG4CXX_STR("acceptonmatch"))) { priv->acceptOnMatch = OptionConverter::toBoolean(value, priv->acceptOnMatch); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("OPERATOR"), LOG4CXX_STR("operator"))) { priv->mustMatchAll = StringHelper::equalsIgnoreCase(value, LOG4CXX_STR("AND"), LOG4CXX_STR("and")) ? true : false; } else if (!option.empty() && !value.empty()) { priv->keyVals[option] = value; } } Filter::FilterDecision MapFilter::decide( const LOG4CXX_NS::spi::LoggingEventPtr& event) const { if (priv->keyVals.empty()) { return Filter::NEUTRAL; } bool matched = true; for (auto const& item : priv->keyVals) { LogString curval; event->getMDC(item.first, curval); if (curval.empty() || curval != item.second) { matched = false; } else { matched = true; } if (priv->mustMatchAll != matched) { break; } } if (priv->acceptOnMatch) { return matched ? Filter::ACCEPT : Filter::NEUTRAL; } else { return matched ? Filter::DENY : Filter::NEUTRAL; } } void MapFilter::setKeyValue(const LogString& strKey, const LogString& strValue) { priv->keyVals[strKey] = strValue; } const LogString& MapFilter::getValue(const LogString& strKey) const { static const WideLife empty; const KeyVals::const_iterator it(priv->keyVals.find(strKey)); return (it != priv->keyVals.end() ? it->second : empty.value()); } void MapFilter::setAcceptOnMatch(bool acceptOnMatch1) { priv->acceptOnMatch = acceptOnMatch1; } bool MapFilter::getAcceptOnMatch() const { return priv->acceptOnMatch; } bool MapFilter::getMustMatchAll() const { return priv->mustMatchAll; } void MapFilter::setMustMatchAll(bool mustMatchAll1) { priv->mustMatchAll = mustMatchAll1; } apache-log4cxx-1.3.1/src/main/cpp/filelocationpatternconverter.cpp0000644000175100001770000000330614721727031024675 0ustar runnerdocker/* * 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. */ #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::pattern; using namespace LOG4CXX_NS::spi; using namespace helpers; IMPLEMENT_LOG4CXX_OBJECT(FileLocationPatternConverter) FileLocationPatternConverter::FileLocationPatternConverter() : LoggingEventPatternConverter(LOG4CXX_STR("File Location"), LOG4CXX_STR("file")) { } PatternConverterPtr FileLocationPatternConverter::newInstance( const std::vector& /* options */ ) { static WideLife instance = std::make_shared(); return instance; } void FileLocationPatternConverter::format( const LoggingEventPtr& event, LogString& toAppendTo, Pool& /* p */ ) const { append(toAppendTo, event->getLocationInformation().getFileName()); } apache-log4cxx-1.3.1/src/main/cpp/outputstreamwriter.cpp0000644000175100001770000000651114721727031022711 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(OutputStreamWriter) struct OutputStreamWriter::OutputStreamWriterPrivate{ OutputStreamWriterPrivate(OutputStreamPtr& out1) : out(out1), enc(CharsetEncoder::getDefaultEncoder()){} OutputStreamWriterPrivate(OutputStreamPtr& out1, CharsetEncoderPtr& enc1) : out(out1), enc(enc1){} OutputStreamPtr out; CharsetEncoderPtr enc; }; OutputStreamWriter::OutputStreamWriter(OutputStreamPtr& out1) : m_priv(std::make_unique(out1)) { if (out1 == 0) { throw NullPointerException(LOG4CXX_STR("out parameter may not be null.")); } } OutputStreamWriter::OutputStreamWriter(OutputStreamPtr& out1, CharsetEncoderPtr& enc1) : m_priv(std::make_unique(out1, enc1)) { if (out1 == 0) { throw NullPointerException(LOG4CXX_STR("out parameter may not be null.")); } if (enc1 == 0) { throw NullPointerException(LOG4CXX_STR("enc parameter may not be null.")); } } OutputStreamWriter::~OutputStreamWriter() { } void OutputStreamWriter::close(Pool& p) { m_priv->out->close(p); } void OutputStreamWriter::flush(Pool& p) { m_priv->out->flush(p); } void OutputStreamWriter::write(const LogString& str, Pool& p) { if (str.empty()) return; if (CharsetEncoder::isTriviallyCopyable(str, m_priv->enc)) { ByteBuffer buf((char*)str.data(), str.size() * sizeof (logchar)); m_priv->out->write(buf, p); } else { enum { BUFSIZE = 1024 }; char stackData[BUFSIZE]; char* rawbuf = stackData; size_t bufSize = BUFSIZE; #ifdef LOG4CXX_MULTI_PROCESS std::vector heapData; // Ensure the logging event is a single write system call to keep events from each process separate if (bufSize < str.length() * 2) { heapData.resize(bufSize = str.length() * 2); rawbuf = heapData.data(); } #endif ByteBuffer buf(rawbuf, bufSize); m_priv->enc->reset(); LogString::const_iterator iter = str.begin(); while (iter != str.end()) { CharsetEncoder::encode(m_priv->enc, str, iter, buf); buf.flip(); m_priv->out->write(buf, p); buf.clear(); } CharsetEncoder::encode(m_priv->enc, str, iter, buf); m_priv->enc->flush(buf); buf.flip(); m_priv->out->write(buf, p); } } OutputStreamPtr OutputStreamWriter::getOutputStreamPtr() const { return m_priv->out; } apache-log4cxx-1.3.1/src/main/cpp/levelmatchfilter.cpp0000644000175100001770000000537214721727031022236 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::filter; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; #define priv static_cast(m_priv.get()) struct LevelMatchFilter::LevelMatchFilterPrivate : public FilterPrivate { bool acceptOnMatch; LevelPtr levelToMatch; }; IMPLEMENT_LOG4CXX_OBJECT(LevelMatchFilter) LevelMatchFilter::LevelMatchFilter() : Filter(std::make_unique()) { priv->acceptOnMatch = true; } LevelMatchFilter::~LevelMatchFilter() {} void LevelMatchFilter::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("LEVELTOMATCH"), LOG4CXX_STR("leveltomatch"))) { setLevelToMatch(value); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("ACCEPTONMATCH"), LOG4CXX_STR("acceptonmatch"))) { priv->acceptOnMatch = OptionConverter::toBoolean(value, priv->acceptOnMatch); } } void LevelMatchFilter::setLevelToMatch(const LogString& levelToMatch1) { priv->levelToMatch = OptionConverter::toLevel(levelToMatch1, priv->levelToMatch); } LogString LevelMatchFilter::getLevelToMatch() const { return priv->levelToMatch->toString(); } Filter::FilterDecision LevelMatchFilter::decide( const LOG4CXX_NS::spi::LoggingEventPtr& event) const { if (priv->levelToMatch != 0 && priv->levelToMatch->equals(event->getLevel())) { if (priv->acceptOnMatch) { return Filter::ACCEPT; } else { return Filter::DENY; } } else { return Filter::NEUTRAL; } } void LevelMatchFilter::setAcceptOnMatch(bool acceptOnMatch1) { priv->acceptOnMatch = acceptOnMatch1; } bool LevelMatchFilter::getAcceptOnMatch() const { return priv->acceptOnMatch; } apache-log4cxx-1.3.1/src/main/cpp/inputstream.cpp0000644000175100001770000000202614721727031021250 0ustar runnerdocker/* * 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. */ #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(InputStream) InputStream::InputStream() { } InputStream::~InputStream() { } apache-log4cxx-1.3.1/src/main/cpp/lineseparatorpatternconverter.cpp0000644000175100001770000000353014721727031025074 0ustar runnerdocker/* * 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. */ #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::pattern; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(LineSeparatorPatternConverter) LineSeparatorPatternConverter::LineSeparatorPatternConverter() : LoggingEventPatternConverter(LOG4CXX_STR("Line Sep"), LOG4CXX_STR("lineSep")) { } PatternConverterPtr LineSeparatorPatternConverter::newInstance( const std::vector& /* options */) { static WideLife instance = std::make_shared(); return instance; } void LineSeparatorPatternConverter::format( const LoggingEventPtr& /* event */, LogString& toAppendTo, Pool& /* p */) const { toAppendTo.append(LOG4CXX_EOL); } void LineSeparatorPatternConverter::format( const ObjectPtr& /* event */, LogString& toAppendTo, Pool& /* p */) const { toAppendTo.append(LOG4CXX_EOL); } apache-log4cxx-1.3.1/src/main/cpp/systemerrwriter.cpp0000644000175100001770000000355614721727031022200 0ustar runnerdocker/* * 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. */ #include #include #include #include #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(SystemErrWriter) SystemErrWriter::SystemErrWriter() { } SystemErrWriter::~SystemErrWriter() { } void SystemErrWriter::close(Pool& /* p */) { } void SystemErrWriter::flush(Pool& /* p */) { flush(); } void SystemErrWriter::write(const LogString& str, Pool& /* p */) { write(str); } bool SystemErrWriter::isWide() { #if LOG4CXX_FORCE_WIDE_CONSOLE return true; #elif LOG4CXX_FORCE_BYTE_CONSOLE || !LOG4CXX_HAS_FWIDE return false; #else return fwide(stderr, 0) > 0; #endif } void SystemErrWriter::write(const LogString& str) { #if LOG4CXX_WCHAR_T_API if (isWide()) { LOG4CXX_ENCODE_WCHAR(msg, str); fputws(msg.c_str(), stderr); return; } #endif LOG4CXX_ENCODE_CHAR(msg, str); fputs(msg.c_str(), stderr); } void SystemErrWriter::flush() { fflush(stderr); } apache-log4cxx-1.3.1/src/main/cpp/writer.cpp0000644000175100001770000000202514721727031020210 0ustar runnerdocker/* * 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. */ #include #include #include #include using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(Writer) Writer::Writer() { } Writer::~Writer() { } apache-log4cxx-1.3.1/src/main/cpp/formattinginfo.cpp0000644000175100001770000000555114721727031021731 0ustar runnerdocker/* * 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. */ #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::pattern; struct FormattingInfo::FormattingInfoPrivate { FormattingInfoPrivate(const bool leftAlign1, const int minLength1, const int maxLength1): minLength(minLength1), maxLength(maxLength1), leftAlign(leftAlign1) {} /** * Minimum length. */ const int minLength; /** * Maximum length. */ const int maxLength; /** * Alignment. */ const bool leftAlign; }; IMPLEMENT_LOG4CXX_OBJECT(FormattingInfo) /** * Creates new instance. * @param leftAlign left align if true. * @param minLength minimum length. * @param maxLength maximum length. */ FormattingInfo::FormattingInfo( const bool leftAlign1, const int minLength1, const int maxLength1) : m_priv(std::make_unique(leftAlign1, minLength1, maxLength1)) { } FormattingInfo::~FormattingInfo() {} /** * Gets default instance. * @return default instance. */ FormattingInfoPtr FormattingInfo::getDefault() { static helpers::WideLife def= std::make_shared(false, 0, INT_MAX); return def; } /** * 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. */ void FormattingInfo::format(const int fieldStart, LogString& buffer) const { int rawLength = int(buffer.length() - fieldStart); if (rawLength > m_priv->maxLength) { buffer.erase(buffer.begin() + fieldStart, buffer.begin() + fieldStart + (rawLength - m_priv->maxLength)); } else if (rawLength < m_priv->minLength) { if (m_priv->leftAlign) { buffer.append(m_priv->minLength - rawLength, (logchar) 0x20 /* ' ' */); } else { buffer.insert(fieldStart, m_priv->minLength - rawLength, 0x20 /* ' ' */); } } } bool FormattingInfo::isLeftAligned() const { return m_priv->leftAlign; } int FormattingInfo::getMinLength() const { return m_priv->minLength; } int FormattingInfo::getMaxLength() const { return m_priv->maxLength; } apache-log4cxx-1.3.1/src/main/cpp/asyncappender.cpp0000644000175100001770000003371514721727031021542 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #include #include #if LOG4CXX_EVENTS_AT_EXIT #include #endif using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; using namespace LOG4CXX_NS::spi; #if 15 < LOG4CXX_ABI_VERSION namespace { #endif /** * The default buffer size is set to 128 events. */ enum { DEFAULT_BUFFER_SIZE = 128 }; class DiscardSummary { private: /** * First event of the highest severity. */ LoggingEventPtr maxEvent; /** * Total count of messages discarded. */ int count; public: /** * Create new instance. * * @param event event, may not be null. */ DiscardSummary(const LoggingEventPtr& event); /** Copy constructor. */ DiscardSummary(const DiscardSummary& src); /** Assignment operator. */ DiscardSummary& operator=(const DiscardSummary& src); /** * Add discarded event to summary. * * @param event event, may not be null. */ void add(const LoggingEventPtr& event); /** * Create an event with a discard count and the message from \c maxEvent. * * @return the new event. */ LoggingEventPtr createEvent(Pool& p); #if LOG4CXX_ABI_VERSION <= 15 static ::LOG4CXX_NS::spi::LoggingEventPtr createEvent(::LOG4CXX_NS::helpers::Pool& p, size_t discardedCount); #endif /** * The number of messages discarded. */ int getCount() const { return count; } }; typedef std::map DiscardMap; #if 15 < LOG4CXX_ABI_VERSION } #endif #ifdef __cpp_lib_hardware_interference_size using std::hardware_constructive_interference_size; using std::hardware_destructive_interference_size; #else // 64 bytes on x86-64 │ L1_CACHE_BYTES │ L1_CACHE_SHIFT │ __cacheline_aligned │ ... constexpr std::size_t hardware_constructive_interference_size = 64; constexpr std::size_t hardware_destructive_interference_size = 64; #endif struct AsyncAppender::AsyncAppenderPriv : public AppenderSkeleton::AppenderSkeletonPrivate { AsyncAppenderPriv() : AppenderSkeletonPrivate() , buffer(DEFAULT_BUFFER_SIZE) , bufferSize(DEFAULT_BUFFER_SIZE) , dispatcher() , locationInfo(false) , blocking(true) #if LOG4CXX_EVENTS_AT_EXIT , atExitRegistryRaii([this]{stopDispatcher();}) #endif , eventCount(0) , dispatchedCount(0) , commitCount(0) { } ~AsyncAppenderPriv() { stopDispatcher(); } /** * Event buffer. */ struct EventData { LoggingEventPtr event; size_t pendingCount; }; std::vector buffer; /** * Mutex used to guard access to buffer and discardMap. */ std::mutex bufferMutex; std::condition_variable bufferNotFull; std::condition_variable bufferNotEmpty; /** * Map of DiscardSummary objects keyed by logger name. */ DiscardMap discardMap; /** * The maximum number of undispatched events. */ int bufferSize; /** * Nested appenders. */ helpers::AppenderAttachableImpl appenders; /** * Dispatcher. */ std::thread dispatcher; void stopDispatcher() { this->setClosed(); bufferNotEmpty.notify_all(); bufferNotFull.notify_all(); if (dispatcher.joinable()) { dispatcher.join(); } } /** * Should location info be included in dispatched messages. */ bool locationInfo; /** * Does appender block when buffer is full. */ bool blocking; #if LOG4CXX_EVENTS_AT_EXIT helpers::AtExitRegistry::Raii atExitRegistryRaii; #endif /** * Used to calculate the buffer position at which to store the next event. */ alignas(hardware_constructive_interference_size) std::atomic eventCount; /** * Used to calculate the buffer position from which to extract the next event. */ alignas(hardware_constructive_interference_size) std::atomic dispatchedCount; /** * Used to communicate to the dispatch thread when an event is committed in buffer. */ alignas(hardware_constructive_interference_size) std::atomic commitCount; bool isClosed() { std::lock_guard lock(this->bufferMutex); return this->closed; } void setClosed() { std::lock_guard lock(this->bufferMutex); this->closed = true; } /** * Used to ensure the dispatch thread does not wait when a logging thread is waiting. */ int blockedCount{0}; }; IMPLEMENT_LOG4CXX_OBJECT(AsyncAppender) #define priv static_cast(m_priv.get()) AsyncAppender::AsyncAppender() : AppenderSkeleton(std::make_unique()) { } AsyncAppender::~AsyncAppender() { finalize(); } void AsyncAppender::addAppender(const AppenderPtr newAppender) { priv->appenders.addAppender(newAppender); } void AsyncAppender::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("LOCATIONINFO"), LOG4CXX_STR("locationinfo"))) { setLocationInfo(OptionConverter::toBoolean(value, false)); } if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("BUFFERSIZE"), LOG4CXX_STR("buffersize"))) { setBufferSize(OptionConverter::toInt(value, DEFAULT_BUFFER_SIZE)); } if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("BLOCKING"), LOG4CXX_STR("blocking"))) { setBlocking(OptionConverter::toBoolean(value, true)); } else { AppenderSkeleton::setOption(option, value); } } void AsyncAppender::doAppend(const spi::LoggingEventPtr& event, Pool& pool1) { doAppendImpl(event, pool1); } void AsyncAppender::append(const spi::LoggingEventPtr& event, Pool& p) { if (priv->bufferSize <= 0) { priv->appenders.appendLoopOnAppenders(event, p); } // Get a copy of this thread's diagnostic context event->LoadDC(); if (!priv->dispatcher.joinable()) { std::lock_guard lock(priv->mutex); if (!priv->dispatcher.joinable()) priv->dispatcher = ThreadUtility::instance()->createThread( LOG4CXX_STR("AsyncAppender"), &AsyncAppender::dispatch, this ); } while (true) { auto pendingCount = priv->eventCount - priv->dispatchedCount; if (0 <= pendingCount && pendingCount < priv->bufferSize) { // Claim a slot in the ring buffer auto oldEventCount = priv->eventCount++; auto index = oldEventCount % priv->buffer.size(); // Wait for a free slot while (priv->bufferSize <= oldEventCount - priv->dispatchedCount) std::this_thread::yield(); // Allow the dispatch thread to free a slot // Write to the ring buffer priv->buffer[index] = AsyncAppenderPriv::EventData{event, pendingCount}; // Notify the dispatch thread that an event has been added auto failureCount = 0; auto savedEventCount = oldEventCount; while (!priv->commitCount.compare_exchange_weak(oldEventCount, oldEventCount + 1, std::memory_order_release)) { oldEventCount = savedEventCount; if (2 < ++failureCount) // Did the scheduler suspend a thread between claiming a slot and advancing commitCount? std::this_thread::yield(); // Wait a bit } priv->bufferNotEmpty.notify_all(); break; } // // Following code is only reachable if buffer is full or eventCount has overflowed // std::unique_lock lock(priv->bufferMutex); priv->bufferNotEmpty.notify_all(); // // if blocking and thread is not already interrupted // and not the dispatcher then // wait for a buffer notification bool discard = true; if (priv->blocking && !priv->closed && (priv->dispatcher.get_id() != std::this_thread::get_id()) ) { ++priv->blockedCount; priv->bufferNotFull.wait(lock, [this]() { return priv->eventCount - priv->dispatchedCount < priv->bufferSize; }); --priv->blockedCount; discard = false; } // // if blocking is false or thread has been interrupted // add event to discard map. // if (discard) { LogString loggerName = event->getLoggerName(); DiscardMap::iterator iter = priv->discardMap.find(loggerName); if (iter == priv->discardMap.end()) { DiscardSummary summary(event); priv->discardMap.insert(DiscardMap::value_type(loggerName, summary)); } else { (*iter).second.add(event); } break; } } } void AsyncAppender::close() { priv->stopDispatcher(); for (auto item : priv->appenders.getAllAppenders()) { item->close(); } } AppenderList AsyncAppender::getAllAppenders() const { return priv->appenders.getAllAppenders(); } AppenderPtr AsyncAppender::getAppender(const LogString& n) const { return priv->appenders.getAppender(n); } bool AsyncAppender::isAttached(const AppenderPtr appender) const { return priv->appenders.isAttached(appender); } bool AsyncAppender::requiresLayout() const { return false; } void AsyncAppender::removeAllAppenders() { priv->appenders.removeAllAppenders(); } void AsyncAppender::removeAppender(const AppenderPtr appender) { priv->appenders.removeAppender(appender); } void AsyncAppender::removeAppender(const LogString& n) { priv->appenders.removeAppender(n); } bool AsyncAppender::getLocationInfo() const { return priv->locationInfo; } void AsyncAppender::setLocationInfo(bool flag) { priv->locationInfo = flag; } void AsyncAppender::setBufferSize(int size) { if (size < 0) { throw IllegalArgumentException(LOG4CXX_STR("size argument must be non-negative")); } std::lock_guard lock(priv->bufferMutex); priv->bufferSize = (size < 1) ? 1 : size; priv->buffer.resize(priv->bufferSize); priv->bufferNotFull.notify_all(); } int AsyncAppender::getBufferSize() const { return priv->bufferSize; } void AsyncAppender::setBlocking(bool value) { std::lock_guard lock(priv->bufferMutex); priv->blocking = value; priv->bufferNotFull.notify_all(); } bool AsyncAppender::getBlocking() const { return priv->blocking; } DiscardSummary::DiscardSummary(const LoggingEventPtr& event) : maxEvent(event), count(1) { } DiscardSummary::DiscardSummary(const DiscardSummary& src) : maxEvent(src.maxEvent), count(src.count) { } DiscardSummary& DiscardSummary::operator=(const DiscardSummary& src) { maxEvent = src.maxEvent; count = src.count; return *this; } void DiscardSummary::add(const LoggingEventPtr& event) { if (event->getLevel()->toInt() > maxEvent->getLevel()->toInt()) { maxEvent = event; } count++; } LoggingEventPtr DiscardSummary::createEvent(Pool& p) { LogString msg(LOG4CXX_STR("Discarded ")); StringHelper::toString(count, p, msg); msg.append(LOG4CXX_STR(" messages due to a full event buffer including: ")); msg.append(maxEvent->getMessage()); return std::make_shared( maxEvent->getLoggerName(), maxEvent->getLevel(), msg, LocationInfo::getLocationUnavailable() ); } #if LOG4CXX_ABI_VERSION <= 15 ::LOG4CXX_NS::spi::LoggingEventPtr DiscardSummary::createEvent(::LOG4CXX_NS::helpers::Pool& p, size_t discardedCount) { LogString msg(LOG4CXX_STR("Discarded ")); StringHelper::toString(discardedCount, p, msg); msg.append(LOG4CXX_STR(" messages due to a full event buffer")); return std::make_shared( LOG4CXX_STR(""), LOG4CXX_NS::Level::getError(), msg, LocationInfo::getLocationUnavailable() ); } #endif void AsyncAppender::dispatch() { size_t discardCount = 0; std::vector pendingCountHistogram(priv->bufferSize, 0); bool isActive = true; while (isActive) { Pool p; LoggingEventList events; events.reserve(priv->bufferSize); for (int count = 0; count < 2 && priv->dispatchedCount == priv->commitCount; ++count) std::this_thread::yield(); // Wait a bit if (priv->dispatchedCount == priv->commitCount) { std::unique_lock lock(priv->bufferMutex); priv->bufferNotEmpty.wait(lock, [this]() -> bool { return 0 < priv->blockedCount || priv->dispatchedCount != priv->commitCount || priv->closed; } ); } isActive = !priv->isClosed(); while (events.size() < priv->bufferSize && priv->dispatchedCount != priv->commitCount) { auto index = priv->dispatchedCount % priv->buffer.size(); const auto& data = priv->buffer[index]; events.push_back(data.event); if (data.pendingCount < pendingCountHistogram.size()) ++pendingCountHistogram[data.pendingCount]; ++priv->dispatchedCount; } priv->bufferNotFull.notify_all(); { std::lock_guard lock(priv->bufferMutex); for (auto discardItem : priv->discardMap) { events.push_back(discardItem.second.createEvent(p)); discardCount += discardItem.second.getCount(); } priv->discardMap.clear(); } for (auto item : events) { try { priv->appenders.appendLoopOnAppenders(item, p); } catch (std::exception& ex) { if (!priv->isClosed()) { priv->errorHandler->error(LOG4CXX_STR("async dispatcher"), ex, 0, item); isActive = false; } } catch (...) { if (!priv->isClosed()) { priv->errorHandler->error(LOG4CXX_STR("async dispatcher")); isActive = false; } } } } if (LogLog::isDebugEnabled()) { Pool p; LogString msg(LOG4CXX_STR("AsyncAppender")); msg += LOG4CXX_STR(" discardCount "); StringHelper::toString(discardCount, p, msg); msg += LOG4CXX_STR(" pendingCountHistogram"); for (auto item : pendingCountHistogram) { msg += logchar(' '); StringHelper::toString(item, p, msg); } LogLog::debug(msg); } } apache-log4cxx-1.3.1/src/main/cpp/bytebuffer.cpp0000644000175100001770000000461414721727031021037 0ustar runnerdocker/* * 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. */ #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; struct ByteBuffer::ByteBufferPriv { ByteBufferPriv(char* data1, size_t capacity) : base(data1), pos(0), lim(capacity), cap(capacity) {} char* base; size_t pos; size_t lim; size_t cap; }; ByteBuffer::ByteBuffer(char* data1, size_t capacity) : m_priv(std::make_unique(data1, capacity)) { } ByteBuffer::~ByteBuffer() { } void ByteBuffer::clear() { m_priv->lim = m_priv->cap; m_priv->pos = 0; } void ByteBuffer::flip() { m_priv->lim = m_priv->pos; m_priv->pos = 0; } void ByteBuffer::position(size_t newPosition) { if (newPosition < m_priv->lim) { m_priv->pos = newPosition; } else { m_priv->pos = m_priv->lim; } } void ByteBuffer::limit(size_t newLimit) { if (newLimit > m_priv->cap) { throw IllegalArgumentException(LOG4CXX_STR("newLimit")); } m_priv->lim = newLimit; } bool ByteBuffer::put(char byte) { if (m_priv->pos < m_priv->lim) { m_priv->base[m_priv->pos++] = byte; return true; } return false; } char* ByteBuffer::data() { return m_priv->base; } const char* ByteBuffer::data() const { return m_priv->base; } char* ByteBuffer::current() { return m_priv->base + m_priv->pos; } const char* ByteBuffer::current() const { return m_priv->base + m_priv->pos; } size_t ByteBuffer::limit() const { return m_priv->lim; } size_t ByteBuffer::position() const { return m_priv->pos; } size_t ByteBuffer::remaining() const { return m_priv->lim - m_priv->pos; } apache-log4cxx-1.3.1/src/main/cpp/colorstartpatternconverter.cpp0000644000175100001770000002104514721727031024421 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::pattern; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(ColorStartPatternConverter) #define priv static_cast(m_priv.get()) static LogString colorToANSISequence(const LogString& color, bool isForeground, Pool& pool){ int numberToConvert = 0; if(StringHelper::equalsIgnoreCase(color, LOG4CXX_STR("BLACK"), LOG4CXX_STR("black"))){ numberToConvert = 30; }else if(StringHelper::equalsIgnoreCase(color, LOG4CXX_STR("RED"), LOG4CXX_STR("red"))){ numberToConvert = 31; }else if(StringHelper::equalsIgnoreCase(color, LOG4CXX_STR("GREEN"), LOG4CXX_STR("green"))){ numberToConvert = 32; }else if(StringHelper::equalsIgnoreCase(color, LOG4CXX_STR("YELLOW"), LOG4CXX_STR("yellow"))){ numberToConvert = 33; }else if(StringHelper::equalsIgnoreCase(color, LOG4CXX_STR("BLUE"), LOG4CXX_STR("blue"))){ numberToConvert = 34; }else if(StringHelper::equalsIgnoreCase(color, LOG4CXX_STR("MAGENTA"), LOG4CXX_STR("magenta"))){ numberToConvert = 35; }else if(StringHelper::equalsIgnoreCase(color, LOG4CXX_STR("CYAN"), LOG4CXX_STR("cyan"))){ numberToConvert = 36; }else if(StringHelper::equalsIgnoreCase(color, LOG4CXX_STR("WHITE"), LOG4CXX_STR("white"))){ numberToConvert = 37; } if( numberToConvert == 0 ){ return LOG4CXX_STR(""); } LogString ret; if( isForeground == false ){ numberToConvert += 10; } StringHelper::toString(numberToConvert, pool, ret); return ret; } static LogString graphicsModeToANSISequence(const LogString& graphicsMode, Pool& pool){ int numberToConvert = 0; if(StringHelper::equalsIgnoreCase(graphicsMode, LOG4CXX_STR("BOLD"), LOG4CXX_STR("bold"))){ numberToConvert = 1; }else if(StringHelper::equalsIgnoreCase(graphicsMode, LOG4CXX_STR("DIM"), LOG4CXX_STR("dim"))){ numberToConvert = 2; }else if(StringHelper::equalsIgnoreCase(graphicsMode, LOG4CXX_STR("ITALIC"), LOG4CXX_STR("italic"))){ numberToConvert = 3; }else if(StringHelper::equalsIgnoreCase(graphicsMode, LOG4CXX_STR("UNDERLINE"), LOG4CXX_STR("underline"))){ numberToConvert = 4; }else if(StringHelper::equalsIgnoreCase(graphicsMode, LOG4CXX_STR("BLINKING"), LOG4CXX_STR("blinking"))){ numberToConvert = 5; }else if(StringHelper::equalsIgnoreCase(graphicsMode, LOG4CXX_STR("INVERSE"), LOG4CXX_STR("inverse"))){ numberToConvert = 7; }else if(StringHelper::equalsIgnoreCase(graphicsMode, LOG4CXX_STR("STRIKETHROUGH"), LOG4CXX_STR("strikethrough"))){ numberToConvert = 9; } if( numberToConvert == 0 ){ return LOG4CXX_STR(""); } LogString ret; StringHelper::toString(numberToConvert, pool, ret); return ret; } static LogString convertSingleSequence(const LogString& sequence, Pool& pool){ LogString strInParens; bool inParens = false; bool hasParens = false; size_t x = 0; for(x = 0; x < sequence.length(); x++){ if( sequence[x] == '(' && !inParens ){ inParens = true; hasParens = true; continue; }else if( sequence[x] == '(' && inParens ){ // Unbalanced parens - parse invalid return LOG4CXX_STR(""); } if( sequence[x] == ')' && inParens ){ hasParens = true; inParens = false; break; } if( inParens ){ strInParens.push_back(sequence[x]); } } if( (x != (sequence.length() - 1) || inParens) && hasParens ){ // Unbalanced parens, or more data in the string than we expected - parse invalid return LOG4CXX_STR(""); } if(StringHelper::startsWith(sequence, LOG4CXX_STR("fg("))){ // Parse foreground return colorToANSISequence(strInParens, true, pool); }else if(StringHelper::startsWith(sequence, LOG4CXX_STR("bg("))){ return colorToANSISequence(strInParens, false, pool); }else{ return graphicsModeToANSISequence(sequence, pool); } } struct ColorStartPatternConverter::ColorPatternConverterPrivate : public PatternConverterPrivate { ColorPatternConverterPrivate( const LogString& name, const LogString& style ) : PatternConverterPrivate( name, style ){} LogString m_fatalColor; LogString m_errorColor; LogString m_warnColor; LogString m_infoColor; LogString m_debugColor; LogString m_traceColor; }; ColorStartPatternConverter::ColorStartPatternConverter() : LoggingEventPatternConverter(std::make_unique(LOG4CXX_STR("Color Start"), LOG4CXX_STR("colorStart"))) { } PatternConverterPtr ColorStartPatternConverter::newInstance( const std::vector& /* options */) { static WideLife instance = std::make_shared(); return instance; } void ColorStartPatternConverter::format( const LoggingEventPtr& event, LogString& toAppendTo, Pool& p) const { LOG4CXX_NS::LevelPtr lvl = event->getLevel(); switch (lvl->toInt()) { case LOG4CXX_NS::Level::FATAL_INT: toAppendTo.append(priv->m_fatalColor); break; case LOG4CXX_NS::Level::ERROR_INT: toAppendTo.append(priv->m_errorColor); break; case LOG4CXX_NS::Level::WARN_INT: toAppendTo.append(priv->m_warnColor); break; case LOG4CXX_NS::Level::INFO_INT: toAppendTo.append(priv->m_infoColor); break; case LOG4CXX_NS::Level::DEBUG_INT: toAppendTo.append(priv->m_debugColor); break; case LOG4CXX_NS::Level::TRACE_INT: toAppendTo.append(priv->m_traceColor); break; default: break; } } void ColorStartPatternConverter::setFatalColor(const LogString& color){ parseColor(color, &(priv->m_fatalColor)); } void ColorStartPatternConverter::setErrorColor(const LogString& color){ parseColor(color, &(priv->m_errorColor)); } void ColorStartPatternConverter::setWarnColor(const LogString& color){ parseColor(color, &(priv->m_warnColor)); } void ColorStartPatternConverter::setInfoColor(const LogString& color){ parseColor(color, &(priv->m_infoColor)); } void ColorStartPatternConverter::setDebugColor(const LogString& color){ parseColor(color, &(priv->m_debugColor)); } void ColorStartPatternConverter::setTraceColor(const LogString& color){ parseColor(color, &(priv->m_traceColor)); } void ColorStartPatternConverter::parseColor(const LogString& color, LogString* result){ LogString lower = StringHelper::toLowerCase(color); Pool pool; // If the color we are trying to parse is blank, clear our result if(StringHelper::trim(color).empty() || StringHelper::equalsIgnoreCase(color, LOG4CXX_STR("NONE"), LOG4CXX_STR("none"))){ result->clear(); return; } if( StringHelper::startsWith(lower, LOG4CXX_STR("\\x1b")) ){ if( color[color.size() - 1] != 'm' ){ // In order for this to be a valid ANSI escape sequence, // it must end with an 'm'. If it does not, reject. return; } // We start with an escape sequence, copy the data over after the escape byte result->clear(); result->append(LOG4CXX_STR("\x1b")); for( size_t x = 4; x < color.size(); x++ ){ result->push_back(color[x]); } }else{ // We do not start with an escape sequence: try to parse color // Escape sequence information: // https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797 // https://en.wikipedia.org/wiki/ANSI_escape_code result->clear(); result->append(LOG4CXX_STR("\x1b[")); LogString tmp; for( size_t x = 0; x < color.size(); x++ ){ if(color[x] == '|' ){ LogString toAppend = convertSingleSequence(tmp, pool); tmp.clear(); if(!toAppend.empty()){ result->push_back(';'); result->append(toAppend); } }else{ tmp.push_back(color[x]); } } LogString toAppend = convertSingleSequence(tmp, pool); tmp.clear(); if(!toAppend.empty()){ result->push_back(';'); result->append(toAppend); } result->append(LOG4CXX_STR("m")); } } apache-log4cxx-1.3.1/src/main/cpp/configurator.cpp0000644000175100001770000000204414721727031021377 0ustar runnerdocker/* * 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. */ #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::spi; IMPLEMENT_LOG4CXX_OBJECT(Configurator) Configurator::Configurator() { } apache-log4cxx-1.3.1/src/main/cpp/mdcpatternconverter.cpp0000644000175100001770000000512514721727031022771 0ustar runnerdocker/* * 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. */ #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::pattern; IMPLEMENT_LOG4CXX_OBJECT(MDCPatternConverter) MDCPatternConverter::MDCPatternConverter ( const LogString& name , const LogString& style , const std::vector& options ) : LoggingEventPatternConverter(std::make_unique(name, style)) { } PatternConverterPtr MDCPatternConverter::newInstance( const std::vector& options) { if (options.empty()) { static helpers::WideLife def = std::make_shared(); return def; } return std::make_shared(LogString(), options.front()); } void MDCPatternConverter::format ( const spi::LoggingEventPtr& event , LogString& toAppendTo , helpers::Pool& /* p */ ) const { size_t startIndex = toAppendTo.size(); if (m_priv->name.empty()) // Full MDC required? { bool first = true; for (auto key : event->getMDCKeySet()) { toAppendTo.append(first ? LOG4CXX_STR("{") : LOG4CXX_STR(",")); JSONLayout::appendItem(key, toAppendTo); toAppendTo.append(LOG4CXX_STR(":")); LogString value; event->getMDC(key, value); JSONLayout::appendItem(value, toAppendTo); first = false; } if (!first) toAppendTo.append(LOG4CXX_STR("}")); } else event->getMDC(m_priv->name, toAppendTo); if (!m_priv->style.empty()) // In a quoted context? { auto quote = m_priv->style.front(); size_t endIndex; while ((endIndex = toAppendTo.find(quote, startIndex)) != toAppendTo.npos) { toAppendTo.insert(endIndex + 1, 1, quote); startIndex = endIndex + 2; } } } apache-log4cxx-1.3.1/src/main/cpp/class.cpp0000644000175100001770000001335014721727031020004 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include #include #include #include #include #if defined(WIN32) || defined(_WIN32) #if !defined(_WIN32_WCE) #include #endif #include #endif #include #include #include #include #include #include #include #include #include #include #include #include #if LOG4CXX_HAS_FMT_LAYOUT #include #endif #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; using namespace LOG4CXX_NS::net; using namespace LOG4CXX_NS::filter; using namespace LOG4CXX_NS::xml; using namespace LOG4CXX_NS::rolling; namespace LOG4CXX_NS { uint32_t libraryVersion() { // This function defined in log4cxx.h return LOG4CXX_VERSION; } } #if LOG4CXX_ABI_VERSION <= 15 LOG4CXX_EXPORT uint32_t libraryVersion() { return LOG4CXX_NS::libraryVersion(); } #endif Class::Class() { } Class::~Class() { } #if LOG4CXX_ABI_VERSION <= 15 LogString Class::toString() const { return getName(); } #endif Object* Class::newInstance() const { throw InstantiationException(LOG4CXX_STR("Cannot create new instances of Class.")); #if LOG4CXX_RETURN_AFTER_THROW return 0; #endif } Class::ClassMap& Class::getRegistry() { static WideLife registry; return registry; } const Class& Class::forName(const LogString& className) { LogString lowerName(StringHelper::toLowerCase(className)); // // check registry using full class name // const Class* clazz = getRegistry()[lowerName]; if (clazz == 0) { LogString::size_type pos = className.find_last_of(LOG4CXX_STR(".$")); if (pos != LogString::npos) { LogString terminalName(lowerName, pos + 1, LogString::npos); clazz = getRegistry()[terminalName]; if (clazz == 0) { registerClasses(); clazz = getRegistry()[lowerName]; if (clazz == 0) { clazz = getRegistry()[terminalName]; } } } else { registerClasses(); clazz = getRegistry()[lowerName]; } } if (clazz == 0) { throw ClassNotFoundException(className); } return *clazz; } bool Class::registerClass(const Class& newClass) { getRegistry()[StringHelper::toLowerCase(newClass.getName())] = &newClass; return true; } void Class::registerClasses() { AsyncAppender::registerClass(); ConsoleAppender::registerClass(); FileAppender::registerClass(); LOG4CXX_NS::db::ODBCAppender::registerClass(); #if (defined(WIN32) || defined(_WIN32)) #if !defined(_WIN32_WCE) LOG4CXX_NS::nt::NTEventLogAppender::registerClass(); #endif LOG4CXX_NS::nt::OutputDebugStringAppender::registerClass(); #endif SMTPAppender::registerClass(); JSONLayout::registerClass(); HTMLLayout::registerClass(); #if LOG4CXX_HAS_FMT_LAYOUT FMTLayout::registerClass(); #endif PatternLayout::registerClass(); SimpleLayout::registerClass(); XMLLayout::registerClass(); LevelMatchFilter::registerClass(); LevelRangeFilter::registerClass(); StringMatchFilter::registerClass(); LocationInfoFilter::registerClass(); LOG4CXX_NS::rolling::RollingFileAppender::registerClass(); LOG4CXX_NS::rolling::SizeBasedTriggeringPolicy::registerClass(); LOG4CXX_NS::rolling::TimeBasedRollingPolicy::registerClass(); LOG4CXX_NS::rolling::ManualTriggeringPolicy::registerClass(); LOG4CXX_NS::rolling::FixedWindowRollingPolicy::registerClass(); LOG4CXX_NS::rolling::FilterBasedTriggeringPolicy::registerClass(); #if LOG4CXX_HAS_DOMCONFIGURATOR LOG4CXX_NS::xml::DOMConfigurator::registerClass(); #endif LOG4CXX_NS::PropertyConfigurator::registerClass(); LOG4CXX_NS::varia::FallbackErrorHandler::registerClass(); #if LOG4CXX_HAS_NETWORKING TelnetAppender::registerClass(); XMLSocketAppender::registerClass(); SyslogAppender::registerClass(); #endif } apache-log4cxx-1.3.1/src/main/cpp/appenderskeleton.cpp0000644000175100001770000001224514721727031022244 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(AppenderSkeleton) AppenderSkeleton::AppenderSkeleton( std::unique_ptr priv ) : m_priv(std::move(priv)) { } AppenderSkeleton::AppenderSkeleton() : m_priv(std::make_unique()) { } AppenderSkeleton::AppenderSkeleton(const LayoutPtr& layout) : m_priv(std::make_unique(layout)) { } AppenderSkeleton::~AppenderSkeleton() {} void AppenderSkeleton::finalize() { // An appender might be closed then garbage collected. There is no // point in closing twice. if (m_priv->closed) { return; } close(); } void AppenderSkeleton::addFilter(const spi::FilterPtr newFilter) { std::lock_guard lock(m_priv->mutex); if (m_priv->headFilter == nullptr) { m_priv->headFilter = m_priv->tailFilter = newFilter; } else { m_priv->tailFilter->setNext(newFilter); m_priv->tailFilter = newFilter; } } void AppenderSkeleton::clearFilters() { std::lock_guard lock(m_priv->mutex); m_priv->headFilter = m_priv->tailFilter = nullptr; } bool AppenderSkeleton::isAsSevereAsThreshold(const LevelPtr& level) const { return ((level == 0) || level->isGreaterOrEqual(m_priv->threshold)); } void AppenderSkeleton::doAppend(const spi::LoggingEventPtr& event, Pool& pool1) { std::lock_guard lock(m_priv->mutex); doAppendImpl(event, pool1); } void AppenderSkeleton::doAppendImpl(const spi::LoggingEventPtr& event, Pool& pool1) { if (m_priv->closed) { LogLog::error(((LogString) LOG4CXX_STR("Attempted to append to closed appender named [")) + m_priv->name + LOG4CXX_STR("].")); return; } if (!isAsSevereAsThreshold(event->getLevel())) { return; } FilterPtr f = m_priv->headFilter; while (f != 0) { switch (f->decide(event)) { case Filter::DENY: return; case Filter::ACCEPT: f = nullptr; break; case Filter::NEUTRAL: f = f->getNext(); } } append(event, pool1); } bool AppenderSkeleton::AppenderSkeletonPrivate::checkNotClosed() { if (this->closed) { if (!this->warnedClosed) { LogLog::warn(LOG4CXX_STR("Not allowed to write to a closed appender.")); this->warnedClosed = true; } return false; } return true; } bool AppenderSkeleton::AppenderSkeletonPrivate::checkLayout() { if (!this->layout) { if (!this->warnedNoLayout) { this->errorHandler->error ( LogString(LOG4CXX_STR("No layout set for the appender named [")) + this->name + LOG4CXX_STR("].") ); this->warnedNoLayout = true; } return false; } return true; } void AppenderSkeleton::setErrorHandler(const spi::ErrorHandlerPtr errorHandler1) { std::lock_guard lock(m_priv->mutex); if (errorHandler1 == nullptr) { // We do not throw exception here since the cause is probably a // bad config file. LogLog::warn(LOG4CXX_STR("You have tried to set a null error-handler.")); } else { m_priv->errorHandler = errorHandler1; } } void AppenderSkeleton::setThreshold(const LevelPtr& threshold1) { std::lock_guard lock(m_priv->mutex); m_priv->threshold = threshold1; } void AppenderSkeleton::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("THRESHOLD"), LOG4CXX_STR("threshold"))) { setThreshold(Level::toLevelLS(value)); } } const spi::ErrorHandlerPtr AppenderSkeleton::getErrorHandler() const { return m_priv->errorHandler; } spi::FilterPtr AppenderSkeleton::getFilter() const { return m_priv->headFilter; } const spi::FilterPtr AppenderSkeleton::getFirstFilter() const { return m_priv->headFilter; } LayoutPtr AppenderSkeleton::getLayout() const { return m_priv->layout; } LogString AppenderSkeleton::getName() const { return m_priv->name; } const LevelPtr AppenderSkeleton::getThreshold() const { return m_priv->threshold; } void AppenderSkeleton::setLayout(const LayoutPtr layout1) { m_priv->layout = layout1; } void AppenderSkeleton::setName(const LogString& name1) { m_priv->name.assign(name1); } apache-log4cxx-1.3.1/src/main/cpp/fulllocationpatternconverter.cpp0000644000175100001770000000367514721727031024731 0ustar runnerdocker/* * 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. */ #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::pattern; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(FullLocationPatternConverter) FullLocationPatternConverter::FullLocationPatternConverter() : LoggingEventPatternConverter(LOG4CXX_STR("Full Location"), LOG4CXX_STR("fullLocation")) { } PatternConverterPtr FullLocationPatternConverter::newInstance( const std::vector& /* options */) { static WideLife instance = std::make_shared(); return instance; } void FullLocationPatternConverter::format( const LoggingEventPtr& event, LogString& toAppendTo, Pool& p) const { append(toAppendTo, event->getLocationInformation().getFileName()); toAppendTo.append(1, (logchar) 0x28 /* '(' */); StringHelper::toString( event->getLocationInformation().getLineNumber(), p, toAppendTo); toAppendTo.append(1, (logchar) 0x29 /* ')' */); } apache-log4cxx-1.3.1/src/main/cpp/simpledateformat.cpp0000644000175100001770000004074614721727031022250 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; using namespace std; #if LOG4CXX_HAS_STD_LOCALE #include #endif #if defined(_MSC_VER) && _MSC_VER < 1300 #define HAS_FACET(locale, type) _HAS(locale, type) #define USE_FACET(locale, type) _USE(locale, type) #define PUT_FACET(facet, os, time, spec) facet.put(os, os, time, spec) #else #if defined(_RWSTD_NO_TEMPLATE_ON_RETURN_TYPE) #define HAS_FACET(locale, type) std::has_facet(locale, (type*) 0) #define USE_FACET(locale, type) std::use_facet(locale, (type*) 0) #else #define HAS_FACET(locale, type) std::has_facet < type >(locale) #define USE_FACET(locale, type) std::use_facet < type >(locale) #endif #define PUT_FACET(facet, os, time, spec) facet.put(os, os, os.fill(), time, spec) #endif namespace LOG4CXX_NS { namespace helpers { namespace SimpleDateFormatImpl { typedef void (*incrementFunction)(tm& time, apr_time_exp_t& apr_time); /** * Abstract inner class representing one format token * (one or more instances of a character). */ class PatternToken { public: PatternToken() { } virtual ~PatternToken() { } /** * Sets the time zone. * @param zone new time zone. */ virtual void setTimeZone(const TimeZonePtr& zone) { } /** * Appends the formatted content to the string. * @param s string to which format contribution is appended. * @param date exploded date/time. * @param p memory pool. */ virtual void format(LogString& s, const apr_time_exp_t& date, LOG4CXX_NS::helpers::Pool& p) const = 0; protected: static void incrementMonth(tm& time, apr_time_exp_t& aprtime) { time.tm_mon++; aprtime.tm_mon++; } static void incrementDay(tm& time, apr_time_exp_t& aprtime) { time.tm_wday++; aprtime.tm_wday++; } static void incrementHalfDay(tm& time, apr_time_exp_t& aprtime) { time.tm_hour += 12; aprtime.tm_hour += 12; } static void renderFacet(const std::locale* locale, incrementFunction inc, char spec, unsigned int wspec, const char* aprspec, std::vector& values) { std::vector::iterator valueIter = values.begin(); tm time; memset(&time, 0, sizeof(time)); apr_time_exp_t aprtime; memset(&aprtime, 0, sizeof(aprtime)); #if LOG4CXX_HAS_STD_LOCALE if (locale != NULL) { #if LOG4CXX_WCHAR_T_API if (HAS_FACET(*locale, std::time_put)) { const std::time_put& facet = USE_FACET(*locale, std::time_put); size_t start = 0; std::basic_ostringstream os; for (; valueIter != values.end(); valueIter++) { PUT_FACET(facet, os, &time, (char)wspec); Transcoder::decode(os.str().substr(start), *valueIter); start = os.str().length(); (*inc)(time, aprtime); } } else #endif if (HAS_FACET(*locale, std::time_put)) { const std::time_put& facet = USE_FACET(*locale, std::time_put ); size_t start = 0; std::ostringstream os; for (; valueIter != values.end(); valueIter++) { PUT_FACET(facet, os, &time, spec); Transcoder::decode(os.str().substr(start), *valueIter); start = os.str().length(); (*inc)(time, aprtime); } } } #endif const size_t BUFSIZE = 256; char buf[BUFSIZE]; memset(buf, 0, BUFSIZE); apr_size_t retsize = 0; for (; valueIter != values.end(); valueIter++) { apr_status_t stat = apr_strftime(buf, &retsize, BUFSIZE, aprspec, &aprtime); (*inc)(time, aprtime); if (stat == APR_SUCCESS) { Transcoder::decode(std::string(buf, retsize), *valueIter); } else { valueIter->append(1, (logchar) 0x3F); } } } private: /** * Private copy constructor. */ PatternToken(const PatternToken&); /** * Private assignment operator. */ PatternToken& operator=(const PatternToken&); }; class LiteralToken : public PatternToken { public: LiteralToken( logchar ch1, int count1 ) : ch( ch1 ), count( count1 ) { } void format( LogString& s, const apr_time_exp_t&, Pool& /* p */ ) const { s.append( count, ch ); } private: logchar ch; int count; }; class EraToken : public PatternToken { public: EraToken( int /* count */, const std::locale* /* locale */ ) { } void format(LogString& s, const apr_time_exp_t& /* tm */, Pool& /* p */ ) const { s.append(1, (logchar) 0x41 /* 'A' */); s.append(1, (logchar) 0x44 /* 'D' */); } }; class NumericToken : public PatternToken { public: NumericToken( size_t width1 ) : width( width1 ) { } virtual int getField( const apr_time_exp_t& tm ) const = 0; void format( LogString& s, const apr_time_exp_t& tm, Pool& p ) const { size_t initialLength = s.length(); StringHelper::toString( getField( tm ), p, s ); size_t finalLength = s.length(); if ( initialLength + width > finalLength ) { s.insert( initialLength, ( initialLength + width ) - finalLength, (logchar) 0x30 /* '0' */); } } private: size_t width; }; class YearToken : public NumericToken { public: YearToken( int width1 ) : NumericToken( width1 ) { } int getField( const apr_time_exp_t& tm ) const { return 1900 + tm.tm_year; } }; class MonthToken : public NumericToken { public: MonthToken( int width1 ) : NumericToken( width1 ) { } int getField( const apr_time_exp_t& tm ) const { return tm.tm_mon + 1; } }; class AbbreviatedMonthNameToken : public PatternToken { public: AbbreviatedMonthNameToken(int, const std::locale* locale) : names( 12 ) { renderFacet(locale, PatternToken::incrementMonth, 'b', 0x62, "%b", names); } void format(LogString& s, const apr_time_exp_t& tm, Pool& /* p */ ) const { s.append( names[tm.tm_mon] ); } private: std::vector < LogString > names; }; class FullMonthNameToken : public PatternToken { public: FullMonthNameToken( int width, const std::locale* locale) : names( 12 ) { renderFacet(locale, PatternToken::incrementMonth, 'B', 0x42, "%B", names); } void format( LogString& s, const apr_time_exp_t& tm, Pool& /* p */ ) const { s.append( names[tm.tm_mon] ); } private: std::vector < LogString > names; }; class WeekInYearToken : public NumericToken { public: WeekInYearToken( int width1 ) : NumericToken( width1 ) { } int getField( const apr_time_exp_t& tm ) const { return tm.tm_yday / 7; } }; class WeekInMonthToken : public NumericToken { public: WeekInMonthToken( int width1 ) : NumericToken( width1 ) { } int getField( const apr_time_exp_t& tm ) const { return tm.tm_mday / 7; } }; class DayInMonthToken : public NumericToken { public: DayInMonthToken( int width1 ) : NumericToken( width1 ) { } int getField( const apr_time_exp_t& tm ) const { return tm.tm_mday; } }; class DayInYearToken : public NumericToken { public: DayInYearToken( int width1 ) : NumericToken( width1 ) { } int getField( const apr_time_exp_t& tm ) const { return tm.tm_yday; } }; class DayOfWeekInMonthToken : public NumericToken { public: DayOfWeekInMonthToken( int width1 ) : NumericToken( width1 ) { } int getField( const apr_time_exp_t& /* tm */ ) const { return -1; } }; class AbbreviatedDayNameToken : public PatternToken { public: AbbreviatedDayNameToken( int width, const std::locale* locale) : names( 7 ) { renderFacet(locale, PatternToken::incrementDay, 'a', 0x61, "%a", names); } void format( LogString& s, const apr_time_exp_t& tm, Pool& /* p */ ) const { s.append( names[tm.tm_wday] ); } private: std::vector < LogString > names; }; class FullDayNameToken : public PatternToken { public: FullDayNameToken( int width, const std::locale* locale) : names( 7 ) { renderFacet(locale, PatternToken::incrementDay, 'A', 0x41, "%A", names); } void format( LogString& s, const apr_time_exp_t& tm, Pool& /* p */ ) const { s.append( names[tm.tm_wday] ); } private: std::vector < LogString > names; }; class MilitaryHourToken : public NumericToken { public: MilitaryHourToken( int width1, int offset1 ) : NumericToken( width1 ), offset( offset1 ) { } int getField( const apr_time_exp_t& tm ) const { return tm.tm_hour + offset; } private: int offset; }; class HourToken : public NumericToken { public: HourToken( int width1, int /* offset1 */ ) : NumericToken( width1 ), offset( 0 ) { } int getField( const apr_time_exp_t& tm ) const { return ( ( tm.tm_hour + 12 - offset ) % 12 ) + offset; } private: int offset; }; class MinuteToken : public NumericToken { public: MinuteToken( int width1 ) : NumericToken( width1 ) { } int getField( const apr_time_exp_t& tm ) const { return tm.tm_min; } }; class SecondToken : public NumericToken { public: SecondToken( int width1 ) : NumericToken( width1 ) { } int getField( const apr_time_exp_t& tm ) const { return tm.tm_sec; } }; class MillisecondToken : public NumericToken { public: MillisecondToken( int width1 ) : NumericToken( width1 ) { } int getField( const apr_time_exp_t& tm ) const { return tm.tm_usec / 1000; } }; class MicrosecondToken : public NumericToken { public: MicrosecondToken( int width1 ) : NumericToken( width1 ) { } int getField( const apr_time_exp_t& tm ) const { return tm.tm_usec; } }; class AMPMToken : public PatternToken { public: AMPMToken( int width, const std::locale* locale) : names( 2 ) { renderFacet(locale, PatternToken::incrementHalfDay, 'p', 0x70, "%p", names); } void format( LogString& s, const apr_time_exp_t& tm, Pool& /* p */ ) const { s.append( names[tm.tm_hour / 12] ); } private: std::vector < LogString > names; }; class GeneralTimeZoneToken : public PatternToken { public: GeneralTimeZoneToken( int /* width */ ) { } void format( LogString& s, const apr_time_exp_t&, Pool& /* p */ ) const { s.append(timeZone->getID()); } void setTimeZone( const TimeZonePtr& zone ) { timeZone = zone; } private: TimeZonePtr timeZone; }; class RFC822TimeZoneToken : public PatternToken { public: RFC822TimeZoneToken( int /* width */ ) { } void format( LogString& s, const apr_time_exp_t& tm, Pool& p ) const { if ( tm.tm_gmtoff == 0 ) { s.append( 1, (logchar) 0x5A /* 'Z' */ ); } else { apr_int32_t off = tm.tm_gmtoff; size_t basePos = s.length(); s.append( LOG4CXX_STR( "+0000" ) ); if ( off < 0 ) { s[basePos] = 0x2D; // '-' off = -off; } LogString hours; StringHelper::toString( off / 3600, p, hours ); size_t hourPos = basePos + 2; // // assumes that point values for 0-9 are same between char and wchar_t // for ( size_t i = hours.length(); i-- > 0; ) { s[hourPos--] = hours[i]; } LogString min; StringHelper::toString( ( off % 3600 ) / 60, p, min ); size_t minPos = basePos + 4; // // assumes that point values for 0-9 are same between char and wchar_t // for ( size_t j = min.length(); j-- > 0; ) { s[minPos--] = min[j]; } } } }; } } } using namespace LOG4CXX_NS::helpers::SimpleDateFormatImpl; void SimpleDateFormat::addToken(const logchar spec, const int repeat, const std::locale* locale, std::vector < PatternToken* >& pattern ) { PatternToken* token = NULL; switch ( spec ) { case 0x47: // 'G' token = ( new EraToken( repeat, locale ) ); break; case 0x79: // 'y' token = ( new YearToken( repeat ) ); break; case 0x4D: // 'M' if ( repeat <= 2 ) { token = ( new MonthToken( repeat ) ); } else if ( repeat <= 3 ) { token = ( new AbbreviatedMonthNameToken( repeat, locale ) ); } else { token = ( new FullMonthNameToken( repeat, locale ) ); } break; case 0x77: // 'w' token = ( new WeekInYearToken( repeat ) ); break; case 0x57: // 'W' token = ( new WeekInMonthToken( repeat ) ); break; case 0x44: // 'D' token = ( new DayInYearToken( repeat ) ); break; case 0x64: // 'd' token = ( new DayInMonthToken( repeat ) ); break; case 0x46: // 'F' token = ( new DayOfWeekInMonthToken( repeat ) ); break; case 0x45: // 'E' if ( repeat <= 3 ) { token = ( new AbbreviatedDayNameToken( repeat, locale ) ); } else { token = ( new FullDayNameToken( repeat, locale ) ); } break; case 0x61: // 'a' token = ( new AMPMToken( repeat, locale ) ); break; case 0x48: // 'H' token = ( new MilitaryHourToken( repeat, 0 ) ); break; case 0x6B: // 'k' token = ( new MilitaryHourToken( repeat, 1 ) ); break; case 0x4B: // 'K' token = ( new HourToken( repeat, 0 ) ); break; case 0x68: // 'h' token = ( new HourToken( repeat, 1 ) ); break; case 0x6D: // 'm' token = ( new MinuteToken( repeat ) ); break; case 0x73: // 's' token = ( new SecondToken( repeat ) ); break; case 0x53: // 'S' if ( repeat == 6 ) { token = ( new MicrosecondToken( repeat ) ); } else { // It would be nice to support patterns with arbitrary // subsecond precision (like "s.S" or "s.SSSS"), but we // don't; so this is a back-compatible default. token = ( new MillisecondToken( repeat ) ); } break; case 0x7A: // 'z' token = ( new GeneralTimeZoneToken( repeat ) ); break; case 0x5A: // 'Z' token = ( new RFC822TimeZoneToken( repeat ) ); break; default: token = ( new LiteralToken( spec, repeat ) ); } assert( token != NULL ); pattern.push_back( token ); } void SimpleDateFormat::parsePattern( const LogString& fmt, const std::locale* locale, std::vector < PatternToken* >& pattern ) { if ( !fmt.empty() ) { LogString::const_iterator iter = fmt.begin(); int repeat = 1; logchar prevChar = * iter; for ( iter++; iter != fmt.end(); iter++ ) { if ( * iter == prevChar ) { repeat++; } else { addToken( prevChar, repeat, locale, pattern ); prevChar = * iter; repeat = 1; } } addToken( prevChar, repeat, locale, pattern ); } } struct SimpleDateFormat::SimpleDateFormatPrivate{ SimpleDateFormatPrivate() : timeZone(TimeZone::getDefault()) {} /** * Time zone. */ TimeZonePtr timeZone; /** * List of tokens. */ PatternTokenList pattern; }; SimpleDateFormat::SimpleDateFormat( const LogString& fmt ) : m_priv(std::make_unique()) { #if LOG4CXX_HAS_STD_LOCALE std::locale defaultLocale; parsePattern( fmt, & defaultLocale, m_priv->pattern ); #else parsePattern( fmt, NULL, m_priv->pattern ); #endif for (auto const& item : m_priv->pattern) { item->setTimeZone( m_priv->timeZone ); } } SimpleDateFormat::SimpleDateFormat( const LogString& fmt, const std::locale* locale ) : m_priv(std::make_unique()) { parsePattern( fmt, locale, m_priv->pattern ); for (auto const& item : m_priv->pattern) { item->setTimeZone( m_priv->timeZone ); } } SimpleDateFormat::~SimpleDateFormat() { for (auto item : m_priv->pattern) { delete item; } } void SimpleDateFormat::format( LogString& s, log4cxx_time_t time, Pool& p ) const { apr_time_exp_t exploded; apr_status_t stat = m_priv->timeZone->explode( & exploded, time ); if ( stat == APR_SUCCESS ) { for ( PatternTokenList::const_iterator iter = m_priv->pattern.begin(); iter != m_priv->pattern.end(); iter++ ) { ( * iter )->format( s, exploded, p ); } } } void SimpleDateFormat::setTimeZone( const TimeZonePtr& zone ) { m_priv->timeZone = zone; } apache-log4cxx-1.3.1/src/main/cpp/nteventlogappender.cpp0000644000175100001770000002200614721727031022601 0ustar runnerdocker/* * 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. */ #if (defined(WIN32) || defined(_WIN32)) && !defined(_WIN32_WCE) #include #include #include #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; using namespace LOG4CXX_NS::nt; #define priv static_cast(m_priv.get()) struct NTEventLogAppender::NTEventLogAppenderPrivate : public AppenderSkeleton::AppenderSkeletonPrivate { NTEventLogAppenderPrivate() : hEventLog(nullptr), pCurrentUserSID(nullptr) {} NTEventLogAppenderPrivate( LayoutPtr layout ) : AppenderSkeletonPrivate(layout), hEventLog(nullptr), pCurrentUserSID(nullptr) {} // Data LogString server; LogString log; LogString source; HANDLE hEventLog; SID* pCurrentUserSID; }; class CCtUserSIDHelper { public: static bool FreeSid(SID* pSid) { return ::HeapFree(GetProcessHeap(), 0, (LPVOID)pSid) != 0; } static bool CopySid(SID * * ppDstSid, SID* pSrcSid) { bool bSuccess = false; DWORD dwLength = ::GetLengthSid(pSrcSid); *ppDstSid = (SID*) ::HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwLength); if (::CopySid(dwLength, *ppDstSid, pSrcSid)) { bSuccess = true; } else { FreeSid(*ppDstSid); } return bSuccess; } static bool GetCurrentUserSID(SID * * ppSid) { bool bSuccess = false; // Pseudohandle so don't need to close it HANDLE hProcess = ::GetCurrentProcess(); HANDLE hToken = NULL; if (::OpenProcessToken(hProcess, TOKEN_QUERY, &hToken)) { // Get the required size DWORD tusize = 0; GetTokenInformation(hToken, TokenUser, NULL, 0, &tusize); TOKEN_USER* ptu = (TOKEN_USER*)new BYTE[tusize]; if (GetTokenInformation(hToken, TokenUser, (LPVOID)ptu, tusize, &tusize)) { bSuccess = CopySid(ppSid, (SID*)ptu->User.Sid); } CloseHandle(hToken); delete [] ptu; } return bSuccess; } }; IMPLEMENT_LOG4CXX_OBJECT(NTEventLogAppender) NTEventLogAppender::NTEventLogAppender() : AppenderSkeleton(std::make_unique()) { } NTEventLogAppender::NTEventLogAppender(const LogString& server, const LogString& log, const LogString& source, const LayoutPtr& layout) : AppenderSkeleton(std::make_unique(layout)) { Pool pool; priv->server = server; priv->log = log; priv->source = source; activateOptions(pool); } NTEventLogAppender::~NTEventLogAppender() { finalize(); } void NTEventLogAppender::close() { if (priv->hEventLog != NULL) { ::DeregisterEventSource(priv->hEventLog); priv->hEventLog = NULL; } if (priv->pCurrentUserSID != NULL) { CCtUserSIDHelper::FreeSid((::SID*) priv->pCurrentUserSID); priv->pCurrentUserSID = NULL; } } void NTEventLogAppender::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("SERVER"), LOG4CXX_STR("server"))) { priv->server = value; } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("LOG"), LOG4CXX_STR("log"))) { priv->log = value; } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("SOURCE"), LOG4CXX_STR("source"))) { priv->source = value; } else { AppenderSkeleton::setOption(option, value); } } void NTEventLogAppender::activateOptions(Pool&) { if (priv->source.empty()) { LogLog::warn( ((LogString) LOG4CXX_STR("Source option not set for appender [")) + this->m_priv->name + LOG4CXX_STR("].")); return; } if (priv->log.empty()) { priv->log = LOG4CXX_STR("Application"); } close(); // current user security identifier CCtUserSIDHelper::GetCurrentUserSID((::SID**) &priv->pCurrentUserSID); addRegistryInfo(); LOG4CXX_ENCODE_WCHAR(wsource, priv->source); LOG4CXX_ENCODE_WCHAR(wserver, priv->server); priv->hEventLog = ::RegisterEventSourceW( wserver.empty() ? NULL : wserver.c_str(), wsource.c_str()); if (priv->hEventLog == NULL) { LogString msg(LOG4CXX_STR("Cannot register NT EventLog -- server: '")); msg.append(priv->server); msg.append(LOG4CXX_STR("' source: '")); msg.append(priv->source); LogLog::error(msg); LogLog::error(getErrorString(LOG4CXX_STR("RegisterEventSource"))); } } void NTEventLogAppender::append(const LoggingEventPtr& event, Pool& p) { if (priv->hEventLog == NULL) { LogLog::warn(LOG4CXX_STR("NT EventLog not opened.")); return; } LogString oss; this->m_priv->layout->format(oss, event, p); wchar_t* msgs = Transcoder::wencode(oss, p); BOOL bSuccess = ::ReportEventW( priv->hEventLog, getEventType(event), getEventCategory(event), 0x1000, priv->pCurrentUserSID, 1, 0, (LPCWSTR*) &msgs, NULL); if (!bSuccess) { LogLog::error(getErrorString(LOG4CXX_STR("ReportEvent"))); } } /* * Add this source with appropriate configuration keys to the registry. */ void NTEventLogAppender::addRegistryInfo() { DWORD disposition = 0; ::HKEY hkey = 0; LogString subkey(LOG4CXX_STR("SYSTEM\\CurrentControlSet\\Services\\EventLog\\")); subkey.append(priv->log); subkey.append(1, (logchar) 0x5C /* '\\' */); subkey.append(priv->source); LOG4CXX_ENCODE_WCHAR(wsubkey, subkey); long stat = RegCreateKeyExW(HKEY_LOCAL_MACHINE, wsubkey.c_str(), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, NULL, &hkey, &disposition); if (stat == ERROR_SUCCESS && disposition == REG_CREATED_NEW_KEY) { HMODULE hmodule = GetModuleHandleW(L"log4cxx"); if (hmodule == NULL) { hmodule = GetModuleHandleW(0); } wchar_t modpath[_MAX_PATH]; DWORD modlen = GetModuleFileNameW(hmodule, modpath, _MAX_PATH - 1); if (modlen > 0) { modpath[modlen] = 0; RegSetValueExW(hkey, L"EventMessageFile", 0, REG_SZ, (LPBYTE) modpath, (DWORD)(wcslen(modpath) * sizeof(wchar_t))); RegSetValueExW(hkey, L"CategoryMessageFile", 0, REG_SZ, (LPBYTE) modpath, (DWORD)(wcslen(modpath) * sizeof(wchar_t))); DWORD typesSupported = 7; DWORD categoryCount = 6; RegSetValueExW(hkey, L"TypesSupported", 0, REG_DWORD, (LPBYTE)&typesSupported, sizeof(DWORD)); RegSetValueExW(hkey, L"CategoryCount", 0, REG_DWORD, (LPBYTE)&categoryCount, sizeof(DWORD)); } } RegCloseKey(hkey); return; } WORD NTEventLogAppender::getEventType(const LoggingEventPtr& event) { int priority = event->getLevel()->toInt(); WORD type = EVENTLOG_SUCCESS; if (priority >= Level::INFO_INT) { type = EVENTLOG_INFORMATION_TYPE; if (priority >= Level::WARN_INT) { type = EVENTLOG_WARNING_TYPE; if (priority >= Level::ERROR_INT) { type = EVENTLOG_ERROR_TYPE; } } } return type; } WORD NTEventLogAppender::getEventCategory(const LoggingEventPtr& event) { int priority = event->getLevel()->toInt(); WORD category = 1; if (priority >= Level::DEBUG_INT) { category = 2; if (priority >= Level::INFO_INT) { category = 3; if (priority >= Level::WARN_INT) { category = 4; if (priority >= Level::ERROR_INT) { category = 5; if (priority >= Level::FATAL_INT) { category = 6; } } } } } return category; } LogString NTEventLogAppender::getErrorString(const LogString& function) { Pool p; enum { MSGSIZE = 5000 }; wchar_t* lpMsgBuf = (wchar_t*) p.palloc(MSGSIZE * sizeof(wchar_t)); DWORD dw = GetLastError(); FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM, NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), lpMsgBuf, MSGSIZE, NULL ); LogString msg(function); msg.append(LOG4CXX_STR(" failed with error ")); StringHelper::toString((size_t) dw, p, msg); msg.append(LOG4CXX_STR(": ")); Transcoder::decode(lpMsgBuf, msg); return msg; } void NTEventLogAppender::setSource(const LogString& source) { priv->source.assign(source); } const LogString& NTEventLogAppender::getSource() const { return priv->source; } void NTEventLogAppender::setLog(const LogString& log) { priv->log.assign(log); } const LogString& NTEventLogAppender::getLog() const { return priv->log; } void NTEventLogAppender::setServer(const LogString& server) { priv->server.assign(server); } const LogString& NTEventLogAppender::getServer() const { return priv->server; } #endif // WIN32 apache-log4cxx-1.3.1/src/main/cpp/systemoutwriter.cpp0000644000175100001770000000356114721727031022213 0ustar runnerdocker/* * 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. */ #include #include #include #include #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(SystemOutWriter) SystemOutWriter::SystemOutWriter() { } SystemOutWriter::~SystemOutWriter() { } void SystemOutWriter::close(Pool& /* p */ ) { } void SystemOutWriter::flush(Pool& /* p */ ) { flush(); } void SystemOutWriter::write(const LogString& str, Pool& /* p */ ) { write(str); } bool SystemOutWriter::isWide() { #if LOG4CXX_FORCE_WIDE_CONSOLE return true; #elif LOG4CXX_FORCE_BYTE_CONSOLE || !LOG4CXX_HAS_FWIDE return false; #else return fwide(stdout, 0) > 0; #endif } void SystemOutWriter::write(const LogString& str) { #if LOG4CXX_WCHAR_T_API if (isWide()) { LOG4CXX_ENCODE_WCHAR(msg, str); fputws(msg.c_str(), stdout); return; } #endif LOG4CXX_ENCODE_CHAR(msg, str); fputs(msg.c_str(), stdout); } void SystemOutWriter::flush() { fflush(stdout); } apache-log4cxx-1.3.1/src/main/cpp/propertysetter.cpp0000644000175100001770000000563714721727031022023 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::config; PropertySetter::PropertySetter(const helpers::ObjectPtr& obj1) : obj(obj1) { } void PropertySetter::setProperties(const helpers::ObjectPtr& obj, helpers::Properties& properties, const LogString& prefix, Pool& p) { PropertySetter(obj).setProperties(properties, prefix, p); } void PropertySetter::setProperties(helpers::Properties& properties, const LogString& prefix, Pool& p) { size_t len = prefix.length(); for (auto key : properties.propertyNames()) { // handle only properties that start with the desired frefix. if (key.find(prefix) == 0) { // ignore key if it contains dots after the prefix if (key.find(0x2E /* '.' */, len + 1) != LogString::npos) { continue; } LogString value = OptionConverter::findAndSubst(key, properties); key = key.substr(len); if (key == LOG4CXX_STR("layout") && obj != 0 && obj->instanceof(Appender::getStaticClass())) { continue; } setProperty(key, value, p); } } activate(p); } void PropertySetter::setProperty(const LogString& option, const LogString& value, Pool&) { if (value.empty()) { return; } if (obj != 0 && obj->instanceof(OptionHandler::getStaticClass())) { if (LogLog::isDebugEnabled()) { LogLog::debug(LOG4CXX_STR("Setting option name=[") + option + LOG4CXX_STR("], value=[") + value + LOG4CXX_STR("]")); } OptionHandlerPtr handler = LOG4CXX_NS::cast(obj); handler->setOption(option, value); } } void PropertySetter::activate(Pool& p) { if (obj != 0 && obj->instanceof(OptionHandler::getStaticClass())) { OptionHandlerPtr handler = LOG4CXX_NS::cast(obj); handler->activateOptions(p); } } apache-log4cxx-1.3.1/src/main/cpp/logger.cpp0000644000175100001770000007150714721727031020166 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #include #include #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; using namespace LOG4CXX_NS::spi; struct Logger::LoggerPrivate { LoggerPrivate(const LogString& name1) : name(name1) , repositoryRaw(0) , additive(true) , levelData(Level::getData()) {} /** The name of this logger. */ LogString name; /** The assigned level of this logger. The level variable need not be assigned a value in which case it is inherited form the hierarchy. */ LevelPtr level; /** The parent of this logger. All loggers have at least one ancestor which is the root logger. */ LoggerPtr parent; /** The resourceBundle for localized messages. @see setResourceBundle, getResourceBundle */ helpers::ResourceBundlePtr resourceBundle; // Loggers need to know what Hierarchy they are in spi::LoggerRepository* repositoryRaw; helpers::AppenderAttachableImpl aai; /** Additivity is set to true by default, that is children inherit the appenders of their ancestors by default. If this variable is set to false then the appenders found in the ancestors of this logger are not used. However, the children of this logger will inherit its appenders, unless the children have their additivity flag set to false too. See the user manual for more details. */ bool additive; Level::DataPtr levelData; }; IMPLEMENT_LOG4CXX_OBJECT(Logger) Logger::Logger(const LogString& name1) : m_priv(std::make_unique(name1)) , m_threshold(0) { } #if LOG4CXX_ABI_VERSION <= 15 Logger::Logger(Pool& p, const LogString& name) : Logger(name) { } #endif Logger::~Logger() { } void Logger::addAppender(const AppenderPtr newAppender) { m_priv->aai.addAppender(newAppender); if (auto rep = getHierarchy()) { rep->fireAddAppenderEvent(this, newAppender.get()); } } void Logger::reconfigure( const std::vector& appenders, bool additive1 ) { m_priv->additive = additive1; m_priv->aai.removeAllAppenders(); for (auto const& item : appenders) { m_priv->aai.addAppender(item); if (auto rep = getHierarchy()) { rep->fireAddAppenderEvent(this, item.get()); } } } void Logger::callAppenders(const spi::LoggingEventPtr& event, Pool& p) const { int writes = 0; for (const Logger* logger = this; logger != 0; logger = logger->m_priv->parent.get()) { writes += logger->m_priv->aai.appendLoopOnAppenders(event, p); if (!logger->m_priv->additive) { break; } } auto rep = getHierarchy(); if (writes == 0 && rep) { rep->emitNoAppenderWarning(const_cast(this)); } } void Logger::closeNestedAppenders() { for (auto& item : getAllAppenders()) { item->close(); } } void Logger::addEvent(const LevelPtr& level, std::string&& message, const LocationInfo& location) const { if (!getHierarchy()) // Has removeHierarchy() been called? return; #if LOG4CXX_LOGCHAR_IS_UTF8 auto event = std::make_shared(m_priv->name, level, location, std::move(message)); #else LOG4CXX_DECODE_CHAR(msg, message); auto event = std::make_shared(m_priv->name, level, location, std::move(msg)); #endif Pool p; callAppenders(event, p); } void Logger::addFatalEvent(std::string&& message, const LocationInfo& location) const { addEvent(m_priv->levelData->Fatal, std::move(message), location); } void Logger::addErrorEvent(std::string&& message, const LocationInfo& location) const { addEvent(m_priv->levelData->Error, std::move(message), location); } void Logger::addWarnEvent(std::string&& message, const LocationInfo& location) const { addEvent(m_priv->levelData->Warn, std::move(message), location); } void Logger::addInfoEvent(std::string&& message, const LocationInfo& location) const { addEvent(m_priv->levelData->Info, std::move(message), location); } void Logger::addDebugEvent(std::string&& message, const LocationInfo& location) const { addEvent(m_priv->levelData->Debug, std::move(message), location); } void Logger::addTraceEvent(std::string&& message, const LocationInfo& location) const { addEvent(m_priv->levelData->Trace, std::move(message), location); } void Logger::forcedLog(const LevelPtr& level, const std::string& message, const LocationInfo& location) const { if (!getHierarchy()) // Has removeHierarchy() been called? return; #if LOG4CXX_LOGCHAR_IS_UTF8 auto event = std::make_shared(m_priv->name, level, message, location); #else LOG4CXX_DECODE_CHAR(msg, message); auto event = std::make_shared(m_priv->name, level, location, std::move(msg)); #endif Pool p; callAppenders(event, p); } void Logger::forcedLog(const LevelPtr& level1, const std::string& message) const { forcedLog(level1, message, LocationInfo::getLocationUnavailable()); } void Logger::addEventLS(const LevelPtr& level, LogString&& message, const LocationInfo& location) const { if (!getHierarchy()) // Has removeHierarchy() been called? return; auto event = std::make_shared(m_priv->name, level, location, std::move(message)); Pool p; callAppenders(event, p); } void Logger::forcedLogLS(const LevelPtr& level1, const LogString& message, const LocationInfo& location) const { if (!getHierarchy()) // Has removeHierarchy() been called? return; auto event = std::make_shared(m_priv->name, level1, message, location); Pool p; callAppenders(event, p); } bool Logger::getAdditivity() const { return m_priv->additive; } AppenderList Logger::getAllAppenders() const { return m_priv->aai.getAllAppenders(); } AppenderPtr Logger::getAppender(const LogString& name1) const { return m_priv->aai.getAppender(name1); } const LevelPtr& Logger::getEffectiveLevel() const { for (const Logger* l = this; l != 0; l = l->m_priv->parent.get()) { if (l->m_priv->level != 0) { return l->m_priv->level; } } throw NullPointerException(LOG4CXX_STR("No level specified for logger or ancestors.")); #if LOG4CXX_RETURN_AFTER_THROW return m_priv->level; #endif } LoggerRepository* Logger::getLoggerRepository() const { return m_priv->repositoryRaw; } LoggerRepository* Logger::getHierarchy() const { return m_priv->repositoryRaw; } ResourceBundlePtr Logger::getResourceBundle() const { for (const Logger* l = this; l != 0; l = l->m_priv->parent.get()) { if (l->m_priv->resourceBundle != 0) { return l->m_priv->resourceBundle; } } // It might be the case that there is no resource bundle return 0; } LogString Logger::getResourceBundleString(const LogString& key) const { ResourceBundlePtr rb = getResourceBundle(); // This is one of the rare cases where we can use logging in order // to report errors from within log4j. if (rb == 0) { return LogString(); } else { try { return rb->getString(key); } catch (MissingResourceException&) { logLS(Level::getError(), LOG4CXX_STR("No resource is associated with key \"") + key + LOG4CXX_STR("\"."), LocationInfo::getLocationUnavailable()); return LogString(); } } } LoggerPtr Logger::getParent() const { return m_priv->parent; } const LevelPtr& Logger::getLevel() const { return m_priv->level; } bool Logger::isAttached(const AppenderPtr appender) const { return m_priv->aai.isAttached(appender); } bool Logger::isTraceEnabled() const { auto rep = getHierarchy(); if (!rep || rep->isDisabled(Level::TRACE_INT)) { return false; } return getEffectiveLevel()->toInt() <= Level::TRACE_INT; } bool Logger::isDebugEnabled() const { auto rep = getHierarchy(); if (!rep || rep->isDisabled(Level::DEBUG_INT)) { return false; } return getEffectiveLevel()->toInt() <= Level::DEBUG_INT; } bool Logger::isEnabledFor(const LevelPtr& level1) const { auto rep = getHierarchy(); if (!rep || rep->isDisabled(level1->toInt())) { return false; } return level1->isGreaterOrEqual(getEffectiveLevel()); } bool Logger::isInfoEnabled() const { auto rep = getHierarchy(); if (!rep || rep->isDisabled(Level::INFO_INT)) { return false; } return getEffectiveLevel()->toInt() <= Level::INFO_INT; } bool Logger::isErrorEnabled() const { auto rep = getHierarchy(); if (!rep || rep->isDisabled(Level::ERROR_INT)) { return false; } return getEffectiveLevel()->toInt() <= Level::ERROR_INT; } bool Logger::isWarnEnabled() const { auto rep = getHierarchy(); if (!rep || rep->isDisabled(Level::WARN_INT)) { return false; } return getEffectiveLevel()->toInt() <= Level::WARN_INT; } bool Logger::isFatalEnabled() const { auto rep = getHierarchy(); if (!rep || rep->isDisabled(Level::FATAL_INT)) { return false; } return getEffectiveLevel()->toInt() <= Level::FATAL_INT; } /*void Logger::l7dlog(const LevelPtr& level, const String& key, const char* file, int line) { auto rep = getHierarchy(); if (!rep || rep->isDisabled(level->level)) { return; } if (level->isGreaterOrEqual(getEffectiveLevel())) { String msg = getResourceBundleString(key); // if message corresponding to 'key' could not be found in the // resource bundle, then default to 'key'. if (msg.empty()) { msg = key; } forcedLog(FQCN, level, msg, file, line); } }*/ void Logger::l7dlog(const LevelPtr& level1, const LogString& key, const LocationInfo& location, const std::vector& params) const { auto rep = getHierarchy(); if (!rep || rep->isDisabled(level1->toInt())) { return; } if (level1->isGreaterOrEqual(getEffectiveLevel())) { LogString pattern = getResourceBundleString(key); LogString msg; if (pattern.empty()) { msg = key; } else { msg = StringHelper::format(pattern, params); } addEventLS(level1, std::move(msg), location); } } void Logger::l7dlog(const LevelPtr& level1, const std::string& key, const LocationInfo& location) const { LOG4CXX_DECODE_CHAR(lkey, key); std::vector values(0); l7dlog(level1, lkey, location, values); } void Logger::l7dlog(const LevelPtr& level1, const std::string& key, const LocationInfo& location, const std::string& val1) const { LOG4CXX_DECODE_CHAR(lkey, key); LOG4CXX_DECODE_CHAR(lval1, val1); std::vector values(1); values[0] = lval1; l7dlog(level1, lkey, location, values); } void Logger::l7dlog(const LevelPtr& level1, const std::string& key, const LocationInfo& location, const std::string& val1, const std::string& val2) const { LOG4CXX_DECODE_CHAR(lkey, key); LOG4CXX_DECODE_CHAR(lval1, val1); LOG4CXX_DECODE_CHAR(lval2, val2); std::vector values(2); values[0] = lval1; values[1] = lval2; l7dlog(level1, lkey, location, values); } void Logger::l7dlog(const LevelPtr& level1, const std::string& key, const LocationInfo& location, const std::string& val1, const std::string& val2, const std::string& val3) const { LOG4CXX_DECODE_CHAR(lkey, key); LOG4CXX_DECODE_CHAR(lval1, val1); LOG4CXX_DECODE_CHAR(lval2, val2); LOG4CXX_DECODE_CHAR(lval3, val3); std::vector values(3); values[0] = lval1; values[1] = lval2; values[2] = lval3; l7dlog(level1, lkey, location, values); } void Logger::removeAllAppenders() { AppenderList currentAppenders = m_priv->aai.getAllAppenders(); m_priv->aai.removeAllAppenders(); auto rep = getHierarchy(); if(rep){ for(AppenderPtr appender : currentAppenders){ rep->fireRemoveAppenderEvent(this, appender.get()); } } } void Logger::removeAppender(const AppenderPtr appender) { m_priv->aai.removeAppender(appender); if (auto rep = getHierarchy()) { rep->fireRemoveAppenderEvent(this, appender.get()); } } void Logger::removeAppender(const LogString& name1) { AppenderPtr appender = m_priv->aai.getAppender(name1); if(appender){ removeAppender(appender); } } void Logger::removeHierarchy() { m_priv->repositoryRaw = 0; } void Logger::setAdditivity(bool additive1) { m_priv->additive = additive1; } void Logger::setHierarchy(spi::LoggerRepository* repository1) { m_priv->repositoryRaw = repository1; } void Logger::setParent(LoggerPtr parentLogger) { m_priv->parent = parentLogger; updateThreshold(); } void Logger::setLevel(const LevelPtr level1) { if (m_priv->level != level1) { m_priv->level = level1; updateThreshold(); if (auto rep = dynamic_cast(getHierarchy())) rep->updateChildren(this); } } void Logger::updateThreshold() { m_threshold = getEffectiveLevel()->toInt(); } const LogString& Logger::getName() const { return m_priv->name; } LoggerPtr Logger::getLogger(const std::string& name) { return LogManager::getLogger(name); } LoggerPtr Logger::getLogger(const char* const name) { return LogManager::getLogger(name); } void Logger::setResourceBundle(const helpers::ResourceBundlePtr& bundle) { m_priv->resourceBundle = bundle; } LoggerPtr Logger::getRootLogger() { return LogManager::getRootLogger(); } LoggerPtr Logger::getLoggerLS(const LogString& name, const spi::LoggerFactoryPtr& factory) { return LogManager::getLoggerLS(name, factory); } void Logger::getName(std::string& rv) const { Transcoder::encode(m_priv->name, rv); } void Logger::trace(const std::string& msg, const LOG4CXX_NS::spi::LocationInfo& location) const { if (isTraceEnabled()) { forcedLog(m_priv->levelData->Trace, msg, location); } } void Logger::trace(const std::string& msg) const { if (isTraceEnabled()) { forcedLog(m_priv->levelData->Trace, msg); } } void Logger::debug(const std::string& msg, const LOG4CXX_NS::spi::LocationInfo& location) const { if (isDebugEnabled()) { forcedLog(m_priv->levelData->Debug, msg, location); } } void Logger::debug(const std::string& msg) const { if (isDebugEnabled()) { forcedLog(m_priv->levelData->Debug, msg); } } void Logger::error(const std::string& msg, const LOG4CXX_NS::spi::LocationInfo& location) const { if (isErrorEnabled()) { forcedLog(m_priv->levelData->Error, msg, location); } } void Logger::error(const std::string& msg) const { if (isErrorEnabled()) { forcedLog(m_priv->levelData->Error, msg); } } void Logger::fatal(const std::string& msg, const LOG4CXX_NS::spi::LocationInfo& location) const { if (isFatalEnabled()) { forcedLog(m_priv->levelData->Fatal, msg, location); } } void Logger::fatal(const std::string& msg) const { if (isFatalEnabled()) { forcedLog(m_priv->levelData->Fatal, msg); } } void Logger::info(const std::string& msg, const LOG4CXX_NS::spi::LocationInfo& location) const { if (isInfoEnabled()) { forcedLog(m_priv->levelData->Info, msg, location); } } void Logger::info(const std::string& msg) const { if (isInfoEnabled()) { forcedLog(m_priv->levelData->Info, msg); } } void Logger::log(const LevelPtr& level1, const std::string& message, const LOG4CXX_NS::spi::LocationInfo& location) const { if (isEnabledFor(level1)) { forcedLog(level1, message, location); } } void Logger::log(const LevelPtr& level1, const std::string& message) const { if (isEnabledFor(level1)) { forcedLog(level1, message); } } void Logger::logLS(const LevelPtr& level1, const LogString& message, const LOG4CXX_NS::spi::LocationInfo& location) const { if (isEnabledFor(level1)) { forcedLogLS(level1, message, location); } } void Logger::warn(const std::string& msg, const LOG4CXX_NS::spi::LocationInfo& location) const { if (isWarnEnabled()) { forcedLog(m_priv->levelData->Warn, msg, location); } } void Logger::warn(const std::string& msg) const { if (isWarnEnabled()) { forcedLog(m_priv->levelData->Warn, msg); } } LoggerPtr Logger::getLoggerLS(const LogString& name) { return LogManager::getLoggerLS(name); } #if LOG4CXX_WCHAR_T_API void Logger::addEvent(const LevelPtr& level, std::wstring&& message, const LocationInfo& location) const { if (!getHierarchy()) // Has removeHierarchy() been called? return; #if LOG4CXX_LOGCHAR_IS_WCHAR auto event = std::make_shared(m_priv->name, level, location, std::move(message)); #else LOG4CXX_DECODE_WCHAR(msg, message); auto event = std::make_shared(m_priv->name, level, location, std::move(msg)); #endif Pool p; callAppenders(event, p); } void Logger::addFatalEvent(std::wstring&& message, const LocationInfo& location) const { addEvent(m_priv->levelData->Fatal, std::move(message), location); } void Logger::addErrorEvent(std::wstring&& message, const LocationInfo& location) const { addEvent(m_priv->levelData->Error, std::move(message), location); } void Logger::addWarnEvent(std::wstring&& message, const LocationInfo& location) const { addEvent(m_priv->levelData->Warn, std::move(message), location); } void Logger::addInfoEvent(std::wstring&& message, const LocationInfo& location) const { addEvent(m_priv->levelData->Info, std::move(message), location); } void Logger::addDebugEvent(std::wstring&& message, const LocationInfo& location) const { addEvent(m_priv->levelData->Debug, std::move(message), location); } void Logger::addTraceEvent(std::wstring&& message, const LocationInfo& location) const { addEvent(m_priv->levelData->Trace, std::move(message), location); } void Logger::forcedLog(const LevelPtr& level, const std::wstring& message, const LocationInfo& location) const { if (!getHierarchy()) // Has removeHierarchy() been called? return; #if LOG4CXX_LOGCHAR_IS_WCHAR auto event = std::make_shared(m_priv->name, level, message, location); #else LOG4CXX_DECODE_WCHAR(msg, message); auto event = std::make_shared(m_priv->name, level, location, std::move(msg)); #endif Pool p; callAppenders(event, p); } void Logger::forcedLog(const LevelPtr& level1, const std::wstring& message) const { forcedLog(level1, message, LocationInfo::getLocationUnavailable()); } void Logger::getName(std::wstring& rv) const { Transcoder::encode(m_priv->name, rv); } LoggerPtr Logger::getLogger(const std::wstring& name) { return LogManager::getLogger(name); } LoggerPtr Logger::getLogger(const wchar_t* const name) { return LogManager::getLogger(name); } void Logger::trace(const std::wstring& msg, const LOG4CXX_NS::spi::LocationInfo& location) const { if (isTraceEnabled()) { forcedLog(m_priv->levelData->Trace, msg, location); } } void Logger::trace(const std::wstring& msg) const { if (isTraceEnabled()) { forcedLog(m_priv->levelData->Trace, msg); } } void Logger::debug(const std::wstring& msg, const LOG4CXX_NS::spi::LocationInfo& location) const { if (isDebugEnabled()) { forcedLog(m_priv->levelData->Debug, msg, location); } } void Logger::debug(const std::wstring& msg) const { if (isDebugEnabled()) { forcedLog(m_priv->levelData->Debug, msg); } } void Logger::error(const std::wstring& msg, const LOG4CXX_NS::spi::LocationInfo& location) const { if (isErrorEnabled()) { forcedLog(m_priv->levelData->Error, msg, location); } } void Logger::error(const std::wstring& msg) const { if (isErrorEnabled()) { forcedLog(m_priv->levelData->Error, msg); } } void Logger::fatal(const std::wstring& msg, const LOG4CXX_NS::spi::LocationInfo& location) const { if (isFatalEnabled()) { forcedLog(m_priv->levelData->Fatal, msg, location); } } void Logger::fatal(const std::wstring& msg) const { if (isFatalEnabled()) { forcedLog(m_priv->levelData->Fatal, msg); } } void Logger::info(const std::wstring& msg, const LOG4CXX_NS::spi::LocationInfo& location) const { if (isInfoEnabled()) { forcedLog(m_priv->levelData->Info, msg, location); } } void Logger::info(const std::wstring& msg) const { if (isInfoEnabled()) { forcedLog(m_priv->levelData->Info, msg); } } void Logger::log(const LevelPtr& level1, const std::wstring& message, const LOG4CXX_NS::spi::LocationInfo& location) const { if (isEnabledFor(level1)) { forcedLog(level1, message, location); } } void Logger::log(const LevelPtr& level1, const std::wstring& message) const { if (isEnabledFor(level1)) { forcedLog(level1, message); } } void Logger::warn(const std::wstring& msg, const LOG4CXX_NS::spi::LocationInfo& location) const { if (isWarnEnabled()) { forcedLog(m_priv->levelData->Warn, msg, location); } } void Logger::warn(const std::wstring& msg) const { if (isWarnEnabled()) { forcedLog(m_priv->levelData->Warn, msg); } } #endif #if LOG4CXX_UNICHAR_API void Logger::addEvent(const LevelPtr& level1, std::basic_string&& message, const LocationInfo& location) const { if (!getHierarchy()) // Has removeHierarchy() been called? return; LOG4CXX_DECODE_UNICHAR(msg, message); auto event = std::make_shared(m_priv->name, level1, location, std::move(msg)); Pool p; callAppenders(event, p); } void Logger::addFatalEvent(std::basic_string&& message, const LocationInfo& location) const { addEvent(m_priv->levelData->Fatal, std::move(message), location); } void Logger::addErrorEvent(std::basic_string&& message, const LocationInfo& location) const { addEvent(m_priv->levelData->Error, std::move(message), location); } void Logger::addWarnEvent(std::basic_string&& message, const LocationInfo& location) const { addEvent(m_priv->levelData->Warn, std::move(message), location); } void Logger::addInfoEvent(std::basic_string&& message, const LocationInfo& location) const { addEvent(m_priv->levelData->Info, std::move(message), location); } void Logger::addDebugEvent(std::basic_string&& message, const LocationInfo& location) const { addEvent(m_priv->levelData->Debug, std::move(message), location); } void Logger::addTraceEvent(std::basic_string&& message, const LocationInfo& location) const { addEvent(m_priv->levelData->Trace, std::move(message), location); } void Logger::forcedLog(const LevelPtr& level1, const std::basic_string& message, const LocationInfo& location) const { if (!getHierarchy()) // Has removeHierarchy() been called? return; LOG4CXX_DECODE_UNICHAR(msg, message); auto event = std::make_shared(m_priv->name, level1, location, std::move(msg)); Pool p; callAppenders(event, p); } void Logger::forcedLog(const LevelPtr& level1, const std::basic_string& message) const { if (!getHierarchy()) // Has removeHierarchy() been called? return; LOG4CXX_DECODE_UNICHAR(msg, message); auto event = std::make_shared(m_priv->name, level1, msg, LocationInfo::getLocationUnavailable()); Pool p; callAppenders(event, p); } void Logger::getName(std::basic_string& rv) const { Transcoder::encode(m_priv->name, rv); } LoggerPtr Logger::getLogger(const std::basic_string& name) { return LogManager::getLogger(name); } void Logger::trace(const std::basic_string& msg, const LOG4CXX_NS::spi::LocationInfo& location) const { if (isTraceEnabled()) { forcedLog(m_priv->levelData->Trace, msg, location); } } void Logger::trace(const std::basic_string& msg) const { if (isTraceEnabled()) { forcedLog(m_priv->levelData->Trace, msg); } } void Logger::debug(const std::basic_string& msg, const LOG4CXX_NS::spi::LocationInfo& location) const { if (isDebugEnabled()) { forcedLog(m_priv->levelData->Debug, msg, location); } } void Logger::debug(const std::basic_string& msg) const { if (isDebugEnabled()) { forcedLog(m_priv->levelData->Debug, msg); } } void Logger::error(const std::basic_string& msg, const LOG4CXX_NS::spi::LocationInfo& location) const { if (isErrorEnabled()) { forcedLog(m_priv->levelData->Error, msg, location); } } void Logger::error(const std::basic_string& msg) const { if (isErrorEnabled()) { forcedLog(m_priv->levelData->Error, msg); } } void Logger::fatal(const std::basic_string& msg, const LOG4CXX_NS::spi::LocationInfo& location) const { if (isFatalEnabled()) { forcedLog(m_priv->levelData->Fatal, msg, location); } } void Logger::fatal(const std::basic_string& msg) const { if (isFatalEnabled()) { forcedLog(m_priv->levelData->Fatal, msg); } } void Logger::info(const std::basic_string& msg, const LOG4CXX_NS::spi::LocationInfo& location) const { if (isInfoEnabled()) { forcedLog(m_priv->levelData->Info, msg, location); } } void Logger::info(const std::basic_string& msg) const { if (isInfoEnabled()) { forcedLog(m_priv->levelData->Info, msg); } } void Logger::log(const LevelPtr& level1, const std::basic_string& message, const LOG4CXX_NS::spi::LocationInfo& location) const { if (isEnabledFor(level1)) { forcedLog(level1, message, location); } } void Logger::log(const LevelPtr& level1, const std::basic_string& message) const { if (isEnabledFor(level1)) { forcedLog(level1, message); } } void Logger::warn(const std::basic_string& msg, const LOG4CXX_NS::spi::LocationInfo& location) const { if (isWarnEnabled()) { forcedLog(m_priv->levelData->Warn, msg, location); } } void Logger::warn(const std::basic_string& msg) const { if (isWarnEnabled()) { forcedLog(m_priv->levelData->Warn, msg); } } #endif #if LOG4CXX_CFSTRING_API void Logger::forcedLog(const LevelPtr& level, const CFStringRef& message, const LocationInfo& location) const { if (!getHierarchy()) // Has removeHierarchy() been called? return; LOG4CXX_DECODE_CFSTRING(msg, message); auto event = std::make_shared(m_priv->name, level, location, std::move(msg)); Pool p; callAppenders(event, p); } void Logger::forcedLog(const LevelPtr& level, const CFStringRef& message) const { if (!getHierarchy()) // Has removeHierarchy() been called? return; LOG4CXX_DECODE_CFSTRING(msg, message); auto event = std::make_shared(m_priv->name, level, msg, LocationInfo::getLocationUnavailable()); Pool p; callAppenders(event, p); } void Logger::getName(CFStringRef& rv) const { rv = Transcoder::encode(m_priv->name); } LoggerPtr Logger::getLogger(const CFStringRef& name) { return LogManager::getLogger(name); } void Logger::trace(const CFStringRef& msg, const LOG4CXX_NS::spi::LocationInfo& location) const { if (isTraceEnabled()) { forcedLog(m_priv->levelData->Trace, msg, location); } } void Logger::trace(const CFStringRef& msg) const { if (isTraceEnabled()) { forcedLog(m_priv->levelData->Trace, msg); } } void Logger::debug(const CFStringRef& msg, const LOG4CXX_NS::spi::LocationInfo& location) const { if (isDebugEnabled()) { forcedLog(m_priv->levelData->Debug, msg, location); } } void Logger::debug(const CFStringRef& msg) const { if (isDebugEnabled()) { forcedLog(m_priv->levelData->Debug, msg); } } void Logger::error(const CFStringRef& msg, const LOG4CXX_NS::spi::LocationInfo& location) const { if (isErrorEnabled()) { forcedLog(m_priv->levelData->Error, msg, location); } } void Logger::error(const CFStringRef& msg) const { if (isErrorEnabled()) { forcedLog(m_priv->levelData->Error, msg); } } void Logger::fatal(const CFStringRef& msg, const LOG4CXX_NS::spi::LocationInfo& location) const { if (isFatalEnabled()) { forcedLog(m_priv->levelData->Fatal, msg, location); } } void Logger::fatal(const CFStringRef& msg) const { if (isFatalEnabled()) { forcedLog(m_priv->levelData->Fatal, msg); } } void Logger::info(const CFStringRef& msg, const LOG4CXX_NS::spi::LocationInfo& location) const { if (isInfoEnabled()) { forcedLog(m_priv->levelData->Info, msg, location); } } void Logger::info(const CFStringRef& msg) const { if (isInfoEnabled()) { forcedLog(m_priv->levelData->Info, msg); } } void Logger::log(const LevelPtr& level1, const CFStringRef& message, const LOG4CXX_NS::spi::LocationInfo& location) const { if (isEnabledFor(level1)) { forcedLog(level1, message, location); } } void Logger::log(const LevelPtr& level1, const CFStringRef& message) const { if (isEnabledFor(level1)) { forcedLog(level1, message); } } void Logger::warn(const CFStringRef& msg, const LOG4CXX_NS::spi::LocationInfo& location) const { if (isWarnEnabled()) { forcedLog(m_priv->levelData->Warn, msg, location); } } void Logger::warn(const CFStringRef& msg) const { if (isWarnEnabled()) { forcedLog(m_priv->levelData->Warn, msg); } } #endif apache-log4cxx-1.3.1/src/main/cpp/rootlogger.cpp0000644000175100001770000000302414721727031021057 0ustar runnerdocker/* * 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. */ #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; RootLogger::RootLogger(const LevelPtr& level1) : Logger(LOG4CXX_STR("root")) { setLevel(level1); } #if LOG4CXX_ABI_VERSION <= 15 RootLogger::RootLogger(Pool&, const LevelPtr level) : RootLogger(level) { } #endif const LevelPtr& RootLogger::getEffectiveLevel() const { return getLevel(); } void RootLogger::setLevel(const LevelPtr level1) { if (level1 == 0) { LogLog::error(LOG4CXX_STR("You have tried to set a null level to root.")); } else { Logger::setLevel(level1); } } apache-log4cxx-1.3.1/src/main/cpp/consoleappender.cpp0000644000175100001770000000757714721727031022076 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; struct ConsoleAppender::ConsoleAppenderPriv : public WriterAppender::WriterAppenderPriv { ConsoleAppenderPriv(LogString target) : WriterAppenderPriv(), target(target) {} LogString target; }; #define _priv static_cast(m_priv.get()) IMPLEMENT_LOG4CXX_OBJECT(ConsoleAppender) ConsoleAppender::ConsoleAppender() : WriterAppender (std::make_unique(getSystemOut())) { } ConsoleAppender::ConsoleAppender(const LayoutPtr& layout) : WriterAppender (std::make_unique(getSystemOut())) { setLayout(layout); Pool p; setWriter(std::make_shared()); WriterAppender::activateOptions(p); } ConsoleAppender::ConsoleAppender(const LayoutPtr& layout, const LogString& target) : WriterAppender (std::make_unique(target)) { setLayout(layout); setTarget(target); Pool p; ConsoleAppender::activateOptions(p); } ConsoleAppender::~ConsoleAppender() { finalize(); } const LogString& ConsoleAppender::getSystemOut() { static const WideLife name(LOG4CXX_STR("System.out")); return name; } const LogString& ConsoleAppender::getSystemErr() { static const WideLife name(LOG4CXX_STR("System.err")); return name; } void ConsoleAppender::setTarget(const LogString& value) { LogString v = StringHelper::trim(value); if (StringHelper::equalsIgnoreCase(v, LOG4CXX_STR("SYSTEM.OUT"), LOG4CXX_STR("system.out"))) { _priv->target = getSystemOut(); } else if (StringHelper::equalsIgnoreCase(v, LOG4CXX_STR("SYSTEM.ERR"), LOG4CXX_STR("system.err"))) { _priv->target = getSystemErr(); } else { targetWarn(value); } } LogString ConsoleAppender::getTarget() const { return _priv->target; } void ConsoleAppender::targetWarn(const LogString& val) { LogLog::warn(((LogString) LOG4CXX_STR("[")) + val + LOG4CXX_STR("] should be system.out or system.err.")); LogLog::warn(LOG4CXX_STR("Using previously set target, System.out by default.")); } void ConsoleAppender::activateOptions(Pool& p) { if (StringHelper::equalsIgnoreCase(_priv->target, LOG4CXX_STR("SYSTEM.OUT"), LOG4CXX_STR("system.out"))) { WriterPtr writer1 = std::make_shared(); setWriter(writer1); } else if (StringHelper::equalsIgnoreCase(_priv->target, LOG4CXX_STR("SYSTEM.ERR"), LOG4CXX_STR("system.err"))) { WriterPtr writer1 = std::make_shared(); setWriter(writer1); } WriterAppender::activateOptions(p); } void ConsoleAppender::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("TARGET"), LOG4CXX_STR("target"))) { setTarget(value); } else { WriterAppender::setOption(option, value); } } apache-log4cxx-1.3.1/src/main/cpp/bytearrayoutputstream.cpp0000644000175100001770000000330614721727031023376 0ustar runnerdocker/* * 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. */ #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; struct ByteArrayOutputStream::ByteArrayOutputStreamPriv { ByteList array; }; IMPLEMENT_LOG4CXX_OBJECT(ByteArrayOutputStream) ByteArrayOutputStream::ByteArrayOutputStream() { } ByteArrayOutputStream::~ByteArrayOutputStream() { } void ByteArrayOutputStream::close(Pool& /* p */) { } void ByteArrayOutputStream::flush(Pool& /* p */) { } void ByteArrayOutputStream::write(ByteBuffer& buf, Pool& /* p */ ) { size_t sz = m_priv->array.size(); m_priv->array.resize(sz + buf.remaining()); memcpy(&m_priv->array[sz], buf.current(), buf.remaining()); buf.position(buf.limit()); } std::vector ByteArrayOutputStream::toByteArray() const { return m_priv->array; } apache-log4cxx-1.3.1/src/main/cpp/sizebasedtriggeringpolicy.cpp0000644000175100001770000000360114721727031024150 0ustar runnerdocker/* * 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. */ #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::rolling; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(SizeBasedTriggeringPolicy) SizeBasedTriggeringPolicy::SizeBasedTriggeringPolicy() : maxFileSize(10 * 1024 * 1024) { } bool SizeBasedTriggeringPolicy::isTriggeringEvent(Appender* /* appender */, const LOG4CXX_NS::spi::LoggingEventPtr& /* event */, const LogString& /* file */, size_t fileLength) { return (fileLength >= maxFileSize); } size_t SizeBasedTriggeringPolicy::getMaxFileSize() { return maxFileSize; } void SizeBasedTriggeringPolicy::setMaxFileSize(size_t l) { maxFileSize = l; } void SizeBasedTriggeringPolicy::activateOptions(Pool& /* p */) { } void SizeBasedTriggeringPolicy::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("MAXFILESIZE"), LOG4CXX_STR("maxfilesize"))) { maxFileSize = OptionConverter::toFileSize(value, 10 * 1024 * 1024); } } apache-log4cxx-1.3.1/src/main/cpp/jsonlayout.cpp0000644000175100001770000002623414721727031021113 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; using namespace LOG4CXX_NS::spi; IMPLEMENT_LOG4CXX_OBJECT(JSONLayout) struct JSONLayout::JSONLayoutPrivate { JSONLayoutPrivate() : locationInfo(false), prettyPrint(false), dateFormat(), ppIndentL1(LOG4CXX_STR(" ")), ppIndentL2(LOG4CXX_STR(" ")), expectedPatternLength(100), threadInfo(false) {} // Print no location info by default bool locationInfo; //= false bool prettyPrint; //= false helpers::ISO8601DateFormat dateFormat; LogString ppIndentL1; LogString ppIndentL2; // Expected length of a formatted event excluding the message text size_t expectedPatternLength; // Thread info is not included by default bool threadInfo; //= false }; JSONLayout::JSONLayout() : m_priv(std::make_unique()) { } JSONLayout::~JSONLayout(){} void JSONLayout::setLocationInfo(bool locationInfoFlag) { m_priv->locationInfo = locationInfoFlag; } bool JSONLayout::getLocationInfo() const { return m_priv->locationInfo; } void JSONLayout::setPrettyPrint(bool prettyPrintFlag) { m_priv->prettyPrint = prettyPrintFlag; } bool JSONLayout::getPrettyPrint() const { return m_priv->prettyPrint; } void JSONLayout::setThreadInfo(bool newValue) { m_priv->threadInfo = newValue; } bool JSONLayout::getThreadInfo() const { return m_priv->threadInfo; } LogString JSONLayout::getContentType() const { return LOG4CXX_STR("application/json"); } void JSONLayout::activateOptions(helpers::Pool& /* p */) { m_priv->expectedPatternLength = getFormattedEventCharacterCount() * 2; } void JSONLayout::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("LOCATIONINFO"), LOG4CXX_STR("locationinfo"))) { setLocationInfo(OptionConverter::toBoolean(value, false)); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("THREADINFO"), LOG4CXX_STR("threadinfo"))) { setThreadInfo(OptionConverter::toBoolean(value, false)); } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("PRETTYPRINT"), LOG4CXX_STR("prettyprint"))) { setPrettyPrint(OptionConverter::toBoolean(value, false)); } } void JSONLayout::format(LogString& output, const spi::LoggingEventPtr& event, Pool& p) const { output.reserve(m_priv->expectedPatternLength + event->getMessage().size()); output.append(LOG4CXX_STR("{")); output.append(m_priv->prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); if (m_priv->prettyPrint) { output.append(m_priv->ppIndentL1); } appendQuotedEscapedString(output, LOG4CXX_STR("timestamp")); output.append(LOG4CXX_STR(": ")); LogString timestamp; m_priv->dateFormat.format(timestamp, event->getTimeStamp(), p); appendQuotedEscapedString(output, timestamp); output.append(LOG4CXX_STR(",")); output.append(m_priv->prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); if (m_priv->threadInfo) { if (m_priv->prettyPrint) { output.append(m_priv->ppIndentL1); } appendQuotedEscapedString(output, LOG4CXX_STR("thread")); output.append(LOG4CXX_STR(": ")); appendQuotedEscapedString(output, event->getThreadName()); output.append(LOG4CXX_STR(",")); output.append(m_priv->prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); } if (m_priv->prettyPrint) { output.append(m_priv->ppIndentL1); } appendQuotedEscapedString(output, LOG4CXX_STR("level")); output.append(LOG4CXX_STR(": ")); LogString level; event->getLevel()->toString(level); appendQuotedEscapedString(output, level); output.append(LOG4CXX_STR(",")); output.append(m_priv->prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); if (m_priv->prettyPrint) { output.append(m_priv->ppIndentL1); } appendQuotedEscapedString(output, LOG4CXX_STR("logger")); output.append(LOG4CXX_STR(": ")); appendQuotedEscapedString(output, event->getLoggerName()); output.append(LOG4CXX_STR(",")); output.append(m_priv->prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); if (m_priv->prettyPrint) { output.append(m_priv->ppIndentL1); } appendQuotedEscapedString(output, LOG4CXX_STR("message")); output.append(LOG4CXX_STR(": ")); appendQuotedEscapedString(output, event->getMessage()); appendSerializedMDC(output, event); appendSerializedNDC(output, event); if (m_priv->locationInfo) { output.append(LOG4CXX_STR(",")); output.append(m_priv->prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); appendSerializedLocationInfo(output, event, p); } output.append(m_priv->prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); output.append(LOG4CXX_STR("}")); output.append(LOG4CXX_EOL); } void JSONLayout::appendQuotedEscapedString(LogString& buf, const LogString& input) const { appendItem(input, buf); } void JSONLayout::appendItem(const LogString& input, LogString& buf) { /* add leading quote */ buf.push_back(0x22); logchar specialChars[] = { 0x08, /* \b backspace */ 0x09, /* \t tab */ 0x0a, /* \n newline */ 0x0c, /* \f form feed */ 0x0d, /* \r carriage return */ 0x22, /* \" double quote */ 0x5c, /* \\ backslash */ 0x00 /* terminating NULL for C-strings */ }; size_t start = 0; size_t found = input.find_first_of(specialChars, start); while (found != LogString::npos) { if (found > start) { buf.append(input, start, found - start); } switch (input[found]) { case 0x08: /* \b backspace */ buf.push_back(0x5c); buf.push_back('b'); break; case 0x09: /* \t tab */ buf.push_back(0x5c); buf.push_back('t'); break; case 0x0a: /* \n newline */ buf.push_back(0x5c); buf.push_back('n'); break; case 0x0c: /* \f form feed */ buf.push_back(0x5c); buf.push_back('f'); break; case 0x0d: /* \r carriage return */ buf.push_back(0x5c); buf.push_back('r'); break; case 0x22: /* \" double quote */ buf.push_back(0x5c); buf.push_back(0x22); break; case 0x5c: /* \\ backslash */ buf.push_back(0x5c); buf.push_back(0x5c); break; default: buf.push_back(input[found]); break; } start = found + 1; if (found < input.size()) { found = input.find_first_of(specialChars, start); } else { found = LogString::npos; } } if (start < input.size()) { buf.append(input, start, input.size() - start); } /* add trailing quote */ buf.push_back(0x22); } void JSONLayout::appendSerializedMDC(LogString& buf, const LoggingEventPtr& event) const { LoggingEvent::KeySet keys = event->getMDCKeySet(); if (keys.empty()) { return; } buf.append(LOG4CXX_STR(",")); buf.append(m_priv->prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); if (m_priv->prettyPrint) { buf.append(m_priv->ppIndentL1); } appendQuotedEscapedString(buf, LOG4CXX_STR("context_map")); buf.append(LOG4CXX_STR(": {")); buf.append(m_priv->prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); for (LoggingEvent::KeySet::iterator it = keys.begin(); it != keys.end(); ++it) { if (m_priv->prettyPrint) { buf.append(m_priv->ppIndentL2); } appendQuotedEscapedString(buf, *it); buf.append(LOG4CXX_STR(": ")); LogString value; event->getMDC(*it, value); appendQuotedEscapedString(buf, value); /* if this isn't the last k:v pair, we need a comma */ if (it + 1 != keys.end()) { buf.append(LOG4CXX_STR(",")); buf.append(m_priv->prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); } else { buf.append(m_priv->prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); } } if (m_priv->prettyPrint) { buf.append(m_priv->ppIndentL1); } buf.append(LOG4CXX_STR("}")); } void JSONLayout::appendSerializedNDC(LogString& buf, const LoggingEventPtr& event) const { LogString ndcVal; if (!event->getNDC(ndcVal)) { return; } buf.append(LOG4CXX_STR(",")); buf.append(m_priv->prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); if (m_priv->prettyPrint) { buf.append(m_priv->ppIndentL1); } appendQuotedEscapedString(buf, LOG4CXX_STR("context_stack")); buf.append(LOG4CXX_STR(": [")); buf.append(m_priv->prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); if (m_priv->prettyPrint) { buf.append(m_priv->ppIndentL2); } appendQuotedEscapedString(buf, ndcVal); buf.append(m_priv->prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); if (m_priv->prettyPrint) { buf.append(m_priv->ppIndentL1); } buf.append(LOG4CXX_STR("]")); } void JSONLayout::appendSerializedLocationInfo(LogString& buf, const LoggingEventPtr& event, Pool& p) const { if (m_priv->prettyPrint) { buf.append(m_priv->ppIndentL1); } appendQuotedEscapedString(buf, LOG4CXX_STR("location_info")); buf.append(LOG4CXX_STR(": {")); buf.append(m_priv->prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); const LocationInfo& locInfo = event->getLocationInformation(); if (m_priv->prettyPrint) { buf.append(m_priv->ppIndentL2); } appendQuotedEscapedString(buf, LOG4CXX_STR("file")); buf.append(LOG4CXX_STR(": ")); LOG4CXX_DECODE_CHAR(fileName, locInfo.getFileName()); appendQuotedEscapedString(buf, fileName); buf.append(LOG4CXX_STR(",")); buf.append(m_priv->prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); if (m_priv->prettyPrint) { buf.append(m_priv->ppIndentL2); } appendQuotedEscapedString(buf, LOG4CXX_STR("line")); buf.append(LOG4CXX_STR(": ")); LogString lineNumber; StringHelper::toString(locInfo.getLineNumber(), p, lineNumber); appendQuotedEscapedString(buf, lineNumber); buf.append(LOG4CXX_STR(",")); buf.append(m_priv->prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); if (m_priv->prettyPrint) { buf.append(m_priv->ppIndentL2); } appendQuotedEscapedString(buf, LOG4CXX_STR("class")); buf.append(LOG4CXX_STR(": ")); LOG4CXX_DECODE_CHAR(className, locInfo.getClassName()); appendQuotedEscapedString(buf, className); buf.append(LOG4CXX_STR(",")); buf.append(m_priv->prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); if (m_priv->prettyPrint) { buf.append(m_priv->ppIndentL2); } appendQuotedEscapedString(buf, LOG4CXX_STR("method")); buf.append(LOG4CXX_STR(": ")); LOG4CXX_DECODE_CHAR(methodName, locInfo.getMethodName()); appendQuotedEscapedString(buf, methodName); buf.append(m_priv->prettyPrint ? LOG4CXX_EOL : LOG4CXX_STR(" ")); if (m_priv->prettyPrint) { buf.append(m_priv->ppIndentL1); } buf.append(LOG4CXX_STR("}")); } apache-log4cxx-1.3.1/src/main/cpp/date.cpp0000644000175100001770000000352314721727031017615 0ustar runnerdocker/* * 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. */ #include #include #include #define LOG4CXX_USEC_PER_SEC 1000000LL #ifndef INT64_C #define INT64_C(x) x ## LL #endif using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(Date) namespace { Date::GetCurrentTimeFn getCurrentTimeFn = 0; } Date::Date() : time(currentTime()) { } Date::Date(log4cxx_time_t t) : time(t) { } Date::~Date() { } log4cxx_time_t Date::getMicrosecondsPerDay() { return 86400000000ull; } log4cxx_time_t Date::getMicrosecondsPerSecond() { return LOG4CXX_USEC_PER_SEC; } log4cxx_time_t Date::getNextSecond() const { return ((time / LOG4CXX_USEC_PER_SEC) + 1) * LOG4CXX_USEC_PER_SEC; } void Date::setGetCurrentTimeFunction(GetCurrentTimeFn fn){ getCurrentTimeFn = fn; } log4cxx_time_t Date::currentTime(){ return getCurrentTimeFn ? getCurrentTimeFn() : getCurrentTimeStd(); } log4cxx_time_t Date::getCurrentTimeStd(){ return std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); } apache-log4cxx-1.3.1/src/main/cpp/cacheddateformat.cpp0000644000175100001770000002656014721727031022164 0ustar runnerdocker/* * 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. */ #define __STDC_CONSTANT_MACROS #define NOMINMAX /* tell wnidows not to define min/max macros */ #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; using namespace LOG4CXX_NS::pattern; struct CachedDateFormat::CachedDateFormatPriv { CachedDateFormatPriv(DateFormatPtr dateFormat, int expiration1) : formatter(dateFormat), millisecondStart(0), slotBegin(std::numeric_limits::min()), cache(50, 0x20), expiration(expiration1), previousTime(std::numeric_limits::min()) {} /** * Wrapped formatter. */ LOG4CXX_NS::helpers::DateFormatPtr formatter; /** * Index of initial digit of millisecond pattern or * UNRECOGNIZED_MILLISECONDS or NO_MILLISECONDS. */ mutable int millisecondStart; /** * Integral second preceding the previous convered Date. */ mutable log4cxx_time_t slotBegin; /** * Cache of previous conversion. */ mutable LogString cache; /** * Maximum validity period for the cache. * Typically 1, use cache for duplicate requests only, or * 1000000, use cache for requests within the same integral second. */ const int expiration; /** * Date requested in previous conversion. */ mutable log4cxx_time_t previousTime; }; /** * Supported digit set. If the wrapped DateFormat uses * a different unit set, the millisecond pattern * will not be recognized and duplicate requests * will use the cache. */ const logchar CachedDateFormat::digits[] = { 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0 }; /** * First magic number (in microseconds) used to detect * the millisecond position. */ const int CachedDateFormat::magic1 = 654000; /** * Expected representation of first magic number in milliseconds. */ const logchar CachedDateFormat::magicString1[] = { 0x36, 0x35, 0x34, 0 }; /** * Second magic number (in microseconds) used to detect * the millisecond position. */ const int CachedDateFormat::magic2 = 987000; /** * Expected representation of second magic number in milliseconds. */ const logchar CachedDateFormat::magicString2[] = { 0x39, 0x38, 0x37, 0}; /** * Expected representation of 0 milliseconds. */ const logchar CachedDateFormat::zeroString[] = { 0x30, 0x30, 0x30, 0 }; /** * Creates a new CachedDateFormat object. * @param dateFormat Date format, may not be null. * @param expiration maximum cached range in milliseconds. * If the dateFormat is known to be incompatible with the * caching algorithm, use a value of 0 to totally disable * caching or 1 to only use cache for duplicate requests. */ CachedDateFormat::CachedDateFormat(const DateFormatPtr& dateFormat, int expiration1) : m_priv(std::make_unique(dateFormat, expiration1)) { if (dateFormat == NULL) { throw IllegalArgumentException(LOG4CXX_STR("dateFormat cannot be null")); } if (expiration1 < 0) { throw IllegalArgumentException(LOG4CXX_STR("expiration must be non-negative")); } } CachedDateFormat::~CachedDateFormat() {} /** * Finds start of millisecond field in formatted time. * @param time long time, must be integral number of seconds * @param formatted String corresponding formatted string * @param formatter DateFormat date format * @return int position in string of first digit of milliseconds, * -1 indicates no millisecond field, -2 indicates unrecognized * field (likely RelativeTimeDateFormat) */ int CachedDateFormat::findMillisecondStart( log4cxx_time_t time, const LogString& formatted, const DateFormatPtr& formatter, Pool& pool) { log4cxx_time_t slotBegin = (time / 1000000) * 1000000; if (slotBegin > time) { slotBegin -= 1000000; } int millis = (int) (time - slotBegin) / 1000; // the magic numbers are in microseconds int magic = magic1; LogString magicString(magicString1); if (millis == magic1 / 1000) { magic = magic2; magicString = magicString2; } LogString plusMagic; formatter->format(plusMagic, slotBegin + magic, pool); /** * If the string lengths differ then * we can't use the cache except for duplicate requests. */ if (plusMagic.length() != formatted.length()) { return UNRECOGNIZED_MILLISECONDS; } else { // find first difference between values for (LogString::size_type i = 0; i < formatted.length(); i++) { if (formatted[i] != plusMagic[i]) { // // determine the expected digits for the base time const logchar abc[] = { 0x41, 0x42, 0x43, 0 }; LogString formattedMillis(abc); millisecondFormat(millis, formattedMillis, 0); LogString plusZero; formatter->format(plusZero, slotBegin, pool); // Test if the next 1..3 characters match the magic string, main problem is that magic // available millis in formatted can overlap. Therefore the current i is not always the // index of the first millis char, but may be already within the millis. Besides that // the millis can occur everywhere in formatted. See LOGCXX-420 and following. size_t magicLength = magicString.length(); size_t overlapping = magicString.find(plusMagic[i]); int possibleRetVal = int(i - overlapping); if (plusZero.length() == formatted.length() && regionMatches(magicString, 0, plusMagic, possibleRetVal, magicLength) && regionMatches(formattedMillis, 0, formatted, possibleRetVal, magicLength) && regionMatches(zeroString, 0, plusZero, possibleRetVal, magicLength) // The following will and should fail for patterns with more than one SSS because // we only seem to be able to change one SSS in e.g. format and need to reformat the // whole string in other cases. && (formatted.length() == possibleRetVal + magicLength || plusZero.compare(possibleRetVal + magicLength, LogString::npos, plusMagic, possibleRetVal + magicLength, LogString::npos) == 0)) { return possibleRetVal; } else { return UNRECOGNIZED_MILLISECONDS; } } } } return NO_MILLISECONDS; } /** * Formats a millisecond count into a date/time string. * * @param now Number of milliseconds after midnight 1 Jan 1970 GMT. * @param sbuf the string buffer to write to */ void CachedDateFormat::format(LogString& buf, log4cxx_time_t now, Pool& p) const { // // If the current requested time is identical to the previously // requested time, then append the cache contents. // if (now == m_priv->previousTime) { buf.append(m_priv->cache); return; } // // If millisecond pattern was not unrecognized // (that is if it was found or milliseconds did not appear) // if (m_priv->millisecondStart != UNRECOGNIZED_MILLISECONDS) { // Check if the cache is still valid. // If the requested time is within the same integral second // as the last request and a shorter expiration was not requested. if (now < m_priv->slotBegin + m_priv->expiration && now >= m_priv->slotBegin && now < m_priv->slotBegin + 1000000L) { // // if there was a millisecond field then update it // if (m_priv->millisecondStart >= 0) { millisecondFormat((int) ((now - m_priv->slotBegin) / 1000), m_priv->cache, m_priv->millisecondStart); } // // update the previously requested time // (the slot begin should be unchanged) m_priv->previousTime = now; buf.append(m_priv->cache); return; } } // // could not use previous value. // Call underlying formatter to format date. m_priv->cache.erase(m_priv->cache.begin(), m_priv->cache.end()); m_priv->formatter->format(m_priv->cache, now, p); buf.append(m_priv->cache); m_priv->previousTime = now; m_priv->slotBegin = (m_priv->previousTime / 1000000) * 1000000; if (m_priv->slotBegin > m_priv->previousTime) { m_priv->slotBegin -= 1000000; } // // if the milliseconds field was previous found // then reevaluate in case it moved. // if (m_priv->millisecondStart >= 0) { m_priv->millisecondStart = findMillisecondStart(now, m_priv->cache, m_priv->formatter, p); } } /** * Formats a count of milliseconds (0-999) into a numeric representation. * @param millis Millisecond count between 0 and 999. * @buf String buffer, may not be null. * @offset Starting position in buffer, the length of the * buffer must be at least offset + 3. */ void CachedDateFormat::millisecondFormat(int millis, LogString& buf, int offset) { buf[offset] = digits[millis / 100]; buf[offset + 1] = digits[(millis / 10) % 10]; buf[offset + 2] = digits[millis % 10]; } /** * Set timezone. * * @remarks Setting the timezone using getCalendar().setTimeZone() * will likely cause caching to misbehave. * @param timeZone TimeZone new timezone */ void CachedDateFormat::setTimeZone(const TimeZonePtr& timeZone) { m_priv->formatter->setTimeZone(timeZone); m_priv->previousTime = std::numeric_limits::min(); m_priv->slotBegin = std::numeric_limits::min(); } void CachedDateFormat::numberFormat(LogString& s, int n, Pool& p) const { m_priv->formatter->numberFormat(s, n, p); } /** * Gets maximum cache validity for the specified SimpleDateTime * conversion pattern. * @param pattern conversion pattern, may not be null. * @returns Duration in microseconds from an integral second * that the cache will return consistent results. */ int CachedDateFormat::getMaximumCacheValidity(const LogString& pattern) { // // If there are more "S" in the pattern than just one "SSS" then // (for example, "HH:mm:ss,SSS SSS"), then set the expiration to // one millisecond which should only perform duplicate request caching. // const logchar S = 0x53; const logchar SSS[] = { 0x53, 0x53, 0x53, 0 }; size_t firstS = pattern.find(S); size_t len = pattern.length(); // // if there are no S's or // three that start with the first S and no fourth S in the string // if (firstS == LogString::npos || (len >= firstS + 3 && pattern.compare(firstS, 3, SSS) == 0 && (len == firstS + 3 || pattern.find(S, firstS + 3) == LogString::npos))) { return 1000000; } return 1000; } /** * Tests if two string regions are equal. * @param target target string. * @param toffset character position in target to start comparison. * @param other other string. * @param ooffset character position in other to start comparison. * @param len length of region. * @return true if regions are equal. */ bool CachedDateFormat::regionMatches( const LogString& target, size_t toffset, const LogString& other, size_t ooffset, size_t len) { return target.compare(toffset, len, other, ooffset, len) == 0; } apache-log4cxx-1.3.1/src/main/cpp/layout.cpp0000644000175100001770000000306114721727031020212 0ustar runnerdocker/* * 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. */ #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(Layout) Layout::~Layout() {} LogString Layout::getContentType() const { return LOG4CXX_STR("text/plain"); } void Layout::appendHeader(LogString&, LOG4CXX_NS::helpers::Pool&) {} void Layout::appendFooter(LogString&, LOG4CXX_NS::helpers::Pool&) {} /** * The expected length of a formatted event excluding the message text */ size_t Layout::getFormattedEventCharacterCount() const { auto exampleEvent = std::make_shared ( LOG4CXX_STR("example.logger") , Level::getDebug() , LOG4CXX_LOCATION , LogString() ); LogString text; Pool pool; format(text, exampleEvent, pool); return text.size(); } apache-log4cxx-1.3.1/src/main/cpp/linelocationpatternconverter.cpp0000644000175100001770000000340614721727031024706 0ustar runnerdocker/* * 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. */ #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::pattern; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(LineLocationPatternConverter) LineLocationPatternConverter::LineLocationPatternConverter() : LoggingEventPatternConverter(LOG4CXX_STR("Line"), LOG4CXX_STR("line")) { } PatternConverterPtr LineLocationPatternConverter::newInstance( const std::vector& /* options */) { static WideLife instance = std::make_shared(); return instance; } void LineLocationPatternConverter::format( const LoggingEventPtr& event, LogString& toAppendTo, Pool& p) const { StringHelper::toString( event->getLocationInformation().getLineNumber(), p, toAppendTo); } apache-log4cxx-1.3.1/src/main/cpp/threadpatternconverter.cpp0000644000175100001770000000320114721727031023466 0ustar runnerdocker/* * 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. */ #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::pattern; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::helpers; IMPLEMENT_LOG4CXX_OBJECT(ThreadPatternConverter) ThreadPatternConverter::ThreadPatternConverter() : LoggingEventPatternConverter(LOG4CXX_STR("Thread"), LOG4CXX_STR("Thread")) { } PatternConverterPtr ThreadPatternConverter::newInstance( const std::vector& /* options */) { static WideLife def = std::make_shared(); return def; } void ThreadPatternConverter::format( const LoggingEventPtr& event, LogString& toAppendTo, Pool& /* p */) const { toAppendTo.append(event->getThreadName()); } apache-log4cxx-1.3.1/src/main/cpp/threadutility.cpp0000644000175100001770000001236414721727031021576 0ustar runnerdocker/* * 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. */ #include "log4cxx/helpers/threadutility.h" #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include "log4cxx/private/log4cxx_private.h" #include "log4cxx/helpers/loglog.h" #include "log4cxx/helpers/transcoder.h" #include #include #ifdef _WIN32 #include #include #endif namespace LOG4CXX_NS { namespace helpers { struct ThreadUtility::priv_data { priv_data() { start_pre = nullptr; started = nullptr; start_post = nullptr; } ThreadStartPre start_pre; ThreadStarted started; ThreadStartPost start_post; }; #if LOG4CXX_HAS_PTHREAD_SIGMASK static thread_local sigset_t old_mask; static thread_local bool sigmask_valid; #endif ThreadUtility::ThreadUtility() : m_priv( new priv_data() ) { // Block signals by default. configureFuncs( std::bind( &ThreadUtility::preThreadBlockSignals, this ), nullptr, std::bind( &ThreadUtility::postThreadUnblockSignals, this ) ); } ThreadUtility::~ThreadUtility() {} ThreadUtility* ThreadUtility::instance() { static WideLife instance; return &instance.value(); } void ThreadUtility::configure( ThreadConfigurationType type ) { auto utility = instance(); if ( type == ThreadConfigurationType::NoConfiguration ) { utility->configureFuncs( nullptr, nullptr, nullptr ); } else if ( type == ThreadConfigurationType::NameThreadOnly ) { utility->configureFuncs( nullptr, std::bind( &ThreadUtility::threadStartedNameThread, utility, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3 ), nullptr ); } else if ( type == ThreadConfigurationType::BlockSignalsOnly ) { utility->configureFuncs( std::bind( &ThreadUtility::preThreadBlockSignals, utility ), nullptr, std::bind( &ThreadUtility::postThreadUnblockSignals, utility ) ); } else if ( type == ThreadConfigurationType::BlockSignalsAndNameThread ) { utility->configureFuncs( std::bind( &ThreadUtility::preThreadBlockSignals, utility ), std::bind( &ThreadUtility::threadStartedNameThread, utility, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3 ), std::bind( &ThreadUtility::postThreadUnblockSignals, utility ) ); } } void ThreadUtility::configureFuncs( ThreadStartPre pre_start, ThreadStarted started, ThreadStartPost post_start ) { m_priv->start_pre = pre_start; m_priv->started = started; m_priv->start_post = post_start; } void ThreadUtility::preThreadBlockSignals() { #if LOG4CXX_HAS_PTHREAD_SIGMASK sigset_t set; sigfillset(&set); if ( pthread_sigmask(SIG_SETMASK, &set, &old_mask) < 0 ) { LOGLOG_ERROR( LOG4CXX_STR("Unable to set thread sigmask") ); sigmask_valid = false; } else { sigmask_valid = true; } #endif /* LOG4CXX_HAS_PTHREAD_SIGMASK */ } void ThreadUtility::threadStartedNameThread(LogString threadName, std::thread::id /*threadId*/, std::thread::native_handle_type nativeHandle) { #if LOG4CXX_HAS_PTHREAD_SETNAME && !(defined(_WIN32) && defined(_LIBCPP_VERSION)) LOG4CXX_ENCODE_CHAR(sthreadName, threadName); if (pthread_setname_np(static_cast(nativeHandle), sthreadName.c_str()) < 0) { LOGLOG_ERROR(LOG4CXX_STR("unable to set thread name")); } #elif defined(_WIN32) typedef HRESULT (WINAPI *TSetThreadDescription)(HANDLE, PCWSTR); static struct initialiser { HMODULE hKernelBase; TSetThreadDescription SetThreadDescription; initialiser() : hKernelBase(GetModuleHandleA("KernelBase.dll")) , SetThreadDescription(nullptr) { if (hKernelBase) SetThreadDescription = reinterpret_cast(GetProcAddress(hKernelBase, "SetThreadDescription")); } } win32Func; if (win32Func.SetThreadDescription) { LOG4CXX_ENCODE_WCHAR(wthreadName, threadName); if(FAILED(win32Func.SetThreadDescription(static_cast(nativeHandle), wthreadName.c_str()))) LOGLOG_ERROR( LOG4CXX_STR("unable to set thread name") ); } #endif } void ThreadUtility::postThreadUnblockSignals() { #if LOG4CXX_HAS_PTHREAD_SIGMASK // Only restore the signal mask if we were able to set it in the first place. if ( sigmask_valid ) { if ( pthread_sigmask(SIG_SETMASK, &old_mask, nullptr) < 0 ) { LOGLOG_ERROR( LOG4CXX_STR("Unable to set thread sigmask") ); } } #endif /* LOG4CXX_HAS_PTHREAD_SIGMASK */ } ThreadStartPre ThreadUtility::preStartFunction() { return m_priv->start_pre; } ThreadStarted ThreadUtility::threadStartedFunction() { return m_priv->started; } ThreadStartPost ThreadUtility::postStartFunction() { return m_priv->start_post; } } //namespace helpers } //namespace log4cxx apache-log4cxx-1.3.1/src/main/cpp/xmllayout.cpp0000644000175100001770000001352314721727031020737 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::xml; struct XMLLayout::XMLLayoutPrivate { XMLLayoutPrivate() : locationInfo(false) , properties(false) , expectedPatternLength(100) {} // Print no location info by default bool locationInfo; //= false bool properties; // = false // Expected length of a formatted event excluding the message text size_t expectedPatternLength; }; IMPLEMENT_LOG4CXX_OBJECT(XMLLayout) XMLLayout::XMLLayout() : m_priv(std::make_unique()) { m_priv->expectedPatternLength = getFormattedEventCharacterCount() * 2; } XMLLayout::~XMLLayout() {} void XMLLayout::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("LOCATIONINFO"), LOG4CXX_STR("locationinfo"))) { setLocationInfo(OptionConverter::toBoolean(value, false)); m_priv->expectedPatternLength = getFormattedEventCharacterCount() * 2; } if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("PROPERTIES"), LOG4CXX_STR("properties"))) { setProperties(OptionConverter::toBoolean(value, false)); m_priv->expectedPatternLength = getFormattedEventCharacterCount() * 2; } } void XMLLayout::format(LogString& output, const spi::LoggingEventPtr& event, Pool& p) const { output.reserve(m_priv->expectedPatternLength + event->getMessage().size()); output.append(LOG4CXX_STR("getLoggerName()); output.append(LOG4CXX_STR("\" timestamp=\"")); StringHelper::toString(event->getTimeStamp() / 1000L, p, output); output.append(LOG4CXX_STR("\" level=\"")); Transform::appendEscapingTags(output, event->getLevel()->toString()); output.append(LOG4CXX_STR("\" thread=\"")); Transform::appendEscapingTags(output, event->getThreadName()); output.append(LOG4CXX_STR("\">")); output.append(LOG4CXX_EOL); output.append(LOG4CXX_STR("getRenderedMessage()); output.append(LOG4CXX_STR("]]>")); output.append(LOG4CXX_EOL); LogString ndc; if (event->getNDC(ndc)) { output.append(LOG4CXX_STR("")); output.append(LOG4CXX_EOL); } if (m_priv->locationInfo) { output.append(LOG4CXX_STR("getLocationInformation(); LOG4CXX_DECODE_CHAR(className, locInfo.getClassName()); Transform::appendEscapingTags(output, className); output.append(LOG4CXX_STR("\" method=\"")); LOG4CXX_DECODE_CHAR(method, locInfo.getMethodName()); Transform::appendEscapingTags(output, method); output.append(LOG4CXX_STR("\" file=\"")); LOG4CXX_DECODE_CHAR(fileName, locInfo.getFileName()); Transform::appendEscapingTags(output, fileName); output.append(LOG4CXX_STR("\" line=\"")); StringHelper::toString(locInfo.getLineNumber(), p, output); output.append(LOG4CXX_STR("\"/>")); output.append(LOG4CXX_EOL); } if (m_priv->properties) { LoggingEvent::KeySet propertySet(event->getPropertyKeySet()); LoggingEvent::KeySet keySet(event->getMDCKeySet()); if (!(keySet.empty() && propertySet.empty())) { output.append(LOG4CXX_STR("")); output.append(LOG4CXX_EOL); for (auto key : keySet) { LogString value; if (event->getMDC(key, value)) { output.append(LOG4CXX_STR("")); output.append(LOG4CXX_EOL); } } for (auto key : propertySet) { LogString value; if (event->getProperty(key, value)) { output.append(LOG4CXX_STR("")); output.append(LOG4CXX_EOL); } } output.append(LOG4CXX_STR("")); output.append(LOG4CXX_EOL); } } output.append(LOG4CXX_STR("")); output.append(LOG4CXX_EOL); output.append(LOG4CXX_EOL); } void XMLLayout::setLocationInfo(bool locationInfo1) { m_priv->locationInfo = locationInfo1; } bool XMLLayout::getLocationInfo() const { return m_priv->locationInfo; } void XMLLayout::setProperties(bool flag) { m_priv->properties = flag; } bool XMLLayout::getProperties() { return m_priv->properties; } apache-log4cxx-1.3.1/src/main/cpp/fallbackerrorhandler.cpp0000644000175100001770000001044114721727031023044 0ustar runnerdocker/* * 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. */ #include #include #include #include #include #include #include #include #include using namespace LOG4CXX_NS; using namespace LOG4CXX_NS::helpers; using namespace LOG4CXX_NS::spi; using namespace LOG4CXX_NS::varia; IMPLEMENT_LOG4CXX_OBJECT(FallbackErrorHandler) struct FallbackErrorHandler::FallbackErrorHandlerPrivate { AppenderWeakPtr backup; AppenderWeakPtr primary; std::vector loggers; bool errorReported = false; }; FallbackErrorHandler::FallbackErrorHandler() : m_priv(std::make_unique()) { } FallbackErrorHandler::~FallbackErrorHandler() {} void FallbackErrorHandler::setLogger(const LoggerPtr& logger) { if (LogLog::isDebugEnabled()) { LogLog::debug(((LogString) LOG4CXX_STR("FB: Adding logger [")) + logger->getName() + LOG4CXX_STR("].")); } m_priv->loggers.push_back(logger); } void FallbackErrorHandler::error(const LogString& message, const std::exception& e, int errorCode) const { error(message, e, errorCode, 0); } void FallbackErrorHandler::error(const LogString& message, const std::exception& e, int, const spi::LoggingEventPtr&) const { if (LogLog::isDebugEnabled()) { LogLog::debug(((LogString) LOG4CXX_STR("FB: The following error reported: ")) + message, e); LogLog::debug(LOG4CXX_STR("FB: INITIATING FALLBACK PROCEDURE.")); } AppenderPtr primaryLocked = m_priv->primary.lock(); AppenderPtr backupLocked = m_priv->backup.lock(); if ( !primaryLocked || !backupLocked ) { return; } for (LoggerPtr l : m_priv->loggers) { if (LogLog::isDebugEnabled()) { LogLog::debug(((LogString) LOG4CXX_STR("FB: Searching for [")) + primaryLocked->getName() + LOG4CXX_STR("] in logger [") + l->getName() + LOG4CXX_STR("].")); LogLog::debug(((LogString) LOG4CXX_STR("FB: Replacing [")) + primaryLocked->getName() + LOG4CXX_STR("] by [") + backupLocked->getName() + LOG4CXX_STR("] in logger [") + l->getName() + LOG4CXX_STR("].")); } l->removeAppender(primaryLocked); if (LogLog::isDebugEnabled()) { LogLog::debug(((LogString) LOG4CXX_STR("FB: Adding appender [")) + backupLocked->getName() + LOG4CXX_STR("] to logger ") + l->getName()); } l->addAppender(backupLocked); } m_priv->errorReported = true; } void FallbackErrorHandler::setAppender(const AppenderPtr& primary1) { if (LogLog::isDebugEnabled()) { LogLog::debug(((LogString) LOG4CXX_STR("FB: Setting primary appender to [")) + primary1->getName() + LOG4CXX_STR("].")); } m_priv->primary = primary1; } void FallbackErrorHandler::setBackupAppender(const AppenderPtr& backup1) { if (LogLog::isDebugEnabled()) { LogLog::debug(((LogString) LOG4CXX_STR("FB: Setting backup appender to [")) + backup1->getName() + LOG4CXX_STR("].")); } m_priv->backup = backup1; // Make sure that we keep a reference to the appender around, since otherwise // the appender would be lost if it has no loggers that use it. LoggerRepository* repository = LogManager::getRootLogger()->getLoggerRepository(); Hierarchy* hierarchy = dynamic_cast(repository); if(hierarchy){ hierarchy->addAppender(backup1); } } void FallbackErrorHandler::activateOptions(Pool&) { } void FallbackErrorHandler::setOption(const LogString&, const LogString&) { } bool FallbackErrorHandler::errorReported() const { return m_priv->errorReported; } apache-log4cxx-1.3.1/src/main/cpp/aprinitializer.cpp0000644000175100001770000001074514721727031021732 0ustar runnerdocker/* * 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. */ #include #if !defined(LOG4CXX) #define LOG4CXX 1 #endif #include #include #include #include #include #include #include #include #include #include using namespace LOG4CXX_NS::helpers; using namespace LOG4CXX_NS; bool APRInitializer::isDestructed = false; struct APRInitializer::APRInitializerPrivate{ APRInitializerPrivate() : p(0), startTime(0), tlsKey(0){ } apr_pool_t* p; std::mutex mutex; std::list watchdogs; log4cxx_time_t startTime; apr_threadkey_t* tlsKey; std::map objects; }; namespace { void tlsDestructImpl(void* ptr) { delete ((ThreadSpecificData*) ptr); } } #if LOG4CXX_ABI_VERSION <= 15 extern "C" void tlsDestruct(void* ptr) { return tlsDestructImpl(ptr); } #endif namespace { // The first object created and the last object destroyed struct apr_environment { apr_environment() { apr_initialize(); } ~apr_environment() { apr_terminate(); } }; } APRInitializer::APRInitializer() : m_priv(std::make_unique()) { apr_pool_create(&m_priv->p, NULL); m_priv->startTime = Date::currentTime(); #if APR_HAS_THREADS apr_status_t stat = apr_threadkey_private_create(&m_priv->tlsKey, tlsDestructImpl, m_priv->p); assert(stat == APR_SUCCESS); #endif } APRInitializer::~APRInitializer() { stopWatchDogs(); isDestructed = true; #if APR_HAS_THREADS std::lock_guard lock(m_priv->mutex); apr_threadkey_private_delete(m_priv->tlsKey); #endif } void APRInitializer::stopWatchDogs() { std::lock_guard lock(m_priv->mutex); while (!m_priv->watchdogs.empty()) { m_priv->watchdogs.back()->stop(); delete m_priv->watchdogs.back(); m_priv->watchdogs.pop_back(); } } void APRInitializer::unregisterAll() { getInstance().stopWatchDogs(); } APRInitializer& APRInitializer::getInstance() { static WideLife env; static WideLife init; return init; } #if LOG4CXX_ABI_VERSION <= 15 log4cxx_time_t APRInitializer::initialize() { return getInstance().m_priv->startTime; } #endif log4cxx_time_t APRInitializer::getStartTime() { return getInstance().m_priv->startTime; } apr_pool_t* APRInitializer::getRootPool() { return getInstance().m_priv->p; } apr_threadkey_t* APRInitializer::getTlsKey() { return getInstance().m_priv->tlsKey; } void APRInitializer::registerCleanup(FileWatchdog* watchdog) { APRInitializer& instance(getInstance()); std::lock_guard lock(instance.m_priv->mutex); instance.m_priv->watchdogs.push_back(watchdog); } void APRInitializer::unregisterCleanup(FileWatchdog* watchdog) { APRInitializer& instance(getInstance()); std::lock_guard lock(instance.m_priv->mutex); auto iter = std::find(instance.m_priv->watchdogs.begin(), instance.m_priv->watchdogs.end(), watchdog); if (iter != instance.m_priv->watchdogs.end()) instance.m_priv->watchdogs.erase(iter); } void APRInitializer::addObject(size_t key, const ObjectPtr& pObject) { std::lock_guard lock(m_priv->mutex); m_priv->objects[key] = pObject; } const ObjectPtr& APRInitializer::findOrAddObject(size_t key, std::function creator) { std::lock_guard lock(m_priv->mutex); if (m_priv->objects.empty()) { // Ensure the internal logger has a longer life than other Log4cxx static data LogLog::debug(LOG4CXX_STR("Started")); } auto pItem = m_priv->objects.find(key); if (m_priv->objects.end() == pItem) pItem = m_priv->objects.emplace(key, creator()).first; return pItem->second; } apache-log4cxx-1.3.1/src/fuzzers/0000755000175100001770000000000014721727031016173 5ustar runnerdockerapache-log4cxx-1.3.1/src/fuzzers/resources/0000755000175100001770000000000014721727031020205 5ustar runnerdockerapache-log4cxx-1.3.1/src/fuzzers/resources/PatternLayoutFuzzer.properties0000644000175100001770000000177414721727031026355 0ustar runnerdocker# # 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=ALL, encoding log4j.appender.encoding=org.apache.log4j.fuzzer.EncodingAppender log4j.appender.encoding.layout=org.apache.log4j.PatternLayout log4j.appender.encoding.layout.ConversionPattern=%5p [%t] (%f:%L) - %m%n apache-log4cxx-1.3.1/src/fuzzers/bash/0000755000175100001770000000000014721727031017110 5ustar runnerdockerapache-log4cxx-1.3.1/src/fuzzers/bash/oss-fuzz-build.sh0000755000175100001770000000323714721727031022351 0ustar runnerdocker#!/bin/bash -eu # # 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. # # Read command line arguments if [[ "$#" -ne 1 ]]; then cat >&2 < outputDir The output directory to dump runner scripts and their dependencies. EOF exit 1 fi outputDir=$(readlink -f "$1") # Ensure output directory exists mkdir -p "$outputDir" # Switch to the project directory (by referencing from the script directory) cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && cd ../../.. # Build the project mkdir -p build && cd $_ cmake \ -DBUILD_SHARED_LIBS=OFF \ -DBUILD_TESTING=OFF \ -DBUILD_EXAMPLES=OFF \ -DBUILD_FUZZERS=ON \ .. cmake --build . -j # Copy executables & resources find src/fuzzers/cpp -maxdepth 1 -executable -type f -exec cp -v {} "$outputDir/" \; cp -v ../src/fuzzers/resources/* "$outputDir/" apache-log4cxx-1.3.1/src/fuzzers/cpp/0000755000175100001770000000000014721727031016755 5ustar runnerdockerapache-log4cxx-1.3.1/src/fuzzers/cpp/CMakeLists.txt0000644000175100001770000000470714721727031021525 0ustar runnerdocker# # 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. # set(ALL_LOG4CXX_FUZZERS PatternLayoutFuzzer) # Get the most recent Git commit ID execute_process( COMMAND git rev-parse HEAD WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} OUTPUT_VARIABLE GIT_COMMIT_ID OUTPUT_STRIP_TRAILING_WHITESPACE) set(FUZZER_SANITIZE_FLAGS "-fsanitize=fuzzer,address,signed-integer-overflow") set(FUZZER_COMPILE_DEFINITIONS "-DCOMPILE_DEFINITIONS=${FUZZER_SANITIZE_FLAGS}" "-DGIT_COMMIT_ID=\"${GIT_COMMIT_ID}\"") if(WIN32) include(win32_target_environment_path) get_target_environment_path(ESCAPED_PATH) elseif(CMAKE_BUILD_TYPE) string(TOUPPER ${CMAKE_BUILD_TYPE} UPPER_BUILD_TYPE) if (UPPER_BUILD_TYPE STREQUAL "DEBUG") list(APPEND FUZZER_COMPILE_DEFINITIONS _DEBUG) endif() else() list(APPEND FUZZER_COMPILE_DEFINITIONS _DEBUG) endif() foreach(fuzzerName IN LISTS ALL_LOG4CXX_FUZZERS) set(PROGRAM_NAME "${fuzzerName}") add_executable(${PROGRAM_NAME} ${fuzzerName}.cpp) target_compile_definitions(${PROGRAM_NAME} PRIVATE ${FUZZER_COMPILE_DEFINITIONS} ${LOG4CXX_COMPILE_DEFINITIONS} ${APR_COMPILE_DEFINITIONS} ${APR_UTIL_COMPILE_DEFINITIONS}) target_include_directories(${PROGRAM_NAME} PRIVATE ${CMAKE_CURRENT_LIST_DIR} $) target_link_libraries(${PROGRAM_NAME} PRIVATE ${FUZZER_SANITIZE_FLAGS} log4cxx ${APR_UTIL_LIBRARIES} ${EXPAT_LIBRARIES} ${APR_LIBRARIES} ${APR_SYSTEM_LIBS}) if(WIN32) set_target_properties(${PROGRAM_NAME} PROPERTIES VS_DEBUGGER_ENVIRONMENT "PATH=${ESCAPED_PATH}" VS_DEBUGGER_WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} FOLDER Fuzzers) endif() endforeach() apache-log4cxx-1.3.1/src/fuzzers/cpp/PatternLayoutFuzzer.cpp0000644000175100001770000000750514721727031023511 0ustar runnerdocker/* * 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. */ #include // for `cout`, `endl` #include // for `exit()`, `EXIT_FAILURE` #include // for `readlink`, `chdir` #include // for `dirname` #include // for `PATH_MAX` #include // for `put_time()` #include // for `time()` #include #include #include using namespace LOG4CXX_NS; namespace LOG4CXX_NS::fuzzer { /** * Appender encoding incoming log events using the provided layout. * It is intended for appender-agnostic fuzzing. */ class EncodingAppender : public AppenderSkeleton { public: DECLARE_LOG4CXX_OBJECT(EncodingAppender) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(EncodingAppender) LOG4CXX_CAST_ENTRY_CHAIN(AppenderSkeleton) END_LOG4CXX_CAST_MAP() EncodingAppender() : AppenderSkeleton() {} EncodingAppender(const LayoutPtr& layout) : AppenderSkeleton(layout) {} void close() override {} bool requiresLayout() const override { return true; } void append(const spi::LoggingEventPtr& event, helpers::Pool& pool) override { LogString msg; getLayout()->format(msg, event, pool); } void activateOptions(helpers::Pool& pool) override {} void setOption(const LogString& option, const LogString& value) override {} }; // class IMPLEMENT_LOG4CXX_OBJECT(EncodingAppender) LOG4CXX_PTR_DEF(EncodingAppender); } // namespace static std::time_t logTime; static std::tm* logTimeBuffer; #define LOG(stream) \ logTime = std::time(nullptr); \ logTimeBuffer = std::localtime(&logTime); \ stream << std::put_time(logTimeBuffer, "%Y-%m-%d %H:%M:%S") << " [" << __FILE_NAME__ << ":" << __LINE__ << "] " static void findExecutablePath(char* buffer) { ssize_t length = readlink("/proc/self/exe", buffer, PATH_MAX); if (length == -1) { LOG(std::cerr) << "ERROR: Failed to find the executable path" << std::endl; exit(EXIT_FAILURE); } buffer[length] = '\0'; } static void chdirExecutableHome() { char executablePath[PATH_MAX]; findExecutablePath(executablePath); char* executableHome = dirname(executablePath); if (chdir(executableHome) != 0) { LOG(std::cerr) << "DEBUG: Executable path: " << executablePath << std::endl; LOG(std::cerr) << "DEBUG: Executable home: " << executableHome << std::endl; LOG(std::cerr) << "ERROR: Failed to `chdir()` the executable path" << std::endl; } } static int INITIALIZED = 0; static void init() { if (INITIALIZED != 0) { return; } LOG(std::cout) << "INFO: Produced using the Git commit ID: " << GIT_COMMIT_ID << std::endl; chdirExecutableHome(); PropertyConfigurator::configure("PatternLayoutFuzzer.properties"); INITIALIZED = 1; } #define MAX_STRING_LENGTH 512 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { init(); LoggerPtr logger = Logger::getRootLogger(); FuzzedDataProvider dataProvider(data, size); while (dataProvider.remaining_bytes() > 0) { std::string message = dataProvider.ConsumeRandomLengthString(MAX_STRING_LENGTH); LOG4CXX_INFO(logger, message); } return 0; } apache-log4cxx-1.3.1/src/CMakeLists.txt0000644000175100001770000000467214721727031017234 0ustar runnerdocker# # 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. # cmake_policy(SET CMP0079 NEW) include(${CMAKE_CURRENT_LIST_DIR}/cmake/boost-fallback/boost-fallback.cmake) include(${CMAKE_CURRENT_LIST_DIR}/cmake/compiler-features/check-compiler-support.cmake) add_subdirectory(main) target_compile_definitions(log4cxx PRIVATE ${LOG4CXX_COMPILE_DEFINITIONS} ${APR_COMPILE_DEFINITIONS} ${APR_UTIL_COMPILE_DEFINITIONS} ) target_include_directories(log4cxx INTERFACE $ PRIVATE ${APR_INCLUDE_DIR} ${APR_UTIL_INCLUDE_DIR}) target_link_libraries(log4cxx PRIVATE ${APR_UTIL_LIBRARIES} ${EXPAT_LIBRARIES} ${APR_LIBRARIES} ${APR_SYSTEM_LIBS}) if(HAS_LIBESMTP) target_include_directories(log4cxx PRIVATE ${ESMTP_INCLUDE_DIR}) target_link_libraries(log4cxx PRIVATE ${ESMTP_LIBRARIES}) endif() if(HAS_ODBC) target_include_directories(log4cxx PRIVATE ${ODBC_INCLUDE_DIR}) target_link_libraries( log4cxx PRIVATE ${ODBC_LIBRARIES}) endif(HAS_ODBC) if(BUILD_TESTING) add_subdirectory(test) endif() option(BUILD_EXAMPLES "Build log4cxx examples" ${BUILD_TESTING}) if(BUILD_EXAMPLES) add_subdirectory(examples/cpp) endif() # Find LibFuzzer include("${CMAKE_CURRENT_LIST_DIR}/cmake/FindLibFuzzer.cmake") # Define `BUILD_FUZZERS_DEFAULT` if(BUILD_TESTING AND LIBFUZZER_FOUND) set(BUILD_FUZZERS_DEFAULT ON) else() set(BUILD_FUZZERS_DEFAULT OFF) endif() # Define `BUILD_FUZZERS` option(BUILD_FUZZERS "Build log4cxx fuzzers" ${BUILD_FUZZERS_DEFAULT}) if(BUILD_FUZZERS) if(NOT LIBFUZZER_FOUND) message(SEND_ERROR "libfuzzer, required by the requested fuzzer build, is not found") else() add_subdirectory(fuzzers/cpp) endif() endif() option(BUILD_SITE "Build log4cxx website" OFF) if(BUILD_SITE) add_subdirectory(site) endif() apache-log4cxx-1.3.1/src/site/0000755000175100001770000000000014721727031015427 5ustar runnerdockerapache-log4cxx-1.3.1/src/site/markdown/0000755000175100001770000000000014721727031017251 5ustar runnerdockerapache-log4cxx-1.3.1/src/site/markdown/license.md0000644000175100001770000003022114721727031021213 0ustar runnerdockerLicense {#license} === # Overview Typically the licenses listed for the project are that of the project itself, and not of dependencies. ## Project License Apache License, Version 2.0 ~~~ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. 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 [yyyy] [name of copyright owner] 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-log4cxx-1.3.1/src/site/markdown/log-flow.md0000644000175100001770000000416614721727031021330 0ustar runnerdockerLog Flow {#log-flow} === Messages are logged as follows: 1. If using the Log4cxx macros(e.g. `LOG4CXX_DEBUG`), the macro must first be enabled. If the macro is not enabled(for example by setting the `LOG4CXX_THRESHOLD` macro), then the log message is not compiled in and the line of code becomes a no-op. 2. The logger level is checked to see if the request level is enabled. If it is, the message is then sent to the logger. 3. The logger creates a new message and gives it to all of its appenders. 4. Each appender checks the logging event's level is greater or equal to the appender's threshold level. 5. Each appender checks its filters to see if the message should be logged. Filters can perform the following actions: 1. Accept the message: This message will immediately be logged without consulting any remaining filters 2. Reject the message: This message will immediately be rejected without consulting any remaining filters 3. Neutral: This filter neither rejects nor accepts the message, it will be passed on to the next filter in the chain If a filter accepts the message, the message will be logged. If no filter rejects the message, the message will be logged. The following flow diagram shows how messages flow through the system: ![](images/log4cxx-flow.png) apache-log4cxx-1.3.1/src/site/markdown/buildsystems.md0000644000175100001770000000463614721727031022333 0ustar runnerdockerUsage with your build system {#buildsystems} === [TOC] The following code snippets show how to use Log4cxx with various different buildsystems. Note that we are unable to provide support for all buildsystems that you may be using. CMake is fully supported for building, as well as any buildsystem that can use `pkgconfig` in order to find packages. When using `pkgconfig`, the package name is `liblog4cxx`. # How do I use Log4cxx with CMake? {#use_with_cmake} Add the following to your CMakeLists.txt file: ~~~ find_package(log4cxx) ... other buildsystem information here ... target_link_libraries( executable PRIVATE log4cxx ) ~~~ # How do I use Log4cxx with CMake and pkg-config? {#use_with_cmake_pkgconfig} Add the following to your CMakeLists.txt file: ~~~ find_package(PkgConfig) pkg_check_modules(log4cxx REQUIRED liblog4cxx) ... other buildsystem information here ... target_link_libraries( executable PRIVATE ${log4cxx_LIBRARIES} ) target_include_directories( executable PRIVATE ${log4cxx_INCLUDE_DIRS} ) ~~~ # How do I use Log4cxx with QMake? {#use_with_qmake} Add the following to your .pro file: ~~~ CONFIG += link_pkgconfig PKGCONFIG += liblog4cxx ~~~ # How do I use Log4cxx with plain Make? {#use_with_make} You probably don't want to do this - it is highly recommended to use a proper buildsystem. However, the following minimal Makefile will build and link an application: ~~~ CXXFLAGS += $(shell pkg-config --cflags liblog4cxx) LDFLAGS += $(shell pkg-config --libs liblog4cxx) all: main.o $(CXX) -o application main.o $(LDFLAGS) ~~~ apache-log4cxx-1.3.1/src/site/markdown/concepts.md0000644000175100001770000006166214721727031021424 0ustar runnerdockerLoggers, Appenders and Layouts {#concepts} === [TOC] Log4cxx has three main components: *loggers*, *appenders* and *layouts*. These three types of components work together to enable developers to log messages according to message type and level, and to control at runtime how these messages are formatted and where they are reported. Configuration of the Log4cxx environment is typically done at application initialization. The preferred way is by reading a configuration file. This approach was discussed in [Runtime Configuration]. # Loggers {#loggers} The first and foremost advantage of any logging API over plain `std::cout` resides in its ability to disable certain log statements while allowing others to print unhindered. This capability is provided by assigning each logging request to a category. A Log4cxx category is a name and it is held by a log4cxx::Logger instance. The name of the class in which the logging request appears is a commonly used naming scheme but any category naming scheme may be used. Logging category names (or equivalently logger name) are case-sensitive. ## Naming {#naming} Log4cxx makes it easy to name loggers by *software component*. This can be accomplished by statically instantiating a logger in each class, with the logger name equal to the fully qualified name of the class. This is a useful and straightforward method of defining loggers. As the log output bears the name of the generating logger, this naming strategy makes it easy to identify the origin of a log message. However, this is only one possible, albeit common, strategy for naming loggers. Log4cxx does not restrict the possible set of loggers. The developer is free to name the loggers as desired. Nevertheless, naming loggers after the class where they are located seems to be the best strategy known so far. Logger names follow a hierarchical naming rule. A logger is said to be an *ancestor* of another logger if its name followed by a dot is a prefix of the *descendant* logger name. A logger is said to be a *parent* of a *child* logger if there are no ancestors between itself and the descendant logger. For example, the logger named `com.foo` is a parent of the logger named `com.foo.Bar`. Similarly, `java` is a parent of `java.util` and an ancestor of `java.util.Vector`. This naming scheme should be familiar to most developers. Sometimes a per object logger is useful. When each class instance has a identifiable name (e.g. when it is instantiated from configuration data) add a member variable to hold a log4cxx::LoggerInstancePtr and initialize it with a name that makes it a *descendant* of the class. This allows activation of DEBUG logging for a single object or all objects of that class. ## Instantiation {#getLogger} The root logger resides at the top of the hierarchy. It is exceptional in two ways: 1. it always exists, 2. it cannot be retrieved by name. Use the class static method log4cxx::Logger::getRootLogger or log4cxx::LogManager::getRootLogger to retrieve it. All other loggers are held in a log4cxx::spi::LoggerRepository singleton. They can be retrieved by calling a log4cxx::Logger::getLogger static class method which takes the name of the desired logger as an argument. An instance of log4cxx::Logger is instantiated if a logger of that name is not already held by the log4cxx::spi::LoggerRepository instance. The core Log4cxx API is made available by \#include . The commonly used log4cxx/logger.h methods and macros are listed below. ~~~{.cpp} namespace log4cxx { class Logger { public: // Creation & retrieval methods: static LoggerPtr getRootLogger(); static LoggerPtr getLogger(const std::string& name); static LoggerPtr getLogger(const std::wstring& name); } } // // Use these macros instead of calling Logger methods directly. // Macros will handle char or wchar_t pointers or strings // and any object that provides a // operator<<(std::ostream&, ...) overload. // #define LOG4CXX_TRACE(logger, expression) ... #define LOG4CXX_DEBUG(logger, expression) ... #define LOG4CXX_INFO(logger, expression) ... #define LOG4CXX_WARN(logger, expression) ... #define LOG4CXX_ERROR(logger, expression) ... #define LOG4CXX_FATAL(logger, expression) ... ~~~ Calling the *getLogger* method with the same name will always return a reference to the exact same logger object. For example, in ~~~{.cpp} auto x = log4cxx::Logger::getLogger("wombat"); auto y = log4cxx::Logger::getLogger("wombat"); ~~~ *x* and *y* refer to *exactly* the same logger object. Thus, it is possible to configure a logger and then to retrieve the same instance somewhere else in the code without passing around references. In fundamental contradiction to biological parenthood, where parents always preceed their children, Log4cxx loggers can be created and configured in any order. In particular, a "parent" logger will find and link to its descendants even if it is instantiated after them. ## Requests {#requests} Logging requests are made by invoking a method of a logger instance, preferrably through the use of LOG4CXX\_INFO or similar macros which support short-circuiting if the threshold is not satisfied and use of the insertion operator (\<\<) in the message parameter. ~~~{.cpp} log4cxx::LoggerPtr logger(log4cxx::Logger::getLogger("com.foo")); const char* region = "World"; LOG4CXX_INFO(logger, "Simple message text."); LOG4CXX_INFO(logger, "Hello, " << region); LOG4CXX_DEBUG(logger, L"Iteration " << i); LOG4CXX_DEBUG(logger, "e^10 = " << std::scientific << exp(10.0)); // // Use a wchar_t first operand to force use of wchar_t based stream. // LOG4CXX_WARN(logger, L"" << i << L" is the number of the iteration."); ~~~ ### Logging Custom Types {#custom-types} Often, the data that needs to be logged is not just standard data types (such as int, string, etc), but amalgamations of those types in a data structure such as a class or struct. In order to log these custom types, simply override an `operator<<` function, the same as if you would print the custom type to `std::cout`. This can be accomplished by doing the following: ~~~{.cpp} struct MyStruct { int x; }; std::ostream& operator<<( std::ostream& stream, const MyStruct& mystruct ){ stream << "[MyStruct x:" << mystruct.x << "]"; return stream; } void someMethod(){ MyStruct mine; mine.x = 90; LOG4CXX_INFO( logger, "Some important information: " << mine ); } ~~~ This will output data similar to the following: ~~~ 0 [0x7fd1eed63bc0] INFO root null - Some important information: [MyStruct x:90] ~~~ ### Using {fmt} style requests {#logging-with-fmt} One issue with utilizing Log4cxx and its ostream style of logging is that log statements can be very awkward if you need to precisely format something: ~~~{.cpp} LOG4CXX_INFO( rootLogger, "Numbers can be formatted with excessive operator<<: " << std::setprecision(3) << 22.456 << " And as hex: " << std::setbase( 16 ) << 123 ); ~~~ This leads to very awkward code to read and write, especially as iostreams don't support positional arguments at all. In order to get around this, Log4cxx provides a family of macros that support positional arguments and printf-like formatting, which makes for much clearer (and more efficient) code like the following: ~~~{.cpp} LOG4CXX_INFO_FMT( rootLogger, "Numbers can be formatted with a format string {:.1f} and as hex: {:x}", 22.456, 123 ); ~~~ The `LOG4CXX_[level]_FMT` macros use the [{fmt}](https://fmt.dev/latest/index.html) library by default. Note that Log4cxx does not include a copy of {fmt}, so you must include the correct headers and linker flags in order to use the `LOG4CXX_[level]_FMT` family of macros. Provide `LOG4CXX_FORMAT_NS=std` to the preprocessor to have the `LOG4CXX_[level]_FMT` macros use the standard library version of [format](https://en.cppreference.com/w/cpp/utility/format/format). As with the standard logger macros, these macros will also be compiled out if the `LOG4CXX_THRESHOLD` macro is set to a level that will compile out the non-FMT macros. A full example can be seen in the \ref format-string.cpp file. ### Overhead {#request-cost} One of the often-cited arguments against logging is its computational cost. This is a legitimate concern as even moderately sized applications can generate thousands of log requests. Much effort was spent measuring and tweaking logging performance. Log4cxx claims to be fast and flexible: speed first, flexibility second. For performance sensitive applications, you should be aware of the following. 1. **Logging performance when logging is turned off.** The LOG4CXX\_DEBUG and similar macros have a cost of an in-lined null pointer check plus an integer comparison when the logger not currently enabled for that level. The other terms inside the macro are not evaluated. When the level is enabled for a logger but the logging hierarchy is turned off entirely or just for a set of levels, the cost of a log request consists of a method invocation plus an integer comparison. 2. **Actually outputting log messages** This is the cost of formatting the log output and sending it to its target destination. Here again, a serious effort was made to make layouts (formatters) perform as quickly as possible. The same is true for appenders. 3. **The cost of changing a logger's level.** The threshold value stored in any child logger is updated. This is done iterating over the map of all known logger objects and walking the hierarchy of each. There has been a serious effort to make this hierarchy walk to be as fast as possible. For example, child loggers link only to their existing ancestors. In the *BasicConfigurator* example shown earlier, the logger named *com.foo.Bar* is linked directly to the root logger, thereby circumventing the nonexistent *com* or *com.foo* loggers. This significantly improves the speed of the walk, especially in "sparse" hierarchies. ### Removing log requests {#removing-log-statements} Sometimes, you may want to remove all log statements from your program, either for speed purposes or to remove sensitive information. This can easily be accomplished at build-time when using the standard `LOG4CXX_[level]` macros (`LOG4CXX_TRACE`, `LOG4CXX_DEBUG`, `LOG4CXX_INFO`, `LOG4CXX_WARN`, `LOG4CXX_ERROR`, `LOG4CXX_FATAL`) or their {fmt} library equivalents (`LOG4CXX_TRACE_FMT`, `LOG4CXX_DEBUG_FMT`, `LOG4CXX_INFO_FMT`, `LOG4CXX_WARN_FMT`, `LOG4CXX_ERROR_FMT`, `LOG4CXX_FATAL_FMT`). Log statements can be removed either above a certain level, or they can be disabled entirely. For example, if we want to remove all log statements within our program that use the `LOG4CXX_[level]` family of macros, add a preprocessor definition `LOG4CXX_THRESHOLD` set to 50001 or greater. This will ensure that any log statement that uses the `LOG4CXX_[level]`-macro will be compiled out of the program. To remove all log statements at `DEBUG` or below, set `LOG4CXX_THRESHOLD` to a value between 10001-20000. The levels are set as follows: |Logger Level|Integer Value| |------------|-------------| |TRACE |5000 | |DEBUG |10000 | |INFO |20000 | |WARN |30000 | |ERROR(1) |40000 | |FATAL |50000 | (1) The `LOG4CXX_ASSERT` macro is the same level as `LOG4CXX_ERROR` Note that this has no effect on other macros, such as using the `LOG4CXX_LOG`, `LOG4CXX_LOGLS`, or `LOG4CXX_L7DLOG` family of macros. ### Removing location information {#removing-location-information} Whenever you log a message with Log4cxx, metadata about the location of the logging statement is captured as well through the preprocessor. This includes the file name, the method name, and the line number. If you would not like to include this information in your build but you still wish to keep the log statements, define `LOG4CXX_DISABLE_LOCATION_INFO` in your build system. This will allow log messages to still be created, but the location information will be invalid. ## Levels {#levels} A log4cxx::Logger instance *may* be assigned a specific level otherwise it will inherit it from the closest ancestor with an assigned level. The root logger always has an assigned level. The pre-defined levels: TRACE, DEBUG, INFO, WARN, ERROR and FATAL are available. These are defined in the log4cxx/level.h file. Additional levels may be registered by the application but this is not recommended (See [Custom_levels]). A logging request is said to be *enabled* if its level is higher than or equal to the level of its logger. Otherwise, the request is said to be *disabled*. A logger without an assigned level will inherit one from the hierarchy. This rule is summarized below. ### Level Inheritance {#level-inheritance} The *effective level* for a given logger *X.Y.Z*, is equal to the first assigned in the logger hierarchy, starting at *X.Y.Z* and proceeding upwards in the hierarchy towards the *root* logger. To ensure that all loggers can eventually inherit a level, the root logger always has an assigned level. Below are four tables with various assigned level values and the resulting effective levels according to the above rule. | Logger name | Assigned level | Effective level | | ----------- | -------------- | --------------- | | root | INFO | INFO | | X | none | INFO | | X.Y | none | INFO | | X.Y.Z | none | INFO | Example 1 In example 1 above, only the root logger is assigned a level. This level value, *INFO*, is inherited by the other loggers *X*, *X.Y* and *X.Y.Z*. | Logger name | Assigned level | Effective level | | ----------- | -------------- | --------------- | | root | INFO | INFO | | X | WARN | WARN | | X.Y | DEBUG | DEBUG | | X.Y.Z | TRACE | TRACE | Example 2 In example 2, all loggers have an assigned level value. There is no use of level inheritence. | Logger name | Assigned level | Effective level | | ----------- | -------------- | --------------- | | root | INFO | INFO | | X | DEBUG | DEBUG | | X.Y | none | DEBUG | | X.Y.Z | WARN | WARN | Example 3 In example 3, the loggers *root*, *X* and *X.Y.Z* are assigned the levels *INFO*, *DEBUG* and *WARN* respectively. The logger *X.Y* inherits its level from its parent *X*. | Logger name | Assigned level | Effective level | | ----------- | -------------- | --------------- | | root | INFO | INFO | | X | DEBUG | DEBUG | | X.Y | none | DEBUG | | X.Y.Z | none | DEBUG | Example 4 In example 4, the loggers *root* and *X* and are assigned the levels *INFO* and *DEBUG* respectively. The loggers *X.Y* and *X.Y.Z* inherit their level from their nearest parent having an assigned level, *X*. ### Basic Selection Rule {#selection-rule} A log request of level *p* in a logger with (either assigned or inherited, whichever is appropriate) level *q*, is enabled if *p \>= q*. This rule is at the heart of Log4cxx. It assumes that levels are ordered. For the standard levels, we have *TRACE \< DEBUG \< INFO \< WARN \< ERROR \< FATAL*. Here is an example of this rule. ~~~{.cpp} // get a logger instance named "com.foo" auto logger = log4cxx::Logger::getLogger("com.foo"); // Now set its level. Normally you do not need to set the // level of a logger programmatically. This is usually done // in configuration files. logger->setLevel(log4cxx::Level::getInfo()); auto barlogger = log4cxx::Logger::getLogger("com.foo.Bar"); // This request is enabled, because WARN >= INFO. LOG4CXX_WARN(logger, "Low fuel level."); // This request is disabled, because DEBUG < INFO. LOG4CXX_DEBUG(logger, "Starting search for nearest gas station."); // The logger instance barlogger, named "com.foo.Bar", // will inherit its level from the logger named // "com.foo" Thus, the following request is enabled // because INFO >= INFO. LOG4CXX_INFO(barlogger. "Located nearest gas station."); // This request is disabled, because DEBUG < INFO. LOG4CXX_DEBUG(barlogger, "Exiting gas station search"); ~~~ # Appenders {#appenders} The ability to selectively enable or disable logging requests based on their logger is only part of the picture. Log4cxx allows logging requests to print to multiple destinations. In Log4cxx speak, an output destination is called an *appender*. Log4cxx provides appenders to write to: - [stdout or stderr](@ref log4cxx.ConsoleAppender) - [files](@ref log4cxx.rolling.RollingFileAppender) - [the NT Event log](@ref log4cxx.nt.NTEventLogAppender) - [the UNIX Syslog](@ref log4cxx.net.SyslogAppender) - [a TCP port](@ref log4cxx.net.TelnetAppender) - [a remote log processor](@ref log4cxx.net.XMLSocketAppender) - [a SMTP server](@ref log4cxx.net.SMTPAppender) - [a database](@ref log4cxx.db.ODBCAppender) If the same file receives log requests concurrently from multiple process, use [this appender](@ref log4cxx.rolling.MultiprocessRollingFileAppender). It is also possible to log [asynchronously](@ref log4cxx.AsyncAppender) to another appender. See \ref async-example.xml The [addAppender](@ref log4cxx.Logger.addAppender) method adds an appender to a given logger. More than one appender can be attached to a logger. ## Additivity {#appender-additivity} Each enabled logging request for a given logger will be forwarded to all the appenders in that logger as well as the appenders higher in the hierarchy. In other words, appenders are inherited additively from the logger hierarchy. For example, if a console appender is added to the root logger, then all enabled logging requests will at least print on the console. If in addition a file appender is added to a logger, say *C*, then enabled logging requests for *C* and *C*'s children will print on a file *and* on the console. It is possible to override this default behavior so that appender accumulation is no longer additive by [setting the additivity flag](@ref log4cxx.Logger.setAdditivity) to `false`. The rules governing appender additivity are summarized below. The output of a log statement of logger *C* will go to all the appenders in *C* and its ancestors. This is the meaning of the term "appender additivity". However, if an ancestor of logger *C*, say *P*, has the additivity flag set to *false*, then *C*'s output will be directed to all the appenders in *C* and it's ancestors up to and including *P* but, not the appenders in any of the ancestors of *P*. Loggers have their additivity flag set to *true* by default, meaning output goes to the appender attached to a parent [Logger](@ref log4cxx.Logger). It is therefore often sufficient to configure or attach an appender only to the root logger in the [Hierarchy](@ref log4cxx.Hierarchy). The table below shows an example: | Logger Name | Added Appenders | Additivity Flag | Output Targets | Comment | | --------------- | --------------- | --------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | root | A1 | not applicable | A1 | The root logger is anonymous but can be accessed with the log4cxx::Logger::getRootLogger() method. There is no default appender attached to root. | | x | A-x1, A-x2 | true | A1, A-x1, A-x2 | Appenders of "x" and root. | | x.y | none | true | A1, A-x1, A-x2 | Appenders of "x" and root. | | x.y.z | A-xyz1 | true | A1, A-x1, A-x2, A-xyz1 | Appenders in "x.y.z", "x" and root. | | security | A-sec | false | A-sec | No appender accumulation since the additivity flag is set to *false*. | | security.access | none | true | A-sec | Only appenders of "security" because the additivity flag in "security" is set to *false*. | # Layouts {#layouts} More often than not, users wish to customize not only the output destination but also the output format. This is accomplished by associating a *layout* with an appender. The layout is responsible for formatting the logging request according to the user's wishes, whereas an appender takes care of sending the formatted output to its destination. The [PatternLayout](@ref log4cxx.PatternLayout), part of the standard Log4cxx distribution, lets the user specify the output format according to conversion patterns similar to the C language *printf* function. For example, the PatternLayout with the conversion pattern `%%r [%%t] %%-5p %%c - %%m%%n` will output something akin to: ~~~ 176 [main] INFO org.foo.Bar - Located nearest gas station. ~~~ The first field is the number of milliseconds elapsed since the start of the program. The second field is the thread making the log request. The third field is the level of the log statement. The fourth field is the name of the logger associated with the log request. The text after the '-' is the message of the statement. The following examples show how you might configure the PatternLayout in order to achieve the results shown. Each example has two blocks of code: the layout for the PatternLayout, and a sample output message. ## Pattern 1 {#pattern1} This pattern contains the date in an ISO-8601 format(without fractional seconds), followed by the logger name, the level, and then the message. ~~~ [%d{yyyy-MM-dd HH:mm:ss}] %c %-5p - %m%n ~~~ ~~~ [2020-12-24 15:31:46] root INFO - Hello there! ~~~ ## Pattern 2 {#pattern2} Similar to Pattern 1, except using ISO-8601 with fractional seconds ~~~ [%d] %c %-5p - %m%n ~~~ ~~~ [2020-12-24 15:35:39,225] root INFO - Hello there! ~~~ ## Pattern 3 {#pattern3} Prints out the number of milliseconds since the start of the application, followed by the level(5 character width), followed by the logger name (20 character width), followed by the message. ~~~ %r %-5p %-20c %m%n ~~~ ~~~ 0 INFO root Hello there! ~~~ ## Pattern 4 {#pattern4} If you have no idea where a log message is coming from, it's possible to print out more information about the place the log statement is coming from. For example, we can get the filename, class name, method name, and line number in one log message. This utilises the %%F(file name), %%C(class name), %%M(method name), %%L(line number) patterns to output more information: ~~~ (%F:%C[%M]:%L) %m%n ~~~ Possible output: ~~~ (/home/robert/log4cxx-test-programs/fooclass.cpp:FooClass[FooClass]:9) Constructor running (/home/robert/log4cxx-test-programs/fooclass.cpp:FooClass[doFoo]:13) Doing foo ~~~ Note that unlike Java logging, the location information is free(as it utilizes macros to determine this information at compile-time). The other layouts provided in Log4cxx are: - [libfmt patterns](@ref log4cxx.FMTLayout) - [a HTML table](@ref log4cxx.HTMLLayout) - [a JSON dictionary](@ref log4cxx.JSONLayout) - [level - message](@ref log4cxx.SimpleLayout) - [log4j event elements](@ref log4cxx.xml.XMLLayout) \example format-string.cpp This example shows logging using the [{fmt}](https://fmt.dev/latest/index.html) library. \example async-example.xml This example shows a configuration using the [asynchronous appender](@ref log4cxx.AsyncAppender). [Custom_levels]:faq.html#custom_levels [Runtime Configuration]:quick-start.html#configuration apache-log4cxx-1.3.1/src/site/markdown/example-programs.md0000644000175100001770000002004314721727031023055 0ustar runnerdockerQuick Start {#quick-start} === [TOC] Creating useful log information requires a fair amount of planning and effort. Observation shows that approximately 4 percent of code is dedicated to logging. Consequently, even moderately sized applications will have thousands of logging statements embedded within their code. Given their number, it becomes imperative to manage these log statements without the need to modify them manually. Let us give a taste of how this is done with the help of an imaginary application *MyApp* that uses Log4cxx. # A Simple Example {#example1} In order to start using Log4cxx, a simple example program is shown below. This program does nothing useful, but it shows the basics of how to start using Log4cxx. Using the [BasicConfigurator](@ref log4cxx.BasicConfigurator) class, we are able to quickly configure the library to output DEBUG, INFO, etc level messages to standard output. \include MyApp1.cpp The above application does nothing useful except to show how to initialize logging with the BasicConfigurator and do logging with different loggers. Note that file based configurations are also possible - see [DOMConfigurator](@ref log4cxx.xml.DOMConfigurator.configure) and [PropertyConfigurator](@ref log4cxx.PropertyConfigurator.configure). Configuring Log4cxx in the main function has the limitation that any logging statements in static initialization code will not generate output. Log4cxx must be configured before it is used and in this example Log4cxx is not configured until the main() function starts. # A Less Simple Example {#example2} In this example we use a *getLogger()* wrapper function which configures Log4cxx on the first usage. The advantages of this approach are: - Log4cxx configuration can be reused in multiple applications. - The structure exhibits better [separation of concerns](https://en.wikipedia.org/wiki/Separation_of_concerns). - Log statements in static initialization code will generate output. This program (*MyApp*) begins by including the file that defines the com::foo::getLogger() function. It obtains a logger named *MyApp* (which in this example is the fully qualified name) from the com::foo::getLogger() function. *MyApp* uses the *com::foo::Bar* class defined in header file *com/foo/bar.h*. \include MyApp2.cpp The *com::foo::Bar* class is defined in header file *com/foo/bar.h*. \include com/foo/bar.h The *com::foo::Bar* class is implemented in the file *com/foo/bar.cpp*. \include com/foo/bar.cpp The header file \ref com/foo/config.h defines the com::foo::getLogger() function and a *LoggerPtr* type for convenience. The file \ref com/foo/config1.cpp implements the com::foo::getLogger() function defines *initAndShutdown* as a *static struct* so its constructor is invoked on the first call to the com::foo::getLogger() function and its destructor is automatically called during application exit. The invocation of the [BasicConfigurator::configure](@ref log4cxx.BasicConfigurator.configure) method creates a rather simple Log4cxx setup. This method is hardwired to add to the root logger a [ConsoleAppender](@ref log4cxx.ConsoleAppender). The output will be formatted using a [PatternLayout](@ref log4cxx.PatternLayout) set to the pattern `%%r [%%t] %%p %%c %%x - %%m%%n`. Note that by default, the root logger is assigned a *DEBUG* level. The output of MyApp is: ~~~ 0 [12345] INFO MyApp null - Entering application. 0 [12345] DEBUG com.foo.Bar null - Did it again! 0 [12345] INFO MyApp null - Exiting application. ~~~ # Runtime Configuration {#configuration} The Log4cxx environment is fully configurable programmatically. However, it is far more flexible to configure Log4cxx using configuration files. Currently, configuration files can be written in XML or in Java properties (key=value) format. The previous example always outputs the same log information. Fortunately, it is easy to modify *config.cpp* so that the log output can be controlled at runtime. Here is a slightly modified version. \include com/foo/config2.cpp This version of *config.cpp* instructs [PropertyConfigurator](@ref log4cxx.PropertyConfigurator.configure) to use the *MyApp.properties* file to configure Log4cxx. A more realistic approach would (for example) use the current module name to select the configuration file (see the \ref com/foo/config3.cpp file for how to do this). Here is a sample *MyApp.properties* configuration file that results in exactly same output as the previous [BasicConfigurator::configure](@ref log4cxx.BasicConfigurator.configure) based example. ~~~ # Set root logger level to DEBUG and its only appender to A1. log4j.rootLogger=DEBUG, A1 # A1 is set to be a ConsoleAppender. log4j.appender.A1=org.apache.log4j.ConsoleAppender # A1 uses PatternLayout. log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=%r [%t] %-5p %c %x - %m%n ~~~ It can be noticed that the PropertyConfigurator file format is the same as log4j. Suppose we are no longer interested in seeing the output of any component belonging to the *com::foo* package. The following configuration file shows one possible way of achieving this. ~~~ log4j.rootLogger=DEBUG, A1 log4j.appender.A1=org.apache.log4j.ConsoleAppender log4j.appender.A1.layout=org.apache.log4j.PatternLayout # Print the date in ISO 8601 format log4j.appender.A1.layout.ConversionPattern=%d [%t] %-5p %c - %m%n # Print only messages of level WARN or above in the package com.foo. log4j.logger.com.foo=WARN ~~~ The output of *MyApp* configured with this file is shown below. ~~~ 2022-12-13 11:01:45,091 [12345] INFO MyApp - Entering application. 2022-12-13 11:01:45,091 [12345] INFO MyApp - Exiting application. ~~~ As the logger *com.foo.Bar* does not have an assigned level, it inherits its level from *com.foo*, which was set to WARN in the configuration file. The log statement from the *Bar::doIt* method has the level *DEBUG*, lower than the logger level WARN. Consequently, *doIt()* method's log request is suppressed. Here is another configuration file that uses multiple appenders. \include MyApp.properties Calling the enhanced MyApp with the this configuration file will output the following on the console. ~~~ INFO [12345] (MyApp.cpp:8) - Entering application. DEBUG [12345] (bar.cpp:8) - Did it again! INFO [12345] (MyApp.cpp:11) - Exiting application. ~~~ In addition, as the root logger has been allocated a second appender, output will also be directed to the *example.log* file. This file will be rolled over when it reaches 100KB. When roll-over occurs, the old version of *example.log* is automatically moved to *example.log.1*. Note that to obtain these different logging behaviors we did not need to recompile code. We could just as easily have logged to a UNIX Syslog daemon, redirected all *com.foo* output to an NT Event logger, or forwarded logging events to a remote Log4cxx server, which would log according to local server policy, for example by forwarding the log event to a second Log4cxx server. \example com/foo/config.h This header file is for encapsulating Log4cxx configuration. \example com/foo/config1.cpp This file is a simplified example of encapsulated Log4cxx configuration. \example com/foo/config3.cpp This file is an example of how to use the current module name to select the Log4cxx configuration file. apache-log4cxx-1.3.1/src/site/markdown/library-design.md0000644000175100001770000000655014721727031022514 0ustar runnerdockerLibrary Design Notes {#library-design} === With version 1.0.0 of Log4cxx, the library is designed to be ABI stable, such that any internal changes to classes will not cause client code to break. In order to do this, there are a few patterns that are used in order to make sure that it stays stable. # Use of class-specific structs to hold data. This looks like the following in a header file: ``` class SomeClass { public: SomeClass(); ~SomeClass(); private: struct SomeClassPriv; std::unique_ptr m_priv; } ``` In the .cpp file, you then can define it and use it like the following: ``` struct SomeClass::SomeClassPriv { int someMemberVariable; }; SomeClass::SomeClass() : m_priv(std::make_unique()){} ``` This ensures that if new members need to be added to a class, or old ones removed, the size of the class will not change. # Inheriting classes with private data Because subclasses no longer have direct access to their parents' variables, a slight variation is used to allow subclasses to access parental variables, and to ensure that the parent only stores one pointer. This results in a separate hierarchy for the private data from the hierarchy of the class. This can be done to any depth that is required. ## Example parent\_priv.h: ``` #include "parent.h" struct Parent::ParentPrivate{ int parentVariable; }; ``` parent.h: ``` class Parent { pubic: struct ParentPrivate; Parent( std::unique_ptr priv ); virtual ~Parent(); protected: std::unique_ptr m_priv; }; ``` parent.cpp: ``` #include "parent_priv.h" Parent::Parent( std::unique_ptr priv ) : m_priv( std::move(priv) ){} ``` child.h: ``` #include "parent.h" class Child : public Parent { public: Child(); ~Child(); void example(); private: struct ChildPriv; }; ``` child.cpp: ``` #include "parent_priv.h" #include "child.h" struct Child::ChildPriv : public Parent::ParentPriv { int childVariable; }; Child::Child() : Parent(std::make_unique() ){} void Child::example(){ m_priv->parentVariable = ... ; // Can access parent variable via m_priv static_cast(m_priv.get())->childVariable = ... ; // Must static_cast to access child } ``` Caveats with this approach: * All variables effectively become protected. If they must be private for some reason, you could probably make the Priv struct be a friend class. # See Also Qt documentation on D-Pointers, which this pattern is based off of: https://wiki.qt.io/D-Pointer apache-log4cxx-1.3.1/src/site/markdown/filters.md0000644000175100001770000003044314721727031021247 0ustar runnerdockerFiltering Log Messages {#filters} === [TOC] # Labeling Log Output {#labeling-log-output} To uniquely stamp each request to relate it to a particular source, you can push contextual information into the *Nested Diagnostic Context* (NDC) using the *log4cxx::NDC* class or the *Mapped Diagnostic Context* provided by *log4cxx::MDC* class. For an example using log4cxx::NDC refer to \ref ndc-example.cpp. The NDC is managed per thread as a *stack* of contextual information. When the layout specifies that the NDC is to be included, each log entry will include the entire stack for the current thread. A log4cxx::PatternLayout allows named entries of the MDC to be included in the log message. The user is responsible for placing the correct information in the NDC/MDC by creating a *log4cxx::NDC* or *log4cxx::MDC* stack variable at a few well-defined points in the code. In contrast, the per-client logger approach commands extensive changes in the code. To illustrate this point, let us take the example of a servlet delivering content to numerous clients. The servlet can build the NDC at the very beginning of the request before executing other code. The contextual information can be the client's host name and other information inherent to the request, typically information contained in cookies. Hence, even if the servlet is serving multiple clients simultaneously, the logs initiated by the same code, i.e. belonging to the same logger, can still be distinguished because each client request will have a different NDC stack. Contrast this with the complexity of passing a freshly instantiated logger to all code exercised during the client's request. Nevertheless, some sophisticated applications, such as virtual hosting web servers, must log differently depending on the virtual host context and also depending on the software component issuing the request. Recent Log4cxx releases support multiple hierarchy trees. This enhancement allows each virtual host to possess its own copy of the logger hierarchy. # Excluding Log Output {#excluding-log-output} When dealing with large amounts of logging information, it can be useful to filter on messages that we are interested in. This filtering only takes places after determining that the level of the current logger would log the message in the first place (as shown in detail by [the flow chart]). Note that filters can only be applied on a per-appender basis, they do not globally affect anything. The filtering system is similar in concept to Linux iptables rules, in that there is a chain of filters that can accept a log message, deny the log message, or pass the message on to the next filter. Accepting a log message means that the message will be logged immediately without consulting other filters. Denying has the opposite affect, immediately dropping the log message and not consulting any other filters. See the documentation for [Filter](@ref log4cxx.spi.Filter) for some more information, or view a [configuration sample](@ref configuration-samples). The following filters are available: * [AndFilter](@ref log4cxx.filter.AndFilter) - Takes in a list of filters that must all match * [DenyAllFilter](@ref log4cxx.filter.DenyAllFilter) - Drops all log messages that reach it * [LevelMatchFilter](@ref log4cxx.filter.LevelMatchFilter) - Filter log messages based off of their level * [LevelRangeFilter](@ref log4cxx.filter.LevelRangeFilter) - Filter log messages based off of their level in a given range * [LocationInfoFilter](@ref log4cxx.filter.LocationInfoFilter) - Filter log messages based off of their location(line number and/or method name) * [LoggerMatchFilter](@ref log4cxx.filter.LoggerMatchFilter) - Accept or deny depending on the logger that generated the message * [MapFilter](@ref log4cxx.filter.MapFilter) - Based off of the log messages MDC, accept or deny the message * [StringMatchFilter](@ref log4cxx.filter.StringMatchFilter) - If the given substring is found in the message, accept or deny # Runtime Configuration {#configure-filter} ## Using MDC Values {#map-filter} The [MapFilter](@ref log4cxx.filter.MapFilter) allows filtering against data elements that are in the *Mapped Diagnostic Context* (*log4cxx::MDC*). | **Parameter Name** | **Type** | **Description** | |:-------------------|:----------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Operator | LogString | If the operator is `AND` then all the key/value pairs must match; any other value is implicitly an `OR` and a match by any one of the key/value pairs will be considered to be a match. The default value is `OR`. | | AcceptOnMatch | LogString | Action to take when the filter matches. May be `true` or `false`. The default value is `false`. | | MDC key | LogString | Any name other than `Operator` or `AcceptOnMatch` is considered a key to the MDC along with the value to match on. Keys may only be specified once; duplicate keys will replace earlier ones. | In this configuration, the [MapFilter](@ref log4cxx.filter.MapFilter) can be used to filter based on system inserted values such as IP address and/or Username. In this example, we assume that the program has inserted appropriate values for `user.ip` and `user.name` into the MDC. In this case, when both the IP address is `127.0.0.1` and the Username is `test`, the entry will not be logged. ```xml ``` If we wanted to exclude multiple IP addresses from the log, we need to define a separate filter for each one as we don’t support wildcards. Since the default `AcceptOnMatch` value is `false`, we can simplify to a single line per filter. In the configuration below we would skip logs for IP addresses matching 192.168.0.5 - 7. ```xml ``` In the case where we only want to log entries from a particular set of IP addresses (**not recommended** as this could be a security vulnerability), we need to have a final `DenyAllFilter` to catch the fall through. In this configuration, we would **only** log entries from 192.168.0.251 and 192.168.0.252. ```xml ``` ## Using the Request Location {#location-info-filter} The [LocationInfoFilter](@ref log4cxx.filter.LocationInfoFilter) allows filtering against the location in the file that the log statement was made. Location information must not be disabled in order for this filter to be effective. Location information is disabled with the `LOG4CXX_DISABLE_LOCATION_INFO` macro. | **Parameter Name** | **Type** | **Description** | |:-------------------|:----------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Operator | LogString | If the operator is `AND` then all the parts of the location(line number and method name) must match. If set to `OR` then only one needs to match. The default value is `OR`. | | AcceptOnMatch | bool | If `true`, accept the message when it matches the parameters. If `false`, deny the message when it matches the parameters. | | LineNumber | int | The line number to match on. The default line number is -1. | | Method | LogString | The method to match on. The method name may be compiler-specific. On GCC, the method name will look like `Class::methodName` | Assume that our code looks something like the following: ~~~{.cpp} LOG4CXX_TRACE(logger, "About to do something!"); for( int x = 0; x < 100; x++ ){ LOG4CXX_TRACE(logger, "Do something number " << x); } ~~~ For various reasons, we may want to know that we are about to do something, but we don't want to know each iteration of the loop. In order to filter out this one message we can create a LocationInfoFilter in order to specifiy the line number that this message is on in order to filter it out: ~~~{.xml} ~~~ Doing this allows us to still see the "About to do something!" message, but ignore each iteration of the loop. \example ndc-example.cpp This example shows how to add a context string to each logging message using the NDC. [the flow chart]:log-flow.html apache-log4cxx-1.3.1/src/site/markdown/configuration-samples.md0000644000175100001770000002007714721727031024112 0ustar runnerdockerConfiguration Samples {#configuration-samples} === [TOC] The following snippets show various ways of configuring Log4cxx. # Default Initialization Behaviour {#default-initialization} The Log4cxx library does not make any assumptions about its environment. In particular, when initially created the root [Logger](@ref log4cxx.Logger) has no appender. However the library will attempt automatic configuration. If the LoggerRepositoy is not yet configured on the first call to [getLogger](@ref log4cxx.LogManager.getLogger) of [LogManager](@ref log4cxx.LogManager), the [configure](@ref log4cxx.DefaultConfigurator.configure) method of [DefaultConfigurator](@ref log4cxx.DefaultConfigurator) is called via [ensureIsConfigured](@ref log4cxx.spi.LoggerRepository.ensureIsConfigured) method of [LoggerRepository](@ref log4cxx.spi.LoggerRepository). To use automatic configuration with a non-standard file name create and use your own wrapper for [getLogger](@ref log4cxx.LogManager.getLogger). A full example can be seen in the \ref com/foo/config3.cpp file. # XML Files {#xmlfiles} One way of configuring Log4cxx is with XML files. The following are some examples on various ways of using an XML file to configure the logging. ## XML Example 1 {#xml-example-1} This simple example simply writes messages to stdout. If you want to send messages to stderr instead, simply change the 'Target' value to `System.err`. ~~~{.xml} ~~~ Sample output: ~~~ Hello there! ~~~ ## XML Example 2 {#xml-example-2} This example sends data to both stdout, as well as to a file. With this configuration the "example.log" file will be created in our working directory. ~~~{.xml} ~~~ Sample output: ~~~ [2020-12-24 15:57:35] root INFO - Hello there! ~~~ ## XML Example 3 {#xml-example-3} This example shows how you can configure logging for a particular category. Assume that our loggers are in our code as such: ~~~{.cpp} log4cxx::LoggerPtr root = log4cxx::Logger::getRootLogger(); log4cxx::LoggerPtr com = log4cxx::Logger::getLogger( "com" ); log4cxx::LoggerPtr com_example = log4cxx::Logger::getLogger( "com.example" ); LOG4CXX_INFO( root, "Hello there!" ); LOG4CXX_DEBUG( com, "com logger debug" ); LOG4CXX_DEBUG( com_example, "com.example debug message" ); LOG4CXX_TRACE( com, "com debug message" ); LOG4CXX_TRACE( com_example, "com.example trace message" ); ~~~ For this configuration, we have set any logger that is at the `com` level or below to be debug. However, we have also set the logger `com.example` to have a more verbose `trace` level to see more information from that particular logger. The "example.log" file will be created in our temporary directory. ~~~{.xml} ~~~ Sample output: ~~~ [2020-12-24 16:05:48] root INFO - Hello there! [2020-12-24 16:05:48] com DEBUG - com logger debug [2020-12-24 16:05:48] com.example DEBUG - com.example debug message [2020-12-24 16:05:48] com.example TRACE - com.example trace message ~~~ ## XML Example 4 {#xml-example-4} This example shows how to add a filter to an appender that will accept messages that match a certain string. If our loggers are configured as such: ~~~{.cpp} log4cxx::LoggerPtr root = log4cxx::Logger::getRootLogger(); log4cxx::LoggerPtr com = log4cxx::Logger::getLogger( "com" ); log4cxx::LoggerPtr com_example = log4cxx::Logger::getLogger( "com.example" ); LOG4CXX_INFO( root, "Hello there!" ); LOG4CXX_DEBUG( com, "Starting to do the thing" ); LOG4CXX_DEBUG( com_example, "A more specific logger" ); LOG4CXX_TRACE( com, "Done with the thing" ); LOG4CXX_TRACE( com_example, "A very specific message" ); ~~~ and we only want to see messages that have the string "specific" in them, we can create a filter chain that will accept messages that have that, and deny everything else: ~~~{.xml} ~~~ Sample output: ~~~ [2021-03-26 20:20:36] com.example DEBUG - A more specific logger [2021-03-26 20:20:36] com.example TRACE - A very specific message ~~~ Note that even though we have the root logger set to the most verbose level(trace), the only messages that we saw were the ones with "specific" in them. \example auto-configured.cpp This is an example of logging in static initialization code and using the current module name to select the Log4cxx configuration file. apache-log4cxx-1.3.1/src/site/markdown/4-build.md0000644000175100001770000000314114721727031021032 0ustar runnerdockerBuild {#build} === As of version 0.11.0, the only supported build system for Log4cxx is CMake. Have a look at the [Building with CMake] page for more information. If you have trouble building, either [create an issue] or send a message to the [users mailing list](mailto:log4cxx-user@logging.apache.org). Various Linux distributions already have Log4cxx as part of their package managers - consult the documentation for your distribution to determine if a package already exists. See the following pages for information on building Log4cxx: * @subpage dependencies * @subpage build-cmake * @subpage build-vcpkg * @subpage supported-systems [Building with CMake]:@ref build-cmake [create an issue]: https://github.com/apache/logging-log4cxx/issues apache-log4cxx-1.3.1/src/site/markdown/environment-variables.md0000644000175100001770000000357714721727031024121 0ustar runnerdockerEnvironment Variables Used by Log4cxx {#environment-variables} === There are several environment variables that can be set in order to influence how Log4cxx works. They are summarized in the following table: | Environment Variable | Usage | | -------------------- | ----- | | LOG4CXX\_DEBUG | Set to the value 'true' to enable internal debugging of Log4cxx. All output goes to stderr. This can be useful to determine why a configuration file is not loading | | log4j.configuratorClass | Used to determine what class to use to configure the logging system | | LOG4CXX\_CONFIGURATOR\_CLASS | Used to determine what class to use to configure the logging system. Takes precedence over log4j.configuratorClass | | log4j.configuration | Set the file to load to configure the logging system | | LOG4CXX\_CONFIGURATION | Set the file to load to configure the logging system. Takes precedence over log4j.configuration | | LOG4CXX\_CONFIGURATION\_WATCH\_SECONDS | Set how often the configuration file should be checked for changes | apache-log4cxx-1.3.1/src/site/markdown/multiprocess.md0000644000175100001770000000300114721727031022316 0ustar runnerdockerLogging With Multiple Processes {#multiprocess-logging} === If you have multiple applications that all log to the same file, it is often desirable that the file that these applications write to will roll over when required. In order for that to happen, Log4cxx provides the log4cxx::rolling::MultiprocessRollingFileAppender that will check the size of the file when writing to the file and roll it over appropriately. This is an optional feature, and thus must be explicitly enabled when building Log4cxx. This feature is also only supported on Linux at the moment. Because this feature is non-standard, it may not work properly in all circumstances. apache-log4cxx-1.3.1/src/site/markdown/extending.md0000644000175100001770000001303314721727031021560 0ustar runnerdockerExtending Log4cxx {#extending-log4cxx} === Sometimes, you may want to extend Log4cxx, for example by creating a new appender to write out data in a new format. The following guide shows how you can extend Log4cxx in order to add a new appender. The full sample application can be found at \ref custom-appender.cpp and \ref custom-appender.xml . The first thing for our example is to create a class that extends log4cxx.AppenderSkeleton so that we don't need to implement all of the virtual methods that are defined in log4cxx.Appender: ~~~{.cpp} using namespace log4cxx; namespace com::foo { class NullWriterAppender : public AppenderSkeleton { }; } ~~~ Next, we need to add in a few macros in order to properly register our new appender with Log4cxx: ~~~{.cpp} using namespace log4cxx; namespace com::foo { class NullWriterAppender : public AppenderSkeleton { public: DECLARE_LOG4CXX_OBJECT(NullWriterAppender) BEGIN_LOG4CXX_CAST_MAP() LOG4CXX_CAST_ENTRY(NullWriterAppender) LOG4CXX_CAST_ENTRY_CHAIN(AppenderSkeleton) END_LOG4CXX_CAST_MAP() }; IMPLEMENT_LOG4CXX_OBJECT(NullWriterAppender) } ~~~ These macros allow Log4cxx to instantiate your class and provide log4cxx::cast. The `DECLARE_LOG4CXX_OBJECT` macro adds method declarations and the `IMPLEMENT_LOG4CXX_OBJECT` macro adds implementations. The `IMPLEMENT_LOG4CXX_OBJECT` also adds a static reference value which is initialized during program startup by calling, for example, `NullWriterAppender::registerClass()`. To avoid [Static Initialization Order Fiasco](https://en.cppreference.com/w/cpp/language/siof) when configuring Log4cxx during static initialization (as in [the recommended runtime configuration technique]) you should put your extension classes (and the `IMPLEMENT_LOG4CXX_OBJECT` macro) in a dynamic library (DSO/DLL) that is loaded before loading the Log4cxx configuration. Alternatively, you could call `NullWriterAppender::registerClass()` before loading the configuration. Multiple `registerClass()` calls do no harm. Now, let's add some basic functionality to our class. As the name of our class implies, we are going to do nothing with our appender here, as this is just an example. To that end, we need to implement the following: 1. Default constructor 2. `close` method 3. `requiresLayout` method 4. `append` method, which does the actual writing of the log event 5. `activateOptions`, which causes the class to reconfigure itself 6. `setOption`, which gets called whenever we get an option in a config file These are basically stub methods, with a few comments on their use: ~~~{.cpp} NullWriterAppender(){} void close() override {} bool requiresLayout() const override { return false; } void append(const spi::LoggingEventPtr& event, helpers::Pool& p) override { // This gets called whenever there is a valid event for our appender. } void activateOptions(helpers::Pool& pool) override { // Given all of our options, do something useful(e.g. open a file) } void setOption(const LogString& option, const LogString& value) override { if (helpers::StringHelper::equalsIgnoreCase ( option , LOG4CXX_STR("SOMEVALUE") , LOG4CXX_STR("somevalue") ) ) { // Do something with the 'value' here. } } ~~~ At this point, we now have a fully functioning(if useless) custom appender. We can now refer to this appender in our configuration file like so: ~~~{.xml} ~~~ When Log4cxx is configured, any messages that go to the `NullLogger` will then be forwarded on to the `NullWriterAppender`. This same technique can be used to add new classes of many different kinds to Log4cxx, including(but not limited to): * [Appenders](@ref log4cxx.Appender) * [Layouts](@ref log4cxx.Layout) * [Filters](@ref log4cxx.spi.Filter) \example custom-appender.cpp This example shows how to extend Log4cxx with a new appender. \example custom-appender.xml This example shows how to use a new appender in a configuration file. [the recommended runtime configuration technique]:quick-start.html#configuration apache-log4cxx-1.3.1/src/site/markdown/conclusions.md0000644000175100001770000000316314721727031022135 0ustar runnerdockerConclusions {#conclusions} === Apache Log4cxx is a popular logging package written in C++. One of its distinctive features is the notion of inheritance in loggers. Using a logger hierarchy it is possible to control which log statements are output at arbitrary granularity. This helps reduce the volume of logged output and minimize the cost of logging. One of the advantages of the Log4cxx API is its manageability. Once the log statements have been inserted into the code, they can be controlled with configuration files. They can be selectively enabled or disabled, and sent to different and multiple output targets in user-chosen formats. The Log4cxx package is designed so that log statements can remain in shipped code without incurring a heavy performance cost. apache-log4cxx-1.3.1/src/site/markdown/development/0000755000175100001770000000000014721727031021573 5ustar runnerdockerapache-log4cxx-1.3.1/src/site/markdown/development/build-cmake.md0000644000175100001770000001541314721727031024276 0ustar runnerdockerBuilding with CMake {#build-cmake} === [TOC] # Supported options | Option | Usage | |------------------------|-------| | LOG4CXX_WCHAR_T=no | Enable wchar_t API methods, choice of yes (default), no. | | LOG4CXX_UNICHAR=yes | Enable UniChar API methods, choice of yes, no (default). | | LOG4CXX_CFSTRING=yes | Enable CFString API methods, requires Mac OS/X CoreFoundation, choice of yes, no (default). | | BUILD_TESTING=off | Do not build tests. Tests are built by default | | BUILD_FUZZERS | Enabled by default if `BUILD_TESTING=ON` and libFuzzer is found. | | BUILD_SITE=OFF | Set to `ON` to enable the project website build. Requires Doxygen. | | BUILD_SHARED_LIBS=off| Build Log4cxx as a static library. A dynamically linked Log4cxx library is built by default. Any compilation unit that includes a Log4cxx header must define LOG4CXX_STATIC. | | APU_STATIC=yes | Link to the APR-Util static library. By default, the Log4cxx shared library is linked to the APR-Util shared library. If BUILD_SHARED_LIBS=off, the static APR-Util library is used. | | APR_STATIC=yes | Link to the APR static library. By default, the Log4cxx shared library is linked to the APR shared library. If BUILD_SHARED_LIBS=off, the static APR library is always used. | | LOG4CXX_TEST_PROGRAM_PATH=path | An extra path to prepend to the PATH for test programs. Log4cxx requires zip, sed, and grep on the PATH in order for the tests to work properly. | | PREFER_BOOST=on | Prefer the Boost version of dependent libraries over standard library | | LOG4CXX_QT_SUPPORT=ON | Enable QString API and log4cxx::qt namespace methods, requires QtCore, choice of ON, OFF (default). | | LOG4CXX_EVENTS_AT_EXIT=ON | Prevent static data cleanup to allow event logging during application exit. | | LOG4CXX_FORMAT_NAMESPACE=std | Make the `LOG4CXX_[level]_FMT` macros use [std::format](https://en.cppreference.com/w/cpp/utility/format/format) by default. | # Examples ## Unix type systems Make sure cmake (3.13+), g++, gzip, zip and make are available. On a Debian system these may be installed by: ~~~ $ sudo apt-get install build-essential cmake gzip zip ~~~ 1. Using the distro provided APR libraries and the cmake cursors UI to configure Log4cxx options. ~~~ $ apt-get install libapr1-dev libaprutil1-dev $ wget https://dlcdn.apache.org/logging/log4cxx/1.3.0/apache-log4cxx-1.3.0.tar.gz $ tar xf apache-log4cxx-1.3.0.tar.gz $ cd apache-log4cxx-1.3.0 $ mkdir build $ cd build $ ccmake .. $ make $ sudo make install ~~~ 2. Install libraries locally in $HOME/libraries and statically bind APR into the Log4cxx DSO. ~~~ $ wget https://archive.apache.org/dist/apr/apr-1.7.4.tar.bz2 $ tar xf apr-1.7.4.tar.bz2 $ cd apr-1.7.4 $ CFLAGS=-fPIC ./configure --prefix=$HOME/libraries $ make install $ cd $HOME $ wget https://archive.apache.org/dist/apr/apr-util-1.6.3.bz2 $ tar xf apr-util-1.6.3.bz2 $ cd apr-util-1.6.3 $ CFLAGS=-fPIC ./configure --with-apr=$HOME/libraries --prefix=$HOME/libraries $ make install $ cd $HOME $ wget https://dlcdn.apache.org/logging/log4cxx/1.3.0/apache-log4cxx-1.3.0.tar.gz $ tar xf apache-log4cxx-1.3.0.tar.gz $ cmake -S apache-log4cxx-1.3.0 -B build/log4cxx -DAPR_STATIC=yes -DAPU_STATIC=yes -DCMAKE_PREFIX_PATH=$HOME/libraries -DCMAKE_INSTALL_PREFIX=$HOME/Libraries -DCMAKE_BUILD_TYPE=Release $ cmake --build build/log4cxx --target install ~~~ ## Windows 1. The easiest way to get dependencies installed is to use vcpkg. Follow the directions at https://github.com/microsoft/vcpkg#quick-start-windows and then install the dependencies needed using `vcpkg install apr apr-util`. Command-line utilities(zip, grep, sed) are available in the Git for Windows distribution (C:/Program Files/Git/usr/bin/) or Msys2 can be downloaded from: https://www.msys2.org/ and by default will be installed under C:/msys2/bin. Unless you pass BUILD_TESTING=off, the location of command-line utilities must be provided to the Log4cxx cmake build in the LOG4CXX_TEST_PROGRAM_PATH cmake variable. 2. Building from source in %HOMEPATH%/Libraries. Use your browser to download source for Expat from github, APR and APR-Util from https://archive.apache.org/dist/apr/ and Log4cxx from https://dlcdn.apache.org/logging/log4cxx/1.3.0. Extract the source code into directories libexpat, apr-1.7.4, apr-util-1.6.3 and apache-log4cxx-1.3.0. ~~~ $ cd %HOMEPATH%/Libraries $ cmake -S libexpat/expat -B buildtrees/expat -DCMAKE_INSTALL_PREFIX=%HOMEPATH%/Libraries/installed $ cmake --build buildtrees/expat --target install --config Release $ cmake -S apr-1.7.4 -B buildtrees/apr -DCMAKE_INSTALL_PREFIX=%HOMEPATH%/Libraries/installed $ cmake --build buildtrees/apr --target install --config Release $ set CMAKE_PREFIX_PATH=%HOMEPATH%/Libraries/installed $ cmake -S apr-util-1.6.3 -B buildtrees/apr-util -DCMAKE_INSTALL_PREFIX=%HOMEPATH%/Libraries/installed $ cmake --build buildtrees/apr-util --target install --config Release $ cmake -S apache-log4cxx-1.3.0 -B buildtrees/log4cxx -DCMAKE_INSTALL_PREFIX=%HOMEPATH%/Libraries/installed -DLOG4CXX_TEST_PROGRAM_PATH=C:/Program Files/Git/usr/bin $ cmake --build buildtrees/log4cxx --target install --config Release ~~~ ## Mac OS/X: APR and APR-Util are provided by the platform in Mac OS/X 10.5 and iODBC in 10.4. cmake can be installed by typing "brew install cmake". CMake can be built from source by typing: ~~~ $ wget https://github.com/Kitware/CMake/releases/download/v3.27.2/cmake-3.27.2.tar.gz $ tar xf cmake-3.27.2.tar.gz $ cd cmake-3.27.2 $ ./bootstrap $ make $ sudo make install ~~~ ## FreeBSD: APR, APR-Util, gzip and zip may be installed from the ports collection by: ~~~ $ cd /usr/ports/archivers/zip $ make $ make install $ cd /usr/ports/archivers/gzip $ make $ make install $ cd /usr/ports/devel/apr $ make $ make install ~~~ apache-log4cxx-1.3.1/src/site/markdown/development/dependencies.md0000644000175100001770000001021414721727031024541 0ustar runnerdockerLog4cxx Dependencies {#dependencies} === [TOC] As of version 0.12.0, Log4cxx requires a minimum C++ version of C++11. Log4cxx requires the following software to build and/or run correctly: |Dependency Name|Version|Dependency Type|Homepage| |---------------|-------|---------------|--------| |Apache Portable Runtime(APR)|>=1.5.4|Compile/Runtime|https://apr.apache.org |APR-Util |>=1.5.4|Compile/Runtime|https://apr.apache.org |gzip |any |Test/Runtime(optional)|https://gzip.org |sed |any |Test|N/A |zip |any |Test/Runtime(optional)|N/A ## APR+APR-Util The Apache Portable Runtime(APR) provides the cross-platform backend for log4cxx. Both APR and APR-util need to be installed and available on your system. ## sed+gzip+zip These applications are needed during test of log4cxx. `gzip`and `sed` are generally installed by default on Linux. `zip` may not be installed by default; check your distribution's documentation for information on how to install these applications. For Windows, you will have to install those tools through a system such as MinGW, cygwin, or MSYS2. `gzip` and `zip` only needed during runtime if you are compressing the log files, for example by setting a rollover policy which ends in `.gz` or `.zip`. # Optional Dependencies The following table lists CMake options that require additional dependencies. |CMake option |Dependency Name|Version| Dependency Type | Homepage| |---------------|---------------| :---: |---------------|--------| |LOG4CXX_MULTIPROCESS_ROLLING_FILE_APPENDER |Boost | any | Compile/runtime. Not required if your compiler supports C++17 | https://boost.org | |ENABLE_FMT_LAYOUT | {fmt} | 9+ | Compile/runtime | https://github.com/fmtlib/fmt | |LOG4CXX_ENABLE_ODBC | unixodbc | any | Compile/runtime (not on Windows) | https://www.unixodbc.org/ | |LOG4CXX_ENABLE_ESMTP | libesmtp | any | Compile/runtime (not on Windows) | https://github.com/libesmtp/libESMTP | |LOG4CXX_QT_SUPPORT |Qt | 5 | Compile/runtime | https://www.qt.io/download | |LOG4CXX_CFSTRING | Mac OS/X Core Foundation | any | Compile/runtime | https://developer.apple.com/documentation/corefoundation | ## A note on C++ version and Boost By default, Log4cxx requests C++20 features. This is to avoid 3rd party dependencies as much as possible. If C++17 is not available, a search for Boost will be taken and those libraries will be used instead. If you would prefer to use Boost, there are two options you have: 1. Pass `-DPREFER_BOOST=ON` to CMake when compiling. This will ignore the results of the tests that check for the standard version of components that are required. Note that this will switch all components, regardless of the C++ version in effect at compile time. 2. Revert to an earlier standard using `-DCMAKE_CXX_STANDARD=11` for example. This will still to check for standard versions of required components, but it will fall back to using Boost for newer components added in C++17. # Licenses(direct dependencies only) | Dependency | License | |------------|---------| | APR, APR-util | **Apache License, Version 2.0** | | Boost | **Boost License, Version 1.0** | | {fmt} | **MIT** | | unixodbc | **LGPL** | | libesmtp | **LGPL** | | Qt | Refer https://www.qt.io/licensing/ | | Mac OS/X Core Foundation | **APSL 2.0** |apache-log4cxx-1.3.1/src/site/markdown/development/source-repository.md0000644000175100001770000000304214721727031025631 0ustar runnerdockerSource Repository {#source-repository} === # Overview Log4cxx uses GIT to manage its source code. Instructions on GIT use can be found at http://git-scm.com/documentation. ## Web Access The default repository can be seen on gitbox at: * https://gitbox.apache.org/repos/asf?p=logging-log4cxx.git This repository is mirrored to GitHub at the following location: * https://github.com/apache/logging-log4cxx ## Anonymous access The source can be checked out anonymously from GIT with this command (See http://git-scm.com/docs/git-clone): ~~~ $ git clone http://gitbox.apache.org/repos/asf/logging-log4cxx.git ~~~ ## Pull Requests Pull requests may be submitted through GitHub. apache-log4cxx-1.3.1/src/site/markdown/development/build-vcpkg.md0000644000175100001770000000276114721727031024332 0ustar runnerdockerBuilding with vcpkg {#build-vcpkg} === Log4cxx is included with Microsoft vcpkg, and can thus be easily installed. This is a quick guide to show you how to do that. ## Preparation Windows: ~~~ > git clone https://github.com/Microsoft/vcpkg.git > cd vcpkg > .\bootstrap-vcpkg.bat # Then, to hook up user-wide integration, run (note: requires admin on first use) > .\vcpkg integrate install ~~~ Linux: ~~~ $ git clone https://github.com/Microsoft/vcpkg.git $ cd vcpkg $ ./bootstrap-vcpkg.sh $ ./vcpkg integrate install ~~~ ## Building log4cxx.dll Windows: ~~~ PS> .\vcpkg install log4cxx ~~~ Linux: ~~~ $ ./vcpkg install log4cxx ~~~ apache-log4cxx-1.3.1/src/site/markdown/development/supported-systems.md0000644000175100001770000000236614721727031025656 0ustar runnerdockerTesting coverage {#supported-systems} === These Github provided environments are used in continuous integration and unit testing: * Windows - Visual Studio 2019 and 2022 * Ubuntu 20.04 - GNU g++ 9.4.0, Clang 11.0.0 * Ubuntu 22.04 - GNU g++ 11.4.0, Clang 14.0.0 * MacOS 13 - AppleClang 15.0 * MacOS 14 - AppleClang 15.0 * Msys2 - ucrt-x86_64/mingw-x86_64, GNU g++ 14.2.0 and Clang 18.1.8 apache-log4cxx-1.3.1/src/site/markdown/development/fuzzing.md0000644000175100001770000000751414721727031023620 0ustar runnerdockerFuzzing {#fuzzing} === [TOC] Log4cxx contains fuzz tests implemented using [LibFuzzer](https://llvm.org/docs/LibFuzzer.html#dictionaries). These tests are located in the `src/fuzzers` directory. ## Google OSS-Fuzz {#oss-fuzz} [OSS-Fuzz](https://github.com/google/oss-fuzz) is a Google service that continuously runs fuzz tests of critical F/OSS projects on a beefy cluster and reports its findings (bugs, vulnerabilities, etc.) privately to project maintainers. Log4cxx provides OSS-Fuzz integration with following helpers: - [Dockerfile](https://github.com/google/oss-fuzz/tree/master/projects/log4cxx/Dockerfile) to create a container image for running tests - `oss-fuzz-build.sh` to generate fuzz test runner scripts along with all necessary dependencies ## Running tests locally {#running} 1. Clone the OSS-Fuzz repository: ~~~~ git clone --depth 1 https://github.com/google/oss-fuzz google-oss-fuzz && cd $_ ~~~~ 1. Build the container image: ~~~~ python infra/helper.py build_image apache-logging-log4cxx ~~~~ 1. Run the container image to build the Log4cxx project and generate runner scripts along with dependencies: ~~~~ python infra/helper.py build_fuzzers \ --sanitizer address --engine libfuzzer --architecture x86_64 \ apache-logging-log4cxx ~~~~ 1. List generated runner scripts: ~~~~ ls -al build/out/apache-logging-log4cxx ~~~~ 1. Check one of the generated runner scripts: ~~~~ python infra/helper.py check_build \ --sanitizer address --engine libfuzzer --architecture x86_64 \ apache-logging-log4cxx PatternLayoutFuzzer ~~~~ 1. Execute one of the generated runner scripts: ~~~~ python infra/helper.py run_fuzzer \ --sanitizer address --engine libfuzzer --architecture x86_64 \ apache-logging-log4cxx PatternLayoutFuzzer ~~~~ ## Viewing fuzzing failures detected by OSS-Fuzz {#view} The system running fuzzers registered to OSS-Fuzz is called **ClusterFuzz**, which provides [a web interface](https://oss-fuzz.com) for maintainers to monitor the fuzzing results. Tests outputs and [reproduction](#reproduce) inputs for failed tests are stored in [a Google Cloud Storage bucket](https://console.cloud.google.com/storage/browser/apache-logging-log4cxx-logs.clusterfuzz-external.appspot.com). Access to both the web interface and the bucket is restricted, and only allowed to [those configured for the project](https://github.com/google/oss-fuzz/blob/master/projects/apache-logging-log4cxx/project.yaml). ## Reproducing fuzzing failures detected by OSS-Fuzz {#reproduce} Download the associated `.testcase` file from [the Google Cloud Storage bucket](https://console.cloud.google.com/storage/browser/apache-logging-log4cxx-logs.clusterfuzz-external.appspot.com), and run the following command: ~~~~ python infra/helper.py reproduce \ apache-logging-log4cxx ~~~~ Refer to https://google.github.io/oss-fuzz/advanced-topics/reproducing/[the related OSS-Fuzz documentation] for details. apache-log4cxx-1.3.1/src/site/markdown/community.md0000644000175100001770000000472414721727031021626 0ustar runnerdockerCommunity {#community} === # Getting help {#support} If you are using an older version, search the [change log], [JIRA] and [mailing list archives] to determine whether your problem has been fixed some time ago. If you already digged through the code and found a problem in the Log4cxx implementation or the Log4cxx build scripts, feel free to directly raise an issue in [Github Issues]. *Please don't just open bugs only because things don't work for you*, some issues simply aren't bugs in the code base of the project or it's build tools, but may have a lot of different other reasons. If things really only don't work and you don't have any clue why, please use the [official support channels], i.e., [usage mailing list](mailto:log4cxx-user@logging.apache.org), [developer mailing lists](mailto:log4cxx-dev@logging.apache.org) or [GitHub Discussions] instead. # Reporting a security issue {#security} Refer to the [official security page] for how to get support on security issues. # Official releases {#artifacts} See [artifact locations] for where you can get offical release artifacts and how to verify them. [change log]:@ref changelog [JIRA]: https://issues.apache.org/jira/browse/LOGCXX [mailing list archives]: http://mail-archives.apache.org/mod_mbox/logging-log4cxx-user [Github Issues]: https://github.com/apache/logging-log4cxx/issues [GitHub Discussions]: https://github.com/apache/logging-log4cxx/discussions [official support channels]: https://logging.apache.org/support.html [official security page]: https://logging.apache.org/security.html [artifact locations]: https://logging.apache.org/download.html apache-log4cxx-1.3.1/src/site/markdown/change-report-gh.md0000644000175100001770000032610214721727031022731 0ustar runnerdockerChange Log {#changelog} === ## Release History {#history} | Version | Date | Description | | ------------------- | ---------- | -------------------- | | [1.3.1](#rel_1_3_1) | 2024-11-XX | Bugfix release | | [1.3.0](#rel_1_3_0) | 2024-10-21 | Maintenance release | | [1.2.0](#rel_1_2_0) | 2024-01-01 | Maintenance release | | [1.1.0](#rel_1_1_0) | 2023-05-01 | General bugfix release | | [1.0.0](#rel_1_0_0) | 2023-01-01 | Major release to standardize the library and make it ABI stable | | [0.13.0](#rel_13_0) | 2022-04-15 | Maintenance release | | [0.12.1](#rel_12_1) | 2021-09-21 | Bugfix for 0.12.0 | | [0.12.0](#rel_12_0) | 2021-05-01 | First release to require C++11. Updates for smart pointers. Standardization on CMake for building. | | [0.11.0](#rel_11_0) | 2020-08-09 | Maintenance release. | | [0.10.0](#rel_10_0) | 2008-04-03 | First Apache release | | [0.9.7](#rel_9_7) | 2004-05-10 | | | [0.9.6](#rel_9_6) | 2004-04-11 | | | [0.9.5](#rel_9_5) | 2004-02-04 | | | [0.9.4](#rel_9_4) | 2003-10-25 | | | [0.9.3](#rel_9_3) | 2003-09-19 | | | [0.9.2](#rel_9_2) | 2003-08-10 | | | [0.9.1](#rel_9_1) | 2003-08-06 | | | [0.9.0](#rel_9_0) | 2003-08-06 | | | [0.1.1](#rel_1_1) | 2003-07-09 | | | [0.1.0](#rel_1_0) | 2003-07-08 | | | [0.0.1](#rel_0_1) | 2003-05-31 | | ## Release 1.3.1 - 2024-11-XX {#rel_1_3_1} This is a minor bugfix release to fix issues found with 1.3.0. ### Bug {#rel_1_3_1_bugs} * Properly prevent undefined behaviour when an appender is deleted without being closed \[[#431](https://github.com/apache/logging-log4cxx/pull/431)\] * Prevent abnormal termination on exit when using a static NDC/MDC variable \[[#426](https://github.com/apache/logging-log4cxx/pull/426)\] * Support for std::experimental::optional (in the standard library used by gcc 5.4) \[[#419](https://github.com/apache/logging-log4cxx/pull/419)\] ## Release 1.3.0 - 2024-10-21 {#rel_1_3_0} Release 1.3.0 includes the following new features: * Overhead reduction of upto 60% sending logging events to an appender * Statistics on the AsyncAppender's queue length (in Log4cxx debug output) * [Fuzz tests](@ref fuzzing) along with [Google OSS-Fuzz](https://github.com/google/oss-fuzz) integration The following issues have been addressed: * MSYS2/MINGW build errors \[[#389](https://github.com/apache/logging-log4cxx/pull/389)\] * `thread_local` problems in MSYS2/MINGW \[[#394](https://github.com/apache/logging-log4cxx/pull/394)\] * A potential 'use after free' fault when using AsyncAppender \[[#397](https://github.com/apache/logging-log4cxx/pull/397)\] ## Release 1.2.0 - 2024-01-01 {#rel_1_2_0} The following issues have been addressed: * The `locale` external character encoding option reverting to US-ASCII \[[LOGCXX-483](https://issues.apache.org/jira/browse/LOGCXX-483)\] * A segfault during process exit when log4cxx::LogManager::shutdown is not called \[[#268](https://github.com/apache/logging-log4cxx/pull/268)\] \[[#219](https://github.com/apache/logging-log4cxx/pull/219)\] * The cmake option to include a MultiprocessRollingFileAppender did not work * Build failure in a MSYS2 environment * Format settings (e.g. std::hex) were retained across LOG4CXX_XXXXX macro logging requests * When the APR library was built without support for threads (APR_HAS_THREADS=0): * the AsyncAppender and dynamically loaded configuration changes were not available * a single nested/mapped diagnostic context (NDC/MDC) would be used and updated (without synchronization) * On Windows, GetThreadDescription() called for each logging event when the thread name was empty \[[#321](https://github.com/apache/logging-log4cxx/pull/321)\] Release 1.2.0 includes the following new features: * LOG4CXX_XXXX macros now support logging of QStrings directly * log4cxx::hexdump function that returns a string of hexadecimal byte values * Ability to remove a HierarchyEventListener \[[#233](https://github.com/apache/logging-log4cxx/issues/233)\] * Less string copying when sending a logging event to an appender * Less frequent mutex contention when logging from multiple threads concurrently \[[#320](https://github.com/apache/logging-log4cxx/pull/320)\] * Allow thread information to be included in JSON formatted output * Optional support for logging during process termination \[[#271](https://github.com/apache/logging-log4cxx/pull/271)\] * A cmake option to place Log4cxx functions in a different namespace \[[#277](https://github.com/apache/logging-log4cxx/pull/277)\] * Optionally use std::format in LOG4CXX_XXXX_FMT macros instead of fmt::format \[[#291](https://github.com/apache/logging-log4cxx/pull/291)\] * Support for per object enabling/disabling of logging requests (see log4cxx::LoggerInstancePtr) Note: the `LOG4CXX_CHARSET` cmake option (external character encoding) default value has changed to `utf-8` ## Release 1.1.0 - 2023-05-01 {#rel_1_1_0} This is a general maintenance release. The following bugs/issues have been fixed: * Fix [CVE-2023-31038](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2023-31038) * Fix to build on Windows Server 2016 * Fix compiling errors with older compilers * Make ODBC and SMTP opt-in instead of automatic * Parameterize statements for ODBC inserts. Add new generic DBAppender class that uses APR for database support * Fix Qt support ## Release 1.0.0 - 2023-01-01 {#rel_1_0_0} This is a major release that fixes a number of long-standing issues and is desinged to make Log4cxx ABI stable moving forward. A few notes on this version: * Removed log4j style Java serialization. Due to Java's inherent problems with serialization, and the fact that Chainsaw no longer supports it, it has been completely removed. * A number of obsolete classes have been removed * Removal of TTCCLayout. If you still want this layout, use a PatternLayout with a format similar to the following: `%%r [%%t] %-5p - %%m%%n` * Removal of DateLayout. Use PatternLayout instead. * Classes now use an internal private class to store member variables in order to make them ABI stable * Multiprocess support is available, but Log4cxx must be explicitly compiled with this option Full release notes are below: ### Bug {#rel_1_0_0_bugs} - \[[LOGCXX-432](https://issues.apache.org/jira/browse/LOGCXX-432)\] - AsyncAppender automatically switches to sync mode when e.g. there is no disk space available - \[[LOGCXX-451](https://issues.apache.org/jira/browse/LOGCXX-451)\] - Application hang up during exit on Windows - \[[LOGCXX-491](https://issues.apache.org/jira/browse/LOGCXX-491)\] - SizeBasedRollingTest cases fail when defining LOG4CXX\_MULTI\_PROCESS - \[[LOGCXX-563](https://issues.apache.org/jira/browse/LOGCXX-563)\] - Fix memory leaks ### New Feature {#rel_1_0_0_features} - \[[LOGCXX-514](https://issues.apache.org/jira/browse/LOGCXX-514)\] - Create a libfmt layout - \[[LOGCXX-518](https://issues.apache.org/jira/browse/LOGCXX-518)\] - Refactor the multi process code of RollingFileAppender - \[[LOGCXX-559](https://issues.apache.org/jira/browse/LOGCXX-559)\] - Implement LocationInfoFilter ### Improvement {#rel_1_0_0_improvements} - \[[LOGCXX-516](https://issues.apache.org/jira/browse/LOGCXX-516)\] - Make classes ABI-stable - \[[LOGCXX-524](https://issues.apache.org/jira/browse/LOGCXX-524)\] - Remove silent exceptions - \[[LOGCXX-527](https://issues.apache.org/jira/browse/LOGCXX-527)\] - Mock the clock for tests - \[[LOGCXX-542](https://issues.apache.org/jira/browse/LOGCXX-542)\] - Remove log4j serialization - \[[LOGCXX-549](https://issues.apache.org/jira/browse/LOGCXX-549)\] - Make networking classes independent of implementation - \[[LOGCXX-557](https://issues.apache.org/jira/browse/LOGCXX-557)\] - Keep track of all appenders even if unused - \[[LOGCXX-558](https://issues.apache.org/jira/browse/LOGCXX-558)\] - Prevent MSVC compilation warnings \"needs to have dll-interface\" - \[[LOGCXX-564](https://issues.apache.org/jira/browse/LOGCXX-564)\] - Put typedefs into log4cxx namespace - \[[LOGCXX-566](https://issues.apache.org/jira/browse/LOGCXX-566)\] - Configurable output colors for log messages - \[[LOGCXX-567](https://issues.apache.org/jira/browse/LOGCXX-567)\] - Investigate backtrace support - \[[LOGCXX-568](https://issues.apache.org/jira/browse/LOGCXX-568)\] - Cleaunup files if rollover fails - \[[LOGCXX-570](https://issues.apache.org/jira/browse/LOGCXX-570)\] - Remove ObjectOutputStream - \[[LOGCXX-571](https://issues.apache.org/jira/browse/LOGCXX-571)\] - Better document \'runtime\' env vars and macros - \[[LOGCXX-572](https://issues.apache.org/jira/browse/LOGCXX-572)\] - Add support to re-read configuration files to Qt support - \[[LOGCXX-573](https://issues.apache.org/jira/browse/LOGCXX-573)\] - Provide feedback when configuring log4cxx - \[[LOGCXX-574](https://issues.apache.org/jira/browse/LOGCXX-574)\] - Provide a list of directories/filenames to try to configure ## Release 0.13.0 - 2022-04-15 {#rel_13_0} This release fixes a number of issues. Notable new features include the ability to block signals from threads that the library creates, automatic creation of log directories, new color patterns, and the ability to determine the library version at compile and run-time. ### Bug {#rel_13_0_bugs} - \[[LOGCXX-102](https://issues.apache.org/jira/browse/LOGCXX-102)\] - PropertyConfigurator does not process the RollingFileAppender options - \[[LOGCXX-387](https://issues.apache.org/jira/browse/LOGCXX-387)\] - SocketAppenderSkeleton re-connects only once - \[[LOGCXX-431](https://issues.apache.org/jira/browse/LOGCXX-431)\] - When log4cxx creates a thread, it doesn\'t block signals it\'s not using, leading to unreliable signal delivery for the calling process. - \[[LOGCXX-519](https://issues.apache.org/jira/browse/LOGCXX-519)\] - Version11 - \"INSTALL.TXT\" and \"vstudio.apt\" miss explenation for generating the log4cxx.dll - \[[LOGCXX-525](https://issues.apache.org/jira/browse/LOGCXX-525)\] - Compressing log files does not create directories - \[[LOGCXX-536](https://issues.apache.org/jira/browse/LOGCXX-536)\] - CMakeLists.txt install pgkconfig and cmake modue to wrong place - \[[LOGCXX-537](https://issues.apache.org/jira/browse/LOGCXX-537)\] - double mutex lock - \[[LOGCXX-540](https://issues.apache.org/jira/browse/LOGCXX-540)\] - propertiestestcase.properties contains CRLF, does not well play with git - \[[LOGCXX-543](https://issues.apache.org/jira/browse/LOGCXX-543)\] - Some tests can fail when there is a \"Q\" in the pathname - \[[LOGCXX-546](https://issues.apache.org/jira/browse/LOGCXX-546)\] - Multi threaded applications run at single threaded speed ### New Feature {#rel_13_0_features} - \[[LOGCXX-529](https://issues.apache.org/jira/browse/LOGCXX-529)\] - Support color and highlight conversion patterns ### Improvement {#rel_13_0_improvements} - \[[LOGCXX-337](https://issues.apache.org/jira/browse/LOGCXX-337)\] - Suggested fix for socketappender not reconnecting multiple times - \[[LOGCXX-538](https://issues.apache.org/jira/browse/LOGCXX-538)\] - Tests cannot be run in parallel - \[[LOGCXX-539](https://issues.apache.org/jira/browse/LOGCXX-539)\] - Allow distribustion log4j to be used for socketservertest - \[[LOGCXX-547](https://issues.apache.org/jira/browse/LOGCXX-547)\] - Allow for hiding of location data - \[[LOGCXX-548](https://issues.apache.org/jira/browse/LOGCXX-548)\] - Doxygen documentation is not reproducible - \[[LOGCXX-550](https://issues.apache.org/jira/browse/LOGCXX-550)\] - Add ability to get thread name not just ID ### Wish {#rel_13_0_wish_list} - \[[LOGCXX-544](https://issues.apache.org/jira/browse/LOGCXX-544)\] - Please embedd library version in a header - \[[LOGCXX-551](https://issues.apache.org/jira/browse/LOGCXX-551)\] - CMake documented build option for Boost vs C++17 Implementation for shared\_mutex ## Release 0.12.1 - 2021-09-21 {#rel_12_1} This is a minor bugfix release to fix issues found with 0.12.0. Notably, this version fixes a bug where a multithreaded application would crash when using a rolling file. ### Bug {#rel_12_1_bugs} - \[[LOGCXX-534](https://issues.apache.org/jira/browse/LOGCXX-534)\] - Crashed in log->forcedLog function when running with multi-thread - \[[LOGCXX-528](https://issues.apache.org/jira/browse/LOGCXX-528)\] - log4cxx fails to build on Centos 7.6 / g++ 4.8.5 / Boost 1.53 ## Release 0.12.0 - 2021-05-01 {#rel_12_0} This is the first release to require a minimum version of C++11. This means that all objects in log4cxx are now created using `std::shared_ptr` as the smart pointer implementation. Alternative build systems have been removed, and we now support CMake only for building the library. With the introduction of smart pointers, the old behavior of implicit casting no longer works. In order to cast between classes, use the new [log4cxx::cast](@ref log4cxx.cast) method. This method returns an invalid `shared_ptr` on failure, or a `shared_ptr` pointing at the same object on success. This should be transparent to user code, unless you are interacting with log4cxx internals directly. Before: ```{.cpp} ObjectPtr instance = Loader::loadClass(className).newInstance(); AppenderPtr appender = instance; ``` After: ```{.cpp} ObjectPtr instance = ObjectPtr(Loader::loadClass(className).newInstance()); AppenderPtr appender = log4cxx::cast(instance); // At this point(assuming the cast was good), instance and appender // both point at the same object. ``` ### Bug {#rel_12_0_bugs} - \[[LOGCXX-322](https://issues.apache.org/jira/browse/LOGCXX-322)\] - Crashes on exit from multithreaded program using log4cxx - \[[LOGCXX-485](https://issues.apache.org/jira/browse/LOGCXX-485)\] - Levels leak memory - \[[LOGCXX-486](https://issues.apache.org/jira/browse/LOGCXX-486)\] - Replace ObjectPtr with more standard shared\_ptr. - \[[LOGCXX-507](https://issues.apache.org/jira/browse/LOGCXX-507)\] - Data race on LevelPtr when using the async appender - \[[LOGCXX-508](https://issues.apache.org/jira/browse/LOGCXX-508)\] - sync - \[[LOGCXX-510](https://issues.apache.org/jira/browse/LOGCXX-510)\] - Build problems using CMAKE and Visual Studio 2019 Community - \[[LOGCXX-517](https://issues.apache.org/jira/browse/LOGCXX-517)\] - Circular reference in ErrorHandlerTestCase - \[[LOGCXX-521](https://issues.apache.org/jira/browse/LOGCXX-521)\] - Can\'t link cleanly with ODBC - \[[LOGCXX-526](https://issues.apache.org/jira/browse/LOGCXX-526)\] - GCC-11.1.0 Support ### New Feature {#rel_12_0_features} - \[[LOGCXX-515](https://issues.apache.org/jira/browse/LOGCXX-515)\] - Add macros to utilize libfmt formatting for messages - \[[LOGCXX-523](https://issues.apache.org/jira/browse/LOGCXX-523)\] - Add in error handling for rollover errors ## Release 0.11.0 - 2020-08-09 {#rel_11_0} | | | | | ------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -- | | Type | Changes | By | | ![](images/fix.gif "fix") | cmake and autotools generate different versioned binaries Fixes [LOGCXX-512](https://issues.apache.org/jira/browse/LOGCXX-512). | | | ![](images/fix.gif "fix") | CachedDateFormat reuses timestamps without updating milliseconds after formatting timestamp with ms == 654 Fixes [LOGCXX-506](https://issues.apache.org/jira/browse/LOGCXX-506). | | | ![](images/update.gif "update") | Checksums/Signatures don't match for log4cxx binaries Fixes [LOGCXX-503](https://issues.apache.org/jira/browse/LOGCXX-503). | | | ![](images/update.gif "update") | appenderattachable.h function doc formatted "incorrectly" Fixes [LOGCXX-502](https://issues.apache.org/jira/browse/LOGCXX-502). | | | ![](images/update.gif "update") | Logging in Timing-Critical Applications Fixes [LOGCXX-500](https://issues.apache.org/jira/browse/LOGCXX-500). | | | ![](images/fix.gif "fix") | Provide a windows build environment for the project by replacing the ant build with a CMake build Fixes [LOGCXX-494](https://issues.apache.org/jira/browse/LOGCXX-494). | | | ![](images/fix.gif "fix") | Wrong usage of milli- vs. micro- and non- vs. milliseconds in some docs. Fixes [LOGCXX-493](https://issues.apache.org/jira/browse/LOGCXX-493). | | | ![](images/fix.gif "fix") | conditional expression is constant Fixes [LOGCXX-490](https://issues.apache.org/jira/browse/LOGCXX-490). | | | ![](images/fix.gif "fix") | Space after log level hides messages Fixes [LOGCXX-488](https://issues.apache.org/jira/browse/LOGCXX-488). | | | ![](images/fix.gif "fix") | Spelling error s/excute/execute Fixes [LOGCXX-484](https://issues.apache.org/jira/browse/LOGCXX-484). | | | ![](images/update.gif "update") | Not able to see hebrew values when logging in log4cxx Fixes [LOGCXX-483](https://issues.apache.org/jira/browse/LOGCXX-483). | | | ![](images/fix.gif "fix") | Build failure with GCC-6 Fixes [LOGCXX-482](https://issues.apache.org/jira/browse/LOGCXX-482). | | | ![](images/fix.gif "fix") | TimeBasedRollingPolicy should append as configured on rollover Fixes [LOGCXX-464](https://issues.apache.org/jira/browse/LOGCXX-464). | | | ![](images/fix.gif "fix") | LogLog::setQuietMode(true) does not suppress exception reporting Fixes [LOGCXX-455](https://issues.apache.org/jira/browse/LOGCXX-455). | | | ![](images/fix.gif "fix") | make install fails, trying to overwrite header files Fixes [LOGCXX-446](https://issues.apache.org/jira/browse/LOGCXX-446). | | | ![](images/fix.gif "fix") | Return by const reference in Logger::getName() Fixes [LOGCXX-443](https://issues.apache.org/jira/browse/LOGCXX-443). | | | ![](images/fix.gif "fix") | Autoconf 2.69 needs 'ACLOCAL\_AMFLAGS= -I .' Fixes [LOGCXX-433](https://issues.apache.org/jira/browse/LOGCXX-433). | | | ![](images/fix.gif "fix") | Wildcards in Makefile.am break either VPATH or non-VPATH installs Fixes [LOGCXX-428](https://issues.apache.org/jira/browse/LOGCXX-428). | | | ![](images/fix.gif "fix") | exceptions in CachedDateFormatTestCase after LOGCXX-420 Fixes [LOGCXX-425](https://issues.apache.org/jira/browse/LOGCXX-425). | | | ![](images/fix.gif "fix") | liblog4cxx.pc.in should reflect dependency on apr-1, apr-1-util Fixes [LOGCXX-424](https://issues.apache.org/jira/browse/LOGCXX-424). | | | ![](images/fix.gif "fix") | Repair autogen script warnings Fixes [LOGCXX-423](https://issues.apache.org/jira/browse/LOGCXX-423). | | | ![](images/fix.gif "fix") | Regression of LOGCXX-420 Fixes [LOGCXX-422](https://issues.apache.org/jira/browse/LOGCXX-422). | | | ![](images/fix.gif "fix") | Possible out\_of\_range exception for millisecond formats in CachedDateFormat Fixes [LOGCXX-420](https://issues.apache.org/jira/browse/LOGCXX-420). | | | ![](images/fix.gif "fix") | atoi undefined on Mac OS 10.9 compiling stringhelper.cpp Fixes [LOGCXX-417](https://issues.apache.org/jira/browse/LOGCXX-417). | | | ![](images/fix.gif "fix") | Configure and watch could crash on app exit with static linking Fixes [LOGCXX-416](https://issues.apache.org/jira/browse/LOGCXX-416). | | | ![](images/fix.gif "fix") | Empty XML configuration file causes crash Fixes [LOGCXX-415](https://issues.apache.org/jira/browse/LOGCXX-415). | | | ![](images/fix.gif "fix") | possibly wrong use of autotools docdir (due to Alex Zbarcea) Fixes [LOGCXX-414](https://issues.apache.org/jira/browse/LOGCXX-414). | | | ![](images/fix.gif "fix") | log4cxx doesn't compile on openembedded (due to Alex Zbarcea) Fixes [LOGCXX-413](https://issues.apache.org/jira/browse/LOGCXX-413). | | | ![](images/fix.gif "fix") | Log4cxx doesn't roll normally when working under multiple processes environment Fixes [LOGCXX-412](https://issues.apache.org/jira/browse/LOGCXX-412). | | | ![](images/fix.gif "fix") | Crash when logging on multiple threads. Fixes [LOGCXX-411](https://issues.apache.org/jira/browse/LOGCXX-411). | | | ![](images/fix.gif "fix") | C++11 does not allow char literals with highest bit set unless cast Fixes [LOGCXX-400](https://issues.apache.org/jira/browse/LOGCXX-400). | | | ![](images/fix.gif "fix") | Non-ascii character output wrong. Fixes [LOGCXX-399](https://issues.apache.org/jira/browse/LOGCXX-399). | | | ![](images/fix.gif "fix") | Infinite loop in Transcoder::encode(const LogString& src, std::wstring& dst) Fixes [LOGCXX-398](https://issues.apache.org/jira/browse/LOGCXX-398). | | | ![](images/fix.gif "fix") | Levels are not thread safe Fixes [LOGCXX-394](https://issues.apache.org/jira/browse/LOGCXX-394). | | | ![](images/fix.gif "fix") | Hierarchy::updateParents loops forever on illegal logger-name like '.logger1' Fixes [LOGCXX-388](https://issues.apache.org/jira/browse/LOGCXX-388). | | | ![](images/fix.gif "fix") | Mingw build type conversion error Fixes [LOGCXX-382](https://issues.apache.org/jira/browse/LOGCXX-382). | | | ![](images/fix.gif "fix") | Pkgconfig can't find dependencies properly if log4cxx built statically Fixes [LOGCXX-381](https://issues.apache.org/jira/browse/LOGCXX-381). | | | ![](images/fix.gif "fix") | Load Properties File Fails When There Are multibyte Characters in the Path Fixes [LOGCXX-369](https://issues.apache.org/jira/browse/LOGCXX-369). | | | ![](images/fix.gif "fix") | method and class name functions not properly implemented Fixes [LOGCXX-368](https://issues.apache.org/jira/browse/LOGCXX-368). | | | ![](images/fix.gif "fix") | Build fails on Linux with g++ 4.4 Fixes [LOGCXX-367](https://issues.apache.org/jira/browse/LOGCXX-367). | | | ![](images/fix.gif "fix") | Errors when compile log4cxx 0.10.0 under Win7 x64 with Visual Studio 2010 (due to Christian Boos and Feng Nan) Fixes [LOGCXX-366](https://issues.apache.org/jira/browse/LOGCXX-366). | | | ![](images/fix.gif "fix") | Unit tests fail on system dates later than 2009-12-31. Fixes [LOGCXX-365](https://issues.apache.org/jira/browse/LOGCXX-365). | | | ![](images/fix.gif "fix") | SMTPAppender generating Emails with an empty body Fixes [LOGCXX-358](https://issues.apache.org/jira/browse/LOGCXX-358). | | | ![](images/fix.gif "fix") | apache-log4cxx-0.10.0\\src\\main\\include\\log4cxx\\spi\\configurator.h(57) : warning C4231: nonstandard extension used : 'extern' before template explicit instantiation Fixes [LOGCXX-356](https://issues.apache.org/jira/browse/LOGCXX-356). | | | ![](images/fix.gif "fix") | When a client disconnects the SocketHubAppender crashes on the next log message Fixes [LOGCXX-353](https://issues.apache.org/jira/browse/LOGCXX-353). | | | ![](images/fix.gif "fix") | Download page does not have link to KEYS file Fixes [LOGCXX-351](https://issues.apache.org/jira/browse/LOGCXX-351). | | | ![](images/fix.gif "fix") | Transcoder::encodeCharsetName bungles encoding Fixes [LOGCXX-340](https://issues.apache.org/jira/browse/LOGCXX-340). | | | ![](images/update.gif "update") | Child thread does not inherit a copy of the mapped diagnostic context of its parent Fixes [LOGCXX-339](https://issues.apache.org/jira/browse/LOGCXX-339). | | | ![](images/fix.gif "fix") | Suggested fix for socketappender not reconnecting multiple times Fixes [LOGCXX-337](https://issues.apache.org/jira/browse/LOGCXX-337). | | | ![](images/fix.gif "fix") | Test compilation fails: Overloading ambiguity Fixes [LOGCXX-336](https://issues.apache.org/jira/browse/LOGCXX-336). | | | ![](images/fix.gif "fix") | DailyRollingFileAppender should roll if program doesn't run at rolling time Fixes [LOGCXX-331](https://issues.apache.org/jira/browse/LOGCXX-331). | | | ![](images/fix.gif "fix") | TLS memory of APR is not freed in destructor of APRInitializer Fixes [LOGCXX-320](https://issues.apache.org/jira/browse/LOGCXX-320). | | | ![](images/fix.gif "fix") | Please make sure that the LOG4CXX\_\* macro's can be used as ordinary statements. Fixes [LOGCXX-319](https://issues.apache.org/jira/browse/LOGCXX-319). | | | ![](images/fix.gif "fix") | Log4cxx triggers locking inversion which can result in a deadlock. Fixes [LOGCXX-317](https://issues.apache.org/jira/browse/LOGCXX-317). | | | ![](images/fix.gif "fix") | Build process fails in case of absence of iconv support in apr-util Fixes [LOGCXX-313](https://issues.apache.org/jira/browse/LOGCXX-313). | | | ![](images/fix.gif "fix") | Property/xml::DOMConfigurator::configureAndWatch can continue to run after APR termination Fixes [LOGCXX-305](https://issues.apache.org/jira/browse/LOGCXX-305). | | | ![](images/fix.gif "fix") | BasicConfigurator::configure results in writer not set warning. Fixes [LOGCXX-304](https://issues.apache.org/jira/browse/LOGCXX-304). | | | ![](images/fix.gif "fix") | DOMConfigurator does not set ErrorHandler. Fixes [LOGCXX-303](https://issues.apache.org/jira/browse/LOGCXX-303). | | | ![](images/fix.gif "fix") | ODBCAppender connection settings broken (or just have changed). Fixes [LOGCXX-300](https://issues.apache.org/jira/browse/LOGCXX-300). | | | ![](images/fix.gif "fix") | odbcappender.cpp does not compile with unixODBC on linux. Fixes [LOGCXX-299](https://issues.apache.org/jira/browse/LOGCXX-299). | | | ![](images/fix.gif "fix") | SMTPAppender does not build properly with autotools. Fixes [LOGCXX-298](https://issues.apache.org/jira/browse/LOGCXX-298). | | | ![](images/fix.gif "fix") | Escape sequences not recognized in property files. Fixes [LOGCXX-293](https://issues.apache.org/jira/browse/LOGCXX-293). | | | ![](images/fix.gif "fix") | Value continuation does not properly handle CRLF in property files. Fixes [LOGCXX-292](https://issues.apache.org/jira/browse/LOGCXX-292). | | | ![](images/fix.gif "fix") | Tab characters are not recognized in property files. Fixes [LOGCXX-291](https://issues.apache.org/jira/browse/LOGCXX-291). | | | ![](images/fix.gif "fix") | Unnecessary trailing semi-colons after LOG4CXX\_INFO et al in docs, examples and tests. Fixes [LOGCXX-288](https://issues.apache.org/jira/browse/LOGCXX-288). | | | ![](images/fix.gif "fix") | gcc 4.3 requires \#include \ when using memcpy and related. Fixes [LOGCXX-286](https://issues.apache.org/jira/browse/LOGCXX-286). | | | ![](images/fix.gif "fix") | LevelRangeFilter has default value for acceptOnMatch that is different from log4j Fixes [LOGCXX-285](https://issues.apache.org/jira/browse/LOGCXX-285). | | | ![](images/fix.gif "fix") | Unit tests fail to compile with xlc\_r on AIX Fixes [LOGCXX-284](https://issues.apache.org/jira/browse/LOGCXX-284). | | | ![](images/fix.gif "fix") | Suspicious, but harmless, reuse of LOCAL1 in SyslogAppender Fixes [LOGCXX-283](https://issues.apache.org/jira/browse/LOGCXX-283). | | | ![](images/fix.gif "fix") | Thread::sleep not affected by Thread::interrupt. Fixes [LOGCXX-282](https://issues.apache.org/jira/browse/LOGCXX-282). | | | ![](images/fix.gif "fix") | Sun Studio 11 reports function hides base virtual function warning Fixes [LOGCXX-281](https://issues.apache.org/jira/browse/LOGCXX-281). | | | ![](images/fix.gif "fix") | tests and sample code unnecessarily compiled during default make target Fixes [LOGCXX-280](https://issues.apache.org/jira/browse/LOGCXX-280). | | | ![](images/fix.gif "fix") | Threads for reconnecting sockets do not end cleanly when program exits Fixes [LOGCXX-278](https://issues.apache.org/jira/browse/LOGCXX-278). | | | ![](images/fix.gif "fix") | Reconnection not working for sockets Fixes [LOGCXX-277](https://issues.apache.org/jira/browse/LOGCXX-277). | | | ![](images/fix.gif "fix") | AndFilter and others defined but not implemented Fixes [LOGCXX-276](https://issues.apache.org/jira/browse/LOGCXX-276). | | | ![](images/fix.gif "fix") | Headers cannot be included with very strict warning settings Fixes [LOGCXX-275](https://issues.apache.org/jira/browse/LOGCXX-275). | | | ![](images/fix.gif "fix") | Prevent filenamepatterntestcase from failing in some timezones Fixes [LOGCXX-273](https://issues.apache.org/jira/browse/LOGCXX-273). | | | ![](images/update.gif "update") | Apache log4cxx 0.11.0 release Fixes [LOGCXX-272](https://issues.apache.org/jira/browse/LOGCXX-272). | | | ![](images/fix.gif "fix") | MDC::put will not overwrite existing key value pair Fixes [LOGCXX-271](https://issues.apache.org/jira/browse/LOGCXX-271). | | | ![](images/fix.gif "fix") | Add ability to compile out logging by logging level. Fixes [LOGCXX-270](https://issues.apache.org/jira/browse/LOGCXX-270). | | | ![](images/fix.gif "fix") | Local variables hide member variables Fixes [LOGCXX-267](https://issues.apache.org/jira/browse/LOGCXX-267). | | | ![](images/fix.gif "fix") | Eliminate Extra ";" ignored warnings Fixes [LOGCXX-266](https://issues.apache.org/jira/browse/LOGCXX-266). | | | ![](images/fix.gif "fix") | Eliminate anachronism warnings Fixes [LOGCXX-265](https://issues.apache.org/jira/browse/LOGCXX-265). | | | ![](images/fix.gif "fix") | Bad link to log4cxx-dev archive Fixes [LOGCXX-263](https://issues.apache.org/jira/browse/LOGCXX-263). | | | ![](images/fix.gif "fix") | socketappendertestcase and xmlsocketappendertestcase not run Fixes [LOGCXX-262](https://issues.apache.org/jira/browse/LOGCXX-262). | | | ![](images/fix.gif "fix") | Console appender crashes if layout is not set Fixes [LOGCXX-249](https://issues.apache.org/jira/browse/LOGCXX-249). | | | ![](images/add.gif "add") | Set SONAME in cmake like autotools based buildsystem would do. Fixes [32](https://github.com/apache/logging-log4cxx/pull/32). | | | ![](images/add.gif "add") | Implementation of map-based filter. Fixes [24](https://github.com/apache/logging-log4cxx/pull/24). | | | ![](images/add.gif "add") | Added support for building log4cxx as a statically linked library on Windows. Fixes [21](https://github.com/apache/logging-log4cxx/pull/21). | | | ![](images/add.gif "add") | Replaced ant build with cmake. Fixes [14](https://github.com/apache/logging-log4cxx/pull/14). | | | ![](images/add.gif "add") | JSONLayout Fixes [13](https://github.com/apache/logging-log4cxx/pull/13). | | | ![](images/update.gif "update") | Behavior of StringHelper::startsWith and endsWith synced. | | | ![](images/update.gif "update") | Documented C (class) and M (method) log format keywords. | | | ![](images/add.gif "add") | LocationInfo for Borland C++ Builder and successors improved. | | ## Release 0.10.0 - 2008-04-03 {#rel_10_0} | | | | | ------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -- | | Type | Changes | By | | ![](images/fix.gif "fix") | Several appenders fail to compile in Visual Studio 2008 Fixes [LOGCXX-259](https://issues.apache.org/jira/browse/LOGCXX-259). | | | ![](images/fix.gif "fix") | unable to build from make dist package due to missing doxygen file Fixes [LOGCXX-258](https://issues.apache.org/jira/browse/LOGCXX-258). | | | ![](images/fix.gif "fix") | ServerSocket::accept hangs on Unix Fixes [LOGCXX-257](https://issues.apache.org/jira/browse/LOGCXX-257). | | | ![](images/fix.gif "fix") | SocketHubAppender fails after accepting connection Fixes [LOGCXX-256](https://issues.apache.org/jira/browse/LOGCXX-256). | | | ![](images/add.gif "add") | Add build option for static C RTL Fixes [LOGCXX-254](https://issues.apache.org/jira/browse/LOGCXX-254). | | | ![](images/fix.gif "fix") | Transcoder compilation error with utf-8 charset Fixes [LOGCXX-253](https://issues.apache.org/jira/browse/LOGCXX-253). | | | ![](images/add.gif "add") | Add documentation for use of operator\<\< in logging requests Fixes [LOGCXX-252](https://issues.apache.org/jira/browse/LOGCXX-252). | | | ![](images/fix.gif "fix") | NDC::cloneStack and NDC::inherit missing in 0.10.0 RC2 Fixes [LOGCXX-251](https://issues.apache.org/jira/browse/LOGCXX-251). | | | ![](images/fix.gif "fix") | ODBCAppender has unicode issues Fixes [LOGCXX-248](https://issues.apache.org/jira/browse/LOGCXX-248). | | | ![](images/fix.gif "fix") | MSVC project has wrong additional include directories Fixes [LOGCXX-247](https://issues.apache.org/jira/browse/LOGCXX-247). | | | ![](images/fix.gif "fix") | Config refresh hangs a client application that uses TelnetAppender Fixes [LOGCXX-246](https://issues.apache.org/jira/browse/LOGCXX-246). | | | ![](images/fix.gif "fix") | Problem Compile in Doxy Fixes [LOGCXX-243](https://issues.apache.org/jira/browse/LOGCXX-243). | | | ![](images/update.gif "update") | Eliminate log4cxx proxies for APR types Fixes [LOGCXX-242](https://issues.apache.org/jira/browse/LOGCXX-242). | | | ![](images/fix.gif "fix") | Non-ascii named files have names mangled Fixes [LOGCXX-241](https://issues.apache.org/jira/browse/LOGCXX-241). | | | ![](images/update.gif "update") | Inconsistent const qualification on logging methods. Fixes [LOGCXX-239](https://issues.apache.org/jira/browse/LOGCXX-239). | | | ![](images/fix.gif "fix") | Include missing headers Fixes [LOGCXX-237](https://issues.apache.org/jira/browse/LOGCXX-237). | | | ![](images/fix.gif "fix") | Re-order constructor initialiser lists to match declaration order Fixes [LOGCXX-236](https://issues.apache.org/jira/browse/LOGCXX-236). | | | ![](images/add.gif "add") | Add ObjectPtrT::exchange Fixes [LOGCXX-235](https://issues.apache.org/jira/browse/LOGCXX-235). | | | ![](images/fix.gif "fix") | Assignment operator removes const qualifier Fixes [LOGCXX-234](https://issues.apache.org/jira/browse/LOGCXX-234). | | | ![](images/update.gif "update") | Unnecessary casts in ObjectPtrT Fixes [LOGCXX-233](https://issues.apache.org/jira/browse/LOGCXX-233). | | | ![](images/update.gif "update") | Drop src/performance Fixes [LOGCXX-232](https://issues.apache.org/jira/browse/LOGCXX-232). | | | ![](images/fix.gif "fix") | Deadlock in AsyncAppender Fixes [LOGCXX-231](https://issues.apache.org/jira/browse/LOGCXX-231). | | | ![](images/update.gif "update") | Align ant build options with automake Fixes [LOGCXX-230](https://issues.apache.org/jira/browse/LOGCXX-230). | | | ![](images/update.gif "update") | Remove \@author tags Fixes [LOGCXX-228](https://issues.apache.org/jira/browse/LOGCXX-228). | | | ![](images/update.gif "update") | Remove \@since tags Fixes [LOGCXX-227](https://issues.apache.org/jira/browse/LOGCXX-227). | | | ![](images/update.gif "update") | Default configurator uses \*.properties in preference to \*.xml Fixes [LOGCXX-226](https://issues.apache.org/jira/browse/LOGCXX-226). | | | ![](images/update.gif "update") | Migrate unit tests from LGPL'd CPPUNIT to an ASL'd testing framework Fixes [LOGCXX-225](https://issues.apache.org/jira/browse/LOGCXX-225). | | | ![](images/fix.gif "fix") | trunk compile error. Fixes [LOGCXX-222](https://issues.apache.org/jira/browse/LOGCXX-222). | | | ![](images/fix.gif "fix") | ThreadID layout does not match debugger Fixes [LOGCXX-221](https://issues.apache.org/jira/browse/LOGCXX-221). | | | ![](images/fix.gif "fix") | Memory leaks when using MFC Fixes [LOGCXX-220](https://issues.apache.org/jira/browse/LOGCXX-220). | | | ![](images/fix.gif "fix") | suspicious warnings Fixes [LOGCXX-219](https://issues.apache.org/jira/browse/LOGCXX-219). | | | ![](images/add.gif "add") | Visual Studio 8 build Fixes [LOGCXX-218](https://issues.apache.org/jira/browse/LOGCXX-218). | | | ![](images/fix.gif "fix") | Not initialized LoggerPtr segfault program. Fixes [LOGCXX-217](https://issues.apache.org/jira/browse/LOGCXX-217). | | | ![](images/fix.gif "fix") | crash on program exit Fixes [LOGCXX-216](https://issues.apache.org/jira/browse/LOGCXX-216). | | | ![](images/update.gif "update") | Eliminate sqlext.h from odbcappender.h Fixes [LOGCXX-215](https://issues.apache.org/jira/browse/LOGCXX-215). | | | ![](images/fix.gif "fix") | Possible memory leak due to fault in build process (via make) Fixes [LOGCXX-214](https://issues.apache.org/jira/browse/LOGCXX-214). | | | ![](images/fix.gif "fix") | trace method implementation is missing Fixes [LOGCXX-213](https://issues.apache.org/jira/browse/LOGCXX-213). | | | ![](images/fix.gif "fix") | unittest failed Fixes [LOGCXX-212](https://issues.apache.org/jira/browse/LOGCXX-212). | | | ![](images/fix.gif "fix") | Crash(Segmentation Fault) in DailyRollingFileAppender when file change Fixes [LOGCXX-211](https://issues.apache.org/jira/browse/LOGCXX-211). | | | ![](images/fix.gif "fix") | HTMLLayout NDC null check Fixes [LOGCXX-210](https://issues.apache.org/jira/browse/LOGCXX-210). | | | ![](images/fix.gif "fix") | A message of type wchar\_t\* is not beeing written correctly to the internal message buffer (Revision: 592627) Fixes [LOGCXX-209](https://issues.apache.org/jira/browse/LOGCXX-209). | | | ![](images/fix.gif "fix") | isTraceEnabled implemenation missing in logger.cpp (Revision: 592627) Fixes [LOGCXX-208](https://issues.apache.org/jira/browse/LOGCXX-208). | | | ![](images/fix.gif "fix") | PatternParserTestCase and FileNamePatternTestCase fail only with VC6 Fixes [LOGCXX-204](https://issues.apache.org/jira/browse/LOGCXX-204). | | | ![](images/fix.gif "fix") | ObjectPtrT has inconsistent const-ness on accessors Fixes [LOGCXX-202](https://issues.apache.org/jira/browse/LOGCXX-202). | | | ![](images/add.gif "add") | Visual Studio 6 build Fixes [LOGCXX-201](https://issues.apache.org/jira/browse/LOGCXX-201). | | | ![](images/add.gif "add") | Implement compression for RollingFileAppender Fixes [LOGCXX-200](https://issues.apache.org/jira/browse/LOGCXX-200). | | | ![](images/fix.gif "fix") | ant can't generate vc6 project Fixes [LOGCXX-197](https://issues.apache.org/jira/browse/LOGCXX-197). | | | ![](images/fix.gif "fix") | Syslog appender destructor can cause core Fixes [LOGCXX-196](https://issues.apache.org/jira/browse/LOGCXX-196). | | | ![](images/fix.gif "fix") | Syslog appender adds characters to output. Fixes [LOGCXX-195](https://issues.apache.org/jira/browse/LOGCXX-195). | | | ![](images/fix.gif "fix") | Garbage in log files when appenders are defined in multiple levels of the logger hierarchy Fixes [LOGCXX-194](https://issues.apache.org/jira/browse/LOGCXX-194). | | | ![](images/update.gif "update") | Please rename or remove new local variable "buf" in Logger.h macros Fixes [LOGCXX-193](https://issues.apache.org/jira/browse/LOGCXX-193). | | | ![](images/update.gif "update") | Suggested improvements to log4cxx webpages Fixes [LOGCXX-192](https://issues.apache.org/jira/browse/LOGCXX-192). | | | ![](images/fix.gif "fix") | Application cores when syslog appender is given an unreachable host/ip. Fixes [LOGCXX-191](https://issues.apache.org/jira/browse/LOGCXX-191). | | | ![](images/fix.gif "fix") | The 'logger.h' header includes itself. Fixes [LOGCXX-190](https://issues.apache.org/jira/browse/LOGCXX-190). | | | ![](images/update.gif "update") | Migrate to Maven 2.0 for documentation and packaging Fixes [LOGCXX-189](https://issues.apache.org/jira/browse/LOGCXX-189). | | | ![](images/update.gif "update") | Upgrade to apr 1.2.9 and apr-util 1.2.8 Fixes [LOGCXX-188](https://issues.apache.org/jira/browse/LOGCXX-188). | | | ![](images/fix.gif "fix") | LogLog::emit() could potentially interleave messages Fixes [LOGCXX-187](https://issues.apache.org/jira/browse/LOGCXX-187). | | | ![](images/fix.gif "fix") | Garbage characters in log files when log requests from multiple threads with hyperthreading enabled Fixes [LOGCXX-186](https://issues.apache.org/jira/browse/LOGCXX-186). | | | ![](images/fix.gif "fix") | Crash when log level set to 'inherited' Fixes [LOGCXX-184](https://issues.apache.org/jira/browse/LOGCXX-184). | | | ![](images/fix.gif "fix") | Compiler warning: dereferencing type-punned pointer will break strict-aliasing rules Fixes [LOGCXX-183](https://issues.apache.org/jira/browse/LOGCXX-183). | | | ![](images/fix.gif "fix") | missing man page for simplesocketserver Fixes [LOGCXX-182](https://issues.apache.org/jira/browse/LOGCXX-182). | | | ![](images/fix.gif "fix") | Level::DEBUG and other non-local statics cause crash on app shutdown on AIX Fixes [LOGCXX-181](https://issues.apache.org/jira/browse/LOGCXX-181). | | | ![](images/fix.gif "fix") | Build fails at domconfigurator.h Fixes [LOGCXX-180](https://issues.apache.org/jira/browse/LOGCXX-180). | | | ![](images/add.gif "add") | example applications do SIGABRT on aix 5.2 Fixes [LOGCXX-179](https://issues.apache.org/jira/browse/LOGCXX-179). | | | ![](images/fix.gif "fix") | Link failure if wchar\_t cannot be determined as UTF-16 or UTF-32 Fixes [LOGCXX-178](https://issues.apache.org/jira/browse/LOGCXX-178). | | | ![](images/fix.gif "fix") | SocketImpl::accept uses private APR function: apr\_wait\_for\_io\_or\_timeout Fixes [LOGCXX-177](https://issues.apache.org/jira/browse/LOGCXX-177). | | | ![](images/fix.gif "fix") | APRCharsetEncoder is not thread safe Fixes [LOGCXX-175](https://issues.apache.org/jira/browse/LOGCXX-175). | | | ![](images/fix.gif "fix") | configure fail with ".infig.status: error: cannot find input file:" Fixes [LOGCXX-172](https://issues.apache.org/jira/browse/LOGCXX-172). | | | ![](images/add.gif "add") | Add project description file for projects.apache.org Fixes [LOGCXX-171](https://issues.apache.org/jira/browse/LOGCXX-171). | | | ![](images/fix.gif "fix") | XMLLayoutTestCase fails on compilers that do not provide location info Fixes [LOGCXX-169](https://issues.apache.org/jira/browse/LOGCXX-169). | | | ![](images/fix.gif "fix") | log4j.dtd does not contain rollingPolicy and other o.a.l.r.RFA elements Fixes [LOGCXX-168](https://issues.apache.org/jira/browse/LOGCXX-168). | | | ![](images/fix.gif "fix") | system locale charmap is not determined properly on Fedora Core 6 Fixes [LOGCXX-167](https://issues.apache.org/jira/browse/LOGCXX-167). | | | ![](images/fix.gif "fix") | XMLSocketAppender may generate erroneous output due to mismatched encoding Fixes [LOGCXX-165](https://issues.apache.org/jira/browse/LOGCXX-165). | | | ![](images/fix.gif "fix") | XMLSocketAppender is disabled Fixes [LOGCXX-164](https://issues.apache.org/jira/browse/LOGCXX-164). | | | ![](images/fix.gif "fix") | liblog4cxx (svn 480882) does not link on Mac OS X 10.4 Fixes [LOGCXX-163](https://issues.apache.org/jira/browse/LOGCXX-163). | | | ![](images/fix.gif "fix") | Problem printing string with embedded NULL character Fixes [LOGCXX-162](https://issues.apache.org/jira/browse/LOGCXX-162). | | | ![](images/fix.gif "fix") | Using RollingFileAppender increases the working set with each rollover Fixes [LOGCXX-161](https://issues.apache.org/jira/browse/LOGCXX-161). | | | ![](images/fix.gif "fix") | helpers/object.h: DECLARE\_LOG4CXX\_OBJECT macro definition is missing virtual destructor declaration Fixes [LOGCXX-160](https://issues.apache.org/jira/browse/LOGCXX-160). | | | ![](images/fix.gif "fix") | Initialization of local static objects out of order on Linux Fixes [LOGCXX-159](https://issues.apache.org/jira/browse/LOGCXX-159). | | | ![](images/fix.gif "fix") | tolower not defined in stringhelper.cpp Fixes [LOGCXX-158](https://issues.apache.org/jira/browse/LOGCXX-158). | | | ![](images/fix.gif "fix") | make install fails since @manual\_dest@ replacement is missing in Makefiles Fixes [LOGCXX-157](https://issues.apache.org/jira/browse/LOGCXX-157). | | | ![](images/update.gif "update") | immediate flush in console appender Fixes [LOGCXX-156](https://issues.apache.org/jira/browse/LOGCXX-156). | | | ![](images/update.gif "update") | Update source headers per new ASF header policy Fixes [LOGCXX-155](https://issues.apache.org/jira/browse/LOGCXX-155). | | | ![](images/add.gif "add") | Automate log4cxx site and doxygen generation and deployment Fixes [LOGCXX-153](https://issues.apache.org/jira/browse/LOGCXX-153). | | | ![](images/fix.gif "fix") | gcc warning about cast from \`const void\*' to \`log4cxx::helpers::Object\*' discards qualifiers from pointer target typ Fixes [LOGCXX-152](https://issues.apache.org/jira/browse/LOGCXX-152). | | | ![](images/fix.gif "fix") | Umlauts as literal in patternlayout won't be logged correct Fixes [LOGCXX-151](https://issues.apache.org/jira/browse/LOGCXX-151). | | | ![](images/fix.gif "fix") | logstream's operator\<\< declared in the wrong namespace Fixes [LOGCXX-150](https://issues.apache.org/jira/browse/LOGCXX-150). | | | ![](images/fix.gif "fix") | make dist does not work Fixes [LOGCXX-149](https://issues.apache.org/jira/browse/LOGCXX-149). | | | ![](images/fix.gif "fix") | DailyRollingFileAppender::~DailyRollingFileAppender must call finalize Fixes [LOGCXX-146](https://issues.apache.org/jira/browse/LOGCXX-146). | | | ![](images/fix.gif "fix") | \-xarch=v8plus should be removed from Makefile.in Fixes [LOGCXX-143](https://issues.apache.org/jira/browse/LOGCXX-143). | | | ![](images/fix.gif "fix") | socketservertestcase.cpp does not compile with Sun Studio 11 on Solaris Fixes [LOGCXX-142](https://issues.apache.org/jira/browse/LOGCXX-142). | | | ![](images/update.gif "update") | Upgrade to APR 1.2.7 or later Fixes [LOGCXX-141](https://issues.apache.org/jira/browse/LOGCXX-141). | | | ![](images/fix.gif "fix") | Handle leak with LoggingEvent::getCurrentThreadName Fixes [LOGCXX-140](https://issues.apache.org/jira/browse/LOGCXX-140). | | | ![](images/fix.gif "fix") | XMLLayoutTestCase uses inadequate filters for 64 bit platforms Fixes [LOGCXX-139](https://issues.apache.org/jira/browse/LOGCXX-139). | | | ![](images/fix.gif "fix") | XMLLayoutTestCase output and filtered output gets overwritten Fixes [LOGCXX-138](https://issues.apache.org/jira/browse/LOGCXX-138). | | | ![](images/fix.gif "fix") | DailyRollingFileAppender not using Property options Fixes [LOGCXX-136](https://issues.apache.org/jira/browse/LOGCXX-136). | | | ![](images/update.gif "update") | Use std::string with logstream Fixes [LOGCXX-135](https://issues.apache.org/jira/browse/LOGCXX-135). | | | ![](images/fix.gif "fix") | FileAppender could create missing directories Fixes [LOGCXX-134](https://issues.apache.org/jira/browse/LOGCXX-134). | | | ![](images/fix.gif "fix") | Missing parenthesis in LOG4CXX\_ASSERT Fixes [LOGCXX-133](https://issues.apache.org/jira/browse/LOGCXX-133). | | | ![](images/fix.gif "fix") | various segmentation faults in multithreaded application Fixes [LOGCXX-132](https://issues.apache.org/jira/browse/LOGCXX-132). | | | ![](images/fix.gif "fix") | TimeBasedRollingPolicy is declared "abstract" Fixes [LOGCXX-131](https://issues.apache.org/jira/browse/LOGCXX-131). | | | ![](images/fix.gif "fix") | Compile fails on gcc4.1 Fixes [LOGCXX-130](https://issues.apache.org/jira/browse/LOGCXX-130). | | | ![](images/fix.gif "fix") | Asyncappender is full of race conditions (improper use of condition variables) Fixes [LOGCXX-129](https://issues.apache.org/jira/browse/LOGCXX-129). | | | ![](images/fix.gif "fix") | Main build.xml not referencing "env" properly. Fixes [LOGCXX-127](https://issues.apache.org/jira/browse/LOGCXX-127). | | | ![](images/fix.gif "fix") | std::cout stops working if log4cxx is first to output Fixes [LOGCXX-126](https://issues.apache.org/jira/browse/LOGCXX-126). | | | ![](images/update.gif "update") | L7dTestCase is stubbed out Fixes [LOGCXX-125](https://issues.apache.org/jira/browse/LOGCXX-125). | | | ![](images/fix.gif "fix") | wchar\_t constructor missing in class NDC Fixes [LOGCXX-124](https://issues.apache.org/jira/browse/LOGCXX-124). | | | ![](images/fix.gif "fix") | UTF-8 build fails on Linux Fixes [LOGCXX-123](https://issues.apache.org/jira/browse/LOGCXX-123). | | | ![](images/fix.gif "fix") | Wrong parameter description in Patternlayout Fixes [LOGCXX-120](https://issues.apache.org/jira/browse/LOGCXX-120). | | | ![](images/fix.gif "fix") | ndctestcase not working Fixes [LOGCXX-119](https://issues.apache.org/jira/browse/LOGCXX-119). | | | ![](images/fix.gif "fix") | Hierarchy corrupts with PropertyConfigurator Fixes [LOGCXX-118](https://issues.apache.org/jira/browse/LOGCXX-118). | | | ![](images/fix.gif "fix") | Memory leak with ThreadSpecificData on Win32 Fixes [LOGCXX-117](https://issues.apache.org/jira/browse/LOGCXX-117). | | | ![](images/fix.gif "fix") | SVN head does not compiler with MinGW compiler Fixes [LOGCXX-116](https://issues.apache.org/jira/browse/LOGCXX-116). | | | ![](images/fix.gif "fix") | SVN head does not compile with Borland C++ compiler Fixes [LOGCXX-115](https://issues.apache.org/jira/browse/LOGCXX-115). | | | ![](images/update.gif "update") | Upgrade APR to 1.2.2 from 1.1.0 Fixes [LOGCXX-114](https://issues.apache.org/jira/browse/LOGCXX-114). | | | ![](images/update.gif "update") | separate apr detection m4 codes from aclocal.m4 Fixes [LOGCXX-113](https://issues.apache.org/jira/browse/LOGCXX-113). | | | ![](images/update.gif "update") | change "static" to "auto" for Transcoder::decode() decoder and CharsetDecoder::getDefaultDecoder() decoder Fixes [LOGCXX-112](https://issues.apache.org/jira/browse/LOGCXX-112). | | | ![](images/update.gif "update") | make Logger cache a LoggerRepositoryPtr instead of a "blind" pointer Fixes [LOGCXX-111](https://issues.apache.org/jira/browse/LOGCXX-111). | | | ![](images/fix.gif "fix") | try fix 64bit log4cxx\_intptr\_t Fixes [LOGCXX-110](https://issues.apache.org/jira/browse/LOGCXX-110). | | | ![](images/fix.gif "fix") | Can't compile log4cxx in ascii on Windows Fixes [LOGCXX-107](https://issues.apache.org/jira/browse/LOGCXX-107). | | | ![](images/fix.gif "fix") | maxFileSize has bad type in SizeBasedTriggeringPolicy file Fixes [LOGCXX-106](https://issues.apache.org/jira/browse/LOGCXX-106). | | | ![](images/fix.gif "fix") | Infinite loop in string replacing Fixes [LOGCXX-105](https://issues.apache.org/jira/browse/LOGCXX-105). | | | ![](images/fix.gif "fix") | ODBCAppender::close does not check if appender is already closed Fixes [LOGCXX-104](https://issues.apache.org/jira/browse/LOGCXX-104). | | | ![](images/update.gif "update") | Much of CVS HEAD seems \#if 0 out, especially ResourceBundle stuff Fixes [LOGCXX-103](https://issues.apache.org/jira/browse/LOGCXX-103). | | | ![](images/fix.gif "fix") | Fixes for ODBCAppender Fixes [LOGCXX-100](https://issues.apache.org/jira/browse/LOGCXX-100). | | | ![](images/fix.gif "fix") | Gump build fails for log4cxx-ant-no-wchar-t target Fixes [LOGCXX-98](https://issues.apache.org/jira/browse/LOGCXX-98). | | | ![](images/update.gif "update") | simplesocketserver.cpp should use LOG4CXX\_STR("...") not L"..." Fixes [LOGCXX-94](https://issues.apache.org/jira/browse/LOGCXX-94). | | | ![](images/update.gif "update") | Explore use of security-enhanced CRT methods Fixes [LOGCXX-88](https://issues.apache.org/jira/browse/LOGCXX-88). | | | ![](images/update.gif "update") | Remove remaining uses of Category and Priority Fixes [LOGCXX-87](https://issues.apache.org/jira/browse/LOGCXX-87). | | | ![](images/add.gif "add") | Add TRACE level Fixes [LOGCXX-86](https://issues.apache.org/jira/browse/LOGCXX-86). | | | ![](images/update.gif "update") | Mac OS/X fixes and enhancements Fixes [LOGCXX-85](https://issues.apache.org/jira/browse/LOGCXX-85). | | | ![](images/fix.gif "fix") | Problems with stream logging in UTF8, no WCHAR\_T build Fixes [LOGCXX-84](https://issues.apache.org/jira/browse/LOGCXX-84). | | | ![](images/fix.gif "fix") | log4cxx::Level::ERROR fails to compile when GDI enabled Fixes [LOGCXX-83](https://issues.apache.org/jira/browse/LOGCXX-83). | | | ![](images/fix.gif "fix") | Compiling with stream.h in multiple object files errors Fixes [LOGCXX-82](https://issues.apache.org/jira/browse/LOGCXX-82). | | | ![](images/fix.gif "fix") | SimpleDateFormat does not compile on Solaris 2.95.2 gcc Fixes [LOGCXX-81](https://issues.apache.org/jira/browse/LOGCXX-81). | | | ![](images/update.gif "update") | Migrated network appenders to APR network IO Fixes [LOGCXX-80](https://issues.apache.org/jira/browse/LOGCXX-80). | | | ![](images/update.gif "update") | configure check for apr-util Fixes [LOGCXX-79](https://issues.apache.org/jira/browse/LOGCXX-79). | | | ![](images/fix.gif "fix") | Static builds broken Fixes [LOGCXX-77](https://issues.apache.org/jira/browse/LOGCXX-77). | | | ![](images/add.gif "add") | user.home, user.dir, java.io.tmpdir available within configuration files Fixes [LOGCXX-76](https://issues.apache.org/jira/browse/LOGCXX-76). | | | ![](images/add.gif "add") | Cygwin build Fixes [LOGCXX-75](https://issues.apache.org/jira/browse/LOGCXX-75). | | | ![](images/add.gif "add") | MinGW build Fixes [LOGCXX-74](https://issues.apache.org/jira/browse/LOGCXX-74). | | | ![](images/fix.gif "fix") | Not loading configuration from log4cxx.properties or log4cxx.xml Fixes [LOGCXX-73](https://issues.apache.org/jira/browse/LOGCXX-73). | | | ![](images/update.gif "update") | INSTALL out of date Fixes [LOGCXX-72](https://issues.apache.org/jira/browse/LOGCXX-72). | | | ![](images/update.gif "update") | Update performance page on web site Fixes [LOGCXX-71](https://issues.apache.org/jira/browse/LOGCXX-71). | | | ![](images/fix.gif "fix") | Logic flaws in StringHelper::startsWith and StringHelper::endsWith Fixes [LOGCXX-70](https://issues.apache.org/jira/browse/LOGCXX-70). | | | ![](images/fix.gif "fix") | NTEventLogAppender always uses RPC method for logging and has inadequate error handling. Fixes [LOGCXX-67](https://issues.apache.org/jira/browse/LOGCXX-67). | | | ![](images/fix.gif "fix") | SyslogAppender append method currently stubbed out Fixes [LOGCXX-66](https://issues.apache.org/jira/browse/LOGCXX-66). | | | ![](images/update.gif "update") | Migrate to APR network IO Fixes [LOGCXX-64](https://issues.apache.org/jira/browse/LOGCXX-64). | | | ![](images/update.gif "update") | Platform appropriate line-feed convention Fixes [LOGCXX-63](https://issues.apache.org/jira/browse/LOGCXX-63). | | | ![](images/update.gif "update") | log4cxx 0.10.0 release Fixes [LOGCXX-62](https://issues.apache.org/jira/browse/LOGCXX-62). | | | ![](images/fix.gif "fix") | XML layout can be mismatched with document encoding Fixes [LOGCXX-60](https://issues.apache.org/jira/browse/LOGCXX-60). | | | ![](images/update.gif "update") | Implement encoding support for Writer appender Fixes [LOGCXX-59](https://issues.apache.org/jira/browse/LOGCXX-59). | | | ![](images/fix.gif "fix") | ImmediateFlush'd FileAppenders extremely slow on Windows Fixes [LOGCXX-58](https://issues.apache.org/jira/browse/LOGCXX-58). | | | ![](images/add.gif "add") | Port log4j performance test Fixes [LOGCXX-57](https://issues.apache.org/jira/browse/LOGCXX-57). | | | ![](images/fix.gif "fix") | BasicConfiguration is unreliable Fixes [LOGCXX-56](https://issues.apache.org/jira/browse/LOGCXX-56). | | | ![](images/add.gif "add") | DailyRolling File Appender Fixes [LOGCXX-55](https://issues.apache.org/jira/browse/LOGCXX-55). | | | ![](images/fix.gif "fix") | Eliminate use of boost-regex in unit tests Fixes [LOGCXX-54](https://issues.apache.org/jira/browse/LOGCXX-54). | | | ![](images/fix.gif "fix") | Problems compiling with MsDev 6.0 (space in paths) Fixes [LOGCXX-53](https://issues.apache.org/jira/browse/LOGCXX-53). | | | ![](images/add.gif "add") | Migrate log4j 1.3 RollingFileAppender Fixes [LOGCXX-52](https://issues.apache.org/jira/browse/LOGCXX-52). | | | ![](images/fix.gif "fix") | variable name clash in macro Fixes [LOGCXX-50](https://issues.apache.org/jira/browse/LOGCXX-50). | | | ![](images/add.gif "add") | Move timezone specification into pattern, remove locale specification Fixes [LOGCXX-49](https://issues.apache.org/jira/browse/LOGCXX-49). | | | ![](images/add.gif "add") | Use hex representation for thread identifier Fixes [LOGCXX-48](https://issues.apache.org/jira/browse/LOGCXX-48). | | | ![](images/fix.gif "fix") | Check headers for missing declarations and Effective C++ violations Fixes [LOGCXX-47](https://issues.apache.org/jira/browse/LOGCXX-47). | | | ![](images/fix.gif "fix") | Extra semicolon after namespace closing paren Fixes [LOGCXX-46](https://issues.apache.org/jira/browse/LOGCXX-46). | | | ![](images/fix.gif "fix") | \_T causes error : 1048576 cannot be used as a function Fixes [LOGCXX-45](https://issues.apache.org/jira/browse/LOGCXX-45). | | | ![](images/add.gif "add") | GUMP integation Fixes [LOGCXX-44](https://issues.apache.org/jira/browse/LOGCXX-44). | | | ![](images/add.gif "add") | configure/make help needed Fixes [LOGCXX-43](https://issues.apache.org/jira/browse/LOGCXX-43). | | | ![](images/fix.gif "fix") | Layout timestamp doesn't seem to adjust for daylight saving Fixes [LOGCXX-41](https://issues.apache.org/jira/browse/LOGCXX-41). | | | ![](images/fix.gif "fix") | PatternLayout does not support Java date format specifiers Fixes [LOGCXX-40](https://issues.apache.org/jira/browse/LOGCXX-40). | | | ![](Pictures/100002000000001400000014836C96AED584EDBB.gif "remove") | Remove DailyRollingFileAppender Fixes [LOGCXX-39](https://issues.apache.org/jira/browse/LOGCXX-39). | | | ![](images/fix.gif "fix") | Unable to build log4cxx under Borland C++ Fixes [LOGCXX-37](https://issues.apache.org/jira/browse/LOGCXX-37). | | | ![](images/add.gif "add") | Migrate to Apache Portable Runtime threads Fixes [LOGCXX-36](https://issues.apache.org/jira/browse/LOGCXX-36). | | | ![](Pictures/100002000000001400000014836C96AED584EDBB.gif "remove") | Avoid use of MSXML Fixes [LOGCXX-35](https://issues.apache.org/jira/browse/LOGCXX-35). | | | ![](images/fix.gif "fix") | Visual Studio 6 CVS build broken Fixes [LOGCXX-34](https://issues.apache.org/jira/browse/LOGCXX-34). | | | ![](images/fix.gif "fix") | log4cxx::Exception is not derived from std::exception Fixes [LOGCXX-33](https://issues.apache.org/jira/browse/LOGCXX-33). | | | ![](images/fix.gif "fix") | Missing copy constructors and assignment operators Fixes [LOGCXX-32](https://issues.apache.org/jira/browse/LOGCXX-32). | | | ![](images/fix.gif "fix") | Missing const qualifiers, Exception::getMessage() in particular. Fixes [LOGCXX-31](https://issues.apache.org/jira/browse/LOGCXX-31). | | | ![](images/fix.gif "fix") | StringTokenizer uses evil strtok and wcstok functions Fixes [LOGCXX-30](https://issues.apache.org/jira/browse/LOGCXX-30). | | | ![](images/fix.gif "fix") | Appender attributes are not passed passed to setOption correctly. Fixes [LOGCXX-29](https://issues.apache.org/jira/browse/LOGCXX-29). | | | ![](images/fix.gif "fix") | Appender threshold cannot be set in configuration files Fixes [LOGCXX-28](https://issues.apache.org/jira/browse/LOGCXX-28). | | | ![](images/fix.gif "fix") | Appender threshold cannot be set in configuration files Fixes [LOGCXX-27](https://issues.apache.org/jira/browse/LOGCXX-27). | | | ![](images/fix.gif "fix") | Default initialization is broken Fixes [LOGCXX-26](https://issues.apache.org/jira/browse/LOGCXX-26). | | | ![](images/add.gif "add") | Add Ant+cpptasks build file Fixes [LOGCXX-25](https://issues.apache.org/jira/browse/LOGCXX-25). | | | ![](images/fix.gif "fix") | Class and module name not available in LogEvent Fixes [LOGCXX-24](https://issues.apache.org/jira/browse/LOGCXX-24). | | | ![](images/fix.gif "fix") | Unit tests have become stale Fixes [LOGCXX-23](https://issues.apache.org/jira/browse/LOGCXX-23). | | | ![](images/fix.gif "fix") | Backslashes in filenames in XML config of FileAppender broken Fixes [LOGCXX-22](https://issues.apache.org/jira/browse/LOGCXX-22). | | | ![](images/add.gif "add") | Add check that libxml2 not libxml has been included Fixes [LOGCXX-21](https://issues.apache.org/jira/browse/LOGCXX-21). | | | ![](images/add.gif "add") | Add .cvsignore's to ignore generated files Fixes [LOGCXX-19](https://issues.apache.org/jira/browse/LOGCXX-19). | | | ![](images/add.gif "add") | LoggerStream Feature Fixes [LOGCXX-18](https://issues.apache.org/jira/browse/LOGCXX-18). | | | ![](images/update.gif "update") | Use of non reentrant time functions Fixes [LOGCXX-17](https://issues.apache.org/jira/browse/LOGCXX-17). | | | ![](images/fix.gif "fix") | Misleading statements in Introduction to log4cxx Fixes [LOGCXX-16](https://issues.apache.org/jira/browse/LOGCXX-16). | | | ![](images/fix.gif "fix") | PatternLayout don't use locale time zone,it's use GMT tome zone Fixes [LOGCXX-15](https://issues.apache.org/jira/browse/LOGCXX-15). | | | ![](images/add.gif "add") | add -Wall to compile log4cxx will get many warning Fixes [LOGCXX-14](https://issues.apache.org/jira/browse/LOGCXX-14). | | | ![](images/add.gif "add") | Add branch optimization hint to LOG4CXX\_DEBUG macro Fixes [LOGCXX-13](https://issues.apache.org/jira/browse/LOGCXX-13). | | | ![](images/fix.gif "fix") | the threshold of ApenderSkeleton can not be set by calling setOption. Fixes [LOGCXX-12](https://issues.apache.org/jira/browse/LOGCXX-12). | | | ![](images/fix.gif "fix") | Timezone may have side-effects Fixes [LOGCXX-11](https://issues.apache.org/jira/browse/LOGCXX-11). | | | ![](images/fix.gif "fix") | Conflicting definitions of tchar.h/simulatenous Unicode+MBCS Fixes [LOGCXX-10](https://issues.apache.org/jira/browse/LOGCXX-10). | | | ![](images/fix.gif "fix") | Compilation problems using VC5 or VC6 with later Platform SDKs Fixes [LOGCXX-8](https://issues.apache.org/jira/browse/LOGCXX-8). | | | ![](images/fix.gif "fix") | SocketAppender binary format not compatible with Chainsaw Fixes [LOGCXX-7](https://issues.apache.org/jira/browse/LOGCXX-7). | | | ![](images/add.gif "add") | Win32 OutputDebugString Fixes [LOGCXX-6](https://issues.apache.org/jira/browse/LOGCXX-6). | | | ![](images/fix.gif "fix") | Preprocessor macro WIN32 used instead of \_WIN32 Fixes [LOGCXX-5](https://issues.apache.org/jira/browse/LOGCXX-5). | | | ![](images/fix.gif "fix") | initialization not working on many OS's Fixes [LOGCXX-4](https://issues.apache.org/jira/browse/LOGCXX-4). | | | ![](images/fix.gif "fix") | Missing \#else Fixes [LOGCXX-3](https://issues.apache.org/jira/browse/LOGCXX-3). | | | ![](images/fix.gif "fix") | logger.h includes config.h Fixes [LOGCXX-2](https://issues.apache.org/jira/browse/LOGCXX-2). | | ## Release 0.9.7 - 2004-05-10 {#rel_9_7} | | | | | ---------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | -- | | Type | Changes | By | | ![](images/fix.gif "fix") | Fixed examples source code in the "Short introduction to log4cxx". | | | ![](images/fix.gif "fix") | Fixed, in the renaming algorithm of RollingFileAppender and DailyRollingFileAppender, a problem specific to Unicode. | | | ![](images/fix.gif "fix") | Fixed conflict with Windows macros "min" and "max", by renaming StrictMath::min and StrictMath::max to StrictMath::minimum and StrictMath::maximum. | | | ![](images/add.gif "add") | Port to HPUX 11.0. | | | ![](images/fix.gif "fix") | Fixed segmentation fault in PropertyConfigurator. | | | ![](images/add.gif "add") | Port to Solaris. | | | ![](images/fix.gif "fix") | Fixed MutexException thrown while destroying RollingFileAppender. | | | ![](images/fix.gif "fix") | Logging macros can be used without explicity declaring the use of log4cxx namespace. | | | ![](images/fix.gif "fix") | Fixed static library unresolved externals for msvc 6 and 7.1 | | ## Release 0.9.6 - 2004-04-11 {#rel_9_6} | | | | | ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | -- | | Type | Changes | By | | ![](images/update.gif "update") | Timezone management has been optimized through the class TimeZone | | | ![](images/update.gif "update") | Inter-thread synchronization and reference counting has been optimized | | | ![](images/update.gif "update") | Reference counting now uses gcc atomic functions (bug 929078) | | | ![](images/update.gif "update") | Use of StringBuffer has been optimized. | | | ![](images/add.gif "add") | Support of localisation throug resourceBundles | | | ![](images/update.gif "update") | SyslogAppender now uses the system function 'syslog' to log on the local host. (only for POSIX systems) | | | ![](images/add.gif "add") | Added TimeZone configuration to PatternLayout (bug 912563) | | | ![](images/add.gif "add") | Support of the DailyRollingFileAppender (feature request 842765) | | ## Release 0.9.5 - 2004-02-04 {#rel_9_5} | | | | | ---------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | -- | | Type | Changes | By | | ![](images/add.gif "add") | Port of log4j Jnuit tests with Cppunit and Boost Regex. | | | ![](images/add.gif "add") | Added explicit exports for MSDEV 6 and MSDEV 7 (no further need of .def files) | | | ![](images/add.gif "add") | Custom levels can be configured through the DOMConfigurator and PropertyConfigurator classes (Level inherites from Object) | | | ![](images/add.gif "add") | Added a reference counter to LoggingEvent to avoid useless copies (LoggingEvent inherites from Object) | | | ![](images/add.gif "add") | The file log4j.xml as well as the file log4j.properties are now search for, in log4cxx initialization. | | | ![](images/add.gif "add") | The root logger can be assigned the "OFF" level. | | | ![](images/add.gif "add") | Added MSVC6 project missing files mutext.cpp and condition.cpp (bug 847397) | | | ![](images/fix.gif "fix") | condition.cpp now compiles with MSVC6 (bug 847417) | | | ![](images/fix.gif "fix") | fixed pure virtual function call in PropertyConfigurator::configureAndWatch (bug 848521) | | | ![](images/fix.gif "fix") | XMLAppender now displays correct timestamp with MSVC 6 (bug 852836) | | | ![](images/add.gif "add") | SRLPORT 4.6 support. | | | ![](images/fix.gif "fix") | Fixed an infinite loop in class Properties. | | | ![](images/fix.gif "fix") | Fixed compilations problems with unicode. | | | ![](images/fix.gif "fix") | Fixed SocketAppender bug concerning MDC and NDC. | | ## Release 0.9.4 - 2003-10-25 {#rel_9_4} | | | | | ------------------------------------------------------------------- | --------------------------------------------------------- | -- | | Type | Changes | By | | ![](images/update.gif "update") | StringBuffer has been optimized. | | | ![](images/fix.gif "fix") | Fixed miscellaneous threading problems. | | | ![](images/add.gif "add") | Added TimeZone support in PatternLayout (bug 796894) | | | ![](images/fix.gif "fix") | Fixed threading configuration problems (bug 809125) | | | ![](images/fix.gif "fix") | Fixed miscellaneous MSVC and cygwin compilation problems. | | ## Release 0.9.3 - 2003-09-19 {#rel_9_3} | | | | | ------------------------------------------------------------------- | ------------------------------------------------------------------------------- | -- | | Type | Changes | By | | ![](images/update.gif "update") | Changed tstring to log4cxx::String and tostringstream to log4cxx::StringBuffer. | | | ![](images/fix.gif "fix") | Fixed MSVC 2003 compilation erros and warnings. | | | ![](images/add.gif "add") | Added helpers for NDC and MDC. | | | ![](images/add.gif "add") | Added TimeZone support in TTCCLayout. | | | ![](images/fix.gif "fix") | Fixed compilation problems with logger macros (LOG4CXX\_...) | | | ![](images/fix.gif "fix") | Fixed milliseconds formatting problem with MSVC 6.0 and 2003 | | | ![](images/fix.gif "fix") | Fixed AsyncAppender crash | | | ![](images/add.gif "add") | Added new tests | | | ![](images/add.gif "add") | Added benchmarks | | ## Release 0.9.2 - 2003-08-10 {#rel_9_2} | | | | | ------------------------------------------------------------------- | ----------------------------------------------------------------------------- | -- | | Type | Changes | By | | ![](images/fix.gif "fix") | Fixed FreeBSD compilation problem with pthread mutex (class CriticalSection). | | | ![](images/fix.gif "fix") | Fixed milliseconds formatting problem (class DateFormat). | | | ![](images/add.gif "add") | Long events (\> 1024 chars) are now supported in the class XMLSocketAppender. | | | ![](images/update.gif "update") | Carriage returns have been normalized in the class XMLLayout. | | ## Release 0.9.1 - 2003-08-06 {#rel_9_1} | | | | | ------------------------------------------------------------------- | ------------------------------------------------------------ | -- | | Type | Changes | By | | ![](images/fix.gif "fix") | Fixed deadlock problems in classes Logger and AsyncAppender. | | | ![](images/fix.gif "fix") | Fixed MSVC 6.0 compilation problems. | | | ![](images/add.gif "add") | Added MSVC 6.0 static libraty project. | | | ![](images/update.gif "update") | Default configuration for the SMTP options is "no". | | ## Release 0.9.0 - 2003-08-06 {#rel_9_0} | | | | | ---------------------------------------------------------------- | ---------------------------------------------------------------------- | -- | | Type | Changes | By | | ![](images/add.gif "add") | Added ODBCAppender (matching log4j JDBCAppender) | | | ![](images/add.gif "add") | Added SyslogAppender | | | ![](images/add.gif "add") | Added SMTPAppender (only for Linux/FreeBSD) | | | ![](images/add.gif "add") | Added BasicConfigurator | | | ![](images/add.gif "add") | Added a FileWatchDog in PropertyConfigurator and DOMConfigurator | | | ![](images/add.gif "add") | Possibility to load a custom LoggerFactory through the DOMConfigurator | | | ![](images/add.gif "add") | Changed time precision from seconds to milliseconds | | | ![](images/add.gif "add") | Added MSVC 6.0 'Unicode Debug' and 'Unicode Release' targets | | | ![](images/add.gif "add") | Added Java like System class. | | ## Release 0.1.1 - 2003-07-09 {#rel_1_1} | | | | | ---------------------------------------------------------------- | ------------------------------------------------------------------- | -- | | Type | Changes | By | | ![](images/fix.gif "fix") | Fixed MSVC 6.0 compilation problems concerning the 'Release' target | | | ![](images/add.gif "add") | Added MSVC 6.0 tests projects | | ## Release 0.1.0 - 2003-07-08 {#rel_1_0} | | | | | ---------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | -- | | Type | Changes | By | | ![](images/add.gif "add") | FreeBSD Autotools/Compilation support | | | ![](images/fix.gif "fix") | Fixed TelnetAppender crash when a socket bind exception occured. | | | ![](images/add.gif "add") | Added log4j DTD support to XMLLayout and DOMConfigurator | | | ![](images/add.gif "add") | Can now send events in XML format over TCP (class XMLSocketAppender) for the log4j Chainsaw UI | | | ![](images/add.gif "add") | Now compiles with 'configure --enable-unicode' (UTF16 Unicode support) | | | ![](images/add.gif "add") | Added Java like Properties class. It's a helper for the PropertyConfigurator | | | ![](images/add.gif "add") | Added Java like objects with dynamic cast and instanciation. Custom objects can be configured through the DOMConfigurator and PropertyConfigurator classes | | | ![](images/add.gif "add") | Port of the PropertyConfigurator class | | | ![](images/add.gif "add") | Port of the "Map Diagnostic Context" (MDC) class | | | ![](images/add.gif "add") | Added 13 tests (try make check) | | ## Release 0.0.1 - 2003-05-31 {#rel_0_1} | | | | | ---------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -- | | Type | Changes | By | | ![](images/add.gif "add") | Loggers, Hierarchy, Filters, Appenders, Layouts, NDC | | | ![](images/add.gif "add") | Appenders: AsyncAppender, ConsoleAppender, FileAppender, NTEventLogAppender, RollingFileAppender, SocketAppender, SocketHubAappender, TelnetAppender | | | ![](images/add.gif "add") | Layouts: HTMLLayout, PatternLayout, SimpleLayout, TTCCLayout, XMLLayout | | | ![](images/add.gif "add") | Filters: DenyAllFilter, LevelMatchFilter, LevelRangeFilter, StringMatchFilter | | | ![](images/add.gif "add") | Configurators: DOMConfigurator | | apache-log4cxx-1.3.1/src/site/markdown/macros-influencing-log4cxx.md0000644000175100001770000000436514721727031024754 0ustar runnerdockerPreprocessor Macros Influencing Log4cxx {#macros-influencing-log4cxx} === The following macros can be defined in client code to influence how log messages are set or not. These macros may be set on a per-file basis(in which case they must be before any Log4cxx includes), or they may be set globally via your build system. | Macro | Usage | | ----- | ----- | | LOG4CXX\_THRESHOLD | Used to determine if log messages are compiled in or not. A higher value causes more messages to be compiled out. See [removing log statements](concepts.html#removing-log-statements) for more information. | | LOG4CXX\_DISABLE\_LOCATION\_INFO | Define this macro to disable location information on log statements. Location information includes the filename, class name, method name, and line number | | LOG4CXX\_ENABLE\_STACKTRACE | Define this macro to cause a stacktrace string to be inserted into the MDC with a key of 'stacktrace'. This requires Boost Stacktrace or C++23 stacktrace to be available when compiling your application. When using the PatternLayout, print out the stacktrace using the `%%X{stacktrace}` specifier. See [stacktrace support](stacktrace-support.html) for more information. | | LOG4CXX_FORMAT_NS | Override the namespace that LOG4CXX_XXXX_FMT macros use by default. The value can be either 'fmt' or 'std'. You would use the value 'std' if Log4cxx was built with LOG4CXX_FORMAT_NAMESPACE=fmt. | apache-log4cxx-1.3.1/src/site/markdown/index.md0000644000175100001770000000702314721727031020704 0ustar runnerdockerIntroduction {#introduction} === Apache Log4cxx is a logging framework for C++ patterned after [Apache log4j], which uses [Apache Portable Runtime] for most platform-specific code and should be usable on any platform supported by APR. Apache Log4cxx is licensed under the [Apache License], an open source license certified by the [Open Source Initiative]. Experience indicates that almost every large application needs runtime configurable logging. In the usual configuration, informational, warning and error log messages are saved to a persistent medium so they are available for study at a later time. With Log4cxx it is possible to activate additional logging output or disable some output for one or more modules of the running application by changing the configuration file. In the development cycle, logging can be an auditing tool. Debugging log output can be activated for an aspect of the application simply by modifying a configuration file. The correctness of a function should be verified by viewing logged calculated values. A faulty piece of code can be isolated by viewing logged function input values and the corresponding logged result values. These debugging log statements can be removed from the shipped application using a compiler build directive. Logging statements do increase the (code) size of the application, but with Log4cxx the speed of the application is not generally affected (see [Performance]). Logging is useful where debuggers are not, for example: - distributed applications - multithreaded applications - scientific applications (with vector and matrix valued variables) - real-time applications - event centered (e.g. GUI) applications For persisted messages, the storage location and the quantity retained can be specified and changed using a configuration file. The configuration also allows you to control the destination of log messages. They can be sent to a file, a remote socket server, event loggers as well as the console, with support for directing particular messages to one or more destinations. The [example programs page] will let you to quickly start using Log4cxx. The components of Log4cxx are described on the [concepts page]. For a more general overview, the logging services committee provides a [logging overview page] that explains more of what logging is and when to use it. [Apache log4j]:https://logging.apache.org/log4j/2.x/ [Apache Portable Runtime]:https://apr.apache.org/ [Apache License]:https://www.apache.org/licenses/ [example programs page]:quick-start.html [concepts page]:concepts.html [Open Source Initiative]:https://opensource.org/ [Performance]:performance.html [logging overview page]:https://logging.apache.org/what-is-logging.html apache-log4cxx-1.3.1/src/site/markdown/faq.md0000644000175100001770000001326314721727031020347 0ustar runnerdockerFrequently Asked Technical Questions {#faq} === [TOC] ## How do I add a custom level to Apache Log4cxx?{#custom_levels} This is a common topic for all the Apache logging frameworks and typically motivated to try to categorize events by functionality or audience. An common request is to add an AUDIT level so that the user can configure AUDIT level messages to go to a specific appender. However, the logger name was designed explicitly to support routing of messages by topic or audience. The common pattern of using classnames for logger names obscures the more general capability of logger name to represent the topic or audience of the logging request. The easiest approach to solve the underlying issue is to use a logger names like "AUDIT.com.example.MyPackage.MyClass" that allow all AUDIT messages to be routed to a particular appender. If you attempted to use a level for that then you would lose the ability to distinguish between different significances within the audit messages. ## My application on Windows crashes on shutdown?{#msvc_crash} Apache Log4cxx API calls use C++ Standard Template Library string parameters. If the caller is using a different instance or type of the C Runtime Library that Log4cxx, then it is very likely that some memory that was originally allocated by Log4cxx would be freed by the caller. If log4cxx and the caller are using different C RTL's, the program will likely crash at the point. Use "Multithread DLL" with release builds of Log4cxx and "Multithread DLL Debug" with debug builds. ## Does Apache Log4cxx support Unicode?{#unicode_supported} Yes. Apache Log4cxx exposes API methods in multiple string flavors supporting differently encoded textual content, like `char*`, `std::string`, `wchar_t*`, `std::wstring`, `CFStringRef` et al. All provided texts will be converted to the `LogString` type before further processing, which is one of several supported internal representations and is selected by the `LOG4CXX_CHAR` cmake option. If methods are used that take `LogString` as arguments, the macro `LOG4CXX_STR()` can be used to convert literals to the current `LogString` type. The default external representation is controlled by the `LOG4CXX_CHARSET` cmake option. This default is used to encode a multi-byte characters unless an `Encoding` property is explicitly configured for the log4cxx::FileAppender specialization you use. Note you should use `UTF-8` or `UTF-16` encoding when writing XML or JSON layouts. Log4cxx also implements character set encodings for `US-ASCII` (`ISO646-US` or `ANSI_X3.4-1968`) and `ISO-8859-1` (`ISO-LATIN-1` or `CP1252`). You are highly encouraged to stick to `UTF-8` for the best support from tools and operating systems. The `locale` character set encoding provides support beyond the above internally implemented options. It allows you to use any multi-byte encoding provided by the standard library. If using the `locale` character set encoding or you use `fwide` to make `stdout` or `stderr` wide-oriented (log4cxx::ConsoleAppender then uses `fputws`) you will need to explicitly configure the system locale at startup, for example by using: ``` std::setlocale( LC_ALL, "" ); /* Set user-preferred locale for C functions */ std::locale::global(std::locale("")); /* Set user-preferred locale for C++ functions */ ``` This is necessary because, according to the [libc documentation](https://www.gnu.org/software/libc/manual/html_node/Setting-the-Locale.html), all programs start in the `C` locale by default, which is the [same as ANSI_X3.4-1968](https://stackoverflow.com/questions/48743106/whats-ansi-x3-4-1968-encoding) and what's commonly known as the encoding `US-ASCII`. That encoding supports a very limited set of characters only, so inputting Unicode with that encoding in effect to output characters can't work properly. For example, here is some Hebrew text which says "People with disabilities": נשים עם מוגבלות If you are to log this information, output on some console might be like the following, simply because the app uses `US-ASCII` by default and that can't map those characters: ``` loggername - ?????????? ???? ?????????????? ``` The important thing to understand is that this is some always applied, backwards compatible default behaviour and even the case when the current environment sets a locale like `en_US.UTF-8`. ## Does Log4cxx support logging at process termination?{#atexit_events} Log4cxx must be built with -DLOG4CXX_EVENTS_AT_EXIT=ON to use logging during the application termination (i.e. in static destuctors and other atexit() functions) . When this option is used, the dynamic memory deallocation, buffer flushing and file handle closing normally done in destructors is not performed. Setting the "BufferedIO" option of any log4cxx::FileAppender to true is possible when using this option due to the forced buffers flushing during the static deinitialization phase. apache-log4cxx-1.3.1/src/site/markdown/performance.md0000644000175100001770000000567314721727031022107 0ustar runnerdockerLog4cxx Performance {#performance} === One important question with a logging library is: is it fast enough? While Log4cxx may not be the fastest logging implementation, it is more than fast enough for the vast majority of cases. In performance testing done on a developer's system(utilising an Intel i5-8400 processor and a virtual machine), it is possible for Log4cxx to handle over 2,000,000 messages/second in a single-threaded application. Since Log4cxx is designed to be multithread-safe, logging from multiple threads makes this throughput much lower. Delays in writing messages to disk can also greatly decrease performance, depending on how much data is being logged. If the logging of a particular level is disabled, performance can also be a lot better. While Log4cxx can generate 2,000,000 log messages/second, skipping a disabled logging request requires only a few nano-seconds, so application performance is not affected when logging requests are not removed from the release build. For the best performance, use the `LOG4CXX_[level]_FMT` series of macros, as the [{fmt}](https://fmt.dev/latest/index.html) library they use is significantly faster (up to twice as fast as `operator<<`). Note that you must include the headers from {fmt} manually. These two pieces of logging code are logically equivalent(printing out the same values), however the one utilizing fmt is close to 2x as fast on some systems. ```{.cpp} for( int x = 0; x < howmany; x++ ){ LOG4CXX_INFO( logger, "Hello logger: msg number " << x); } ``` ```{.cpp} for( int x = 0; x < howmany; x++ ){ LOG4CXX_INFO_FMT( logger, "Hello logger: msg number {}", x); } ``` If you wish to benchmark Log4cxx on your own system, have a look at the tools under the src/test/cpp/throughput and src/test/cpp/benchmark directories. The throughput tests may be built by specifying `BUILD_THROUGHPUT` with CMake when building Log4cxx. The benckmark tests require Google's [Benchmark](https://github.com/google/benchmark) library and may be built by specifying `BUILD_BENCHMARK_CHECKS` with CMake when building Log4cxx. apache-log4cxx-1.3.1/src/site/markdown/6-development.md0000644000175100001770000000202614721727031022260 0ustar runnerdockerDevelop {#development-overview} === See the following pages for development information: * @subpage source-repository * @subpage library-design * @subpage fuzzing apache-log4cxx-1.3.1/src/site/markdown/1-usage.md0000644000175100001770000000255714721727031021046 0ustar runnerdockerUse {#usage-overview} === See the following pages for usage information: * @subpage quick-start * @subpage concepts * @subpage configuration-samples * @subpage filters * @subpage extending-log4cxx * @subpage qt-support * @subpage stacktrace-support * @subpage threading * @subpage multiprocess-logging * @subpage environment-variables * @subpage macros-influencing-log4cxx * @subpage internal-debugging * @subpage performance * @subpage conclusions * @subpage faq * @subpage buildsystems * @subpage log-flow apache-log4cxx-1.3.1/src/site/markdown/internal-debugging.md0000644000175100001770000000254014721727031023341 0ustar runnerdockerInternal Debugging {#internal-debugging} === Because Log4cxx is a logging library, we can't use it to output errors from the library itself. There are several ways to activate internal logging: 1. Configure the library directly by calling the [LogLog::setInternalDebugging](@ref log4cxx.helpers.LogLog.setInternalDebugging) method 2. If using a properties file, set the value `log4j.debug=true` in your configuration file 3. If using an XML file, set the attribute `internalDebug=true` in the root node 4. From the environment: `LOG4CXX_DEBUG=true` All error and warning messages are sent to stderr. apache-log4cxx-1.3.1/src/site/markdown/qt-support.md0000644000175100001770000000511314721727031021731 0ustar runnerdockerQt Support {#qt-support} === When using Qt, messages from the Qt framework itself or other libraries may use the `QDebug` classes. By default, this will print to stderr, thus bypassing the logger entirely. In order to have these messages routed to Log4cxx, a message handler for Qt must be installed. Log4cxx provides a cmake build option `LOG4CXX_QT_SUPPORT=ON` which adds the log4cxx::qt namespace methods for directing Qt messages to Log4cxx and using the Qt event loop to process a configuration file change. Use the target `log4cxx-qt` instead of `log4cxx` in your `target_link_libraries` cmake directive. Also, including `log4cxx-qt/logger.h` allows you to use QString values in the LOG4CXX_WARN, LOG4CXX_INFO, LOG4CXX_DEBUG etc. macros. To install a message handler that will route the Qt logging messages through Log4cxx, include the messagehandler.h and call `qInstallMessageHandler` as follows: ```cpp #include ... qInstallMessageHandler( log4cxx::qt::messageHandler ); ``` Note that by default, this message handler also calls `abort` upon a fatal message. For how to use the Qt event loop to monitor the configuration file, see the \ref com/foo/config-qt.h and \ref com/foo/config-qt.cpp example files. Note that when using the above technique you *must* configure Log4cxx after creating your QCoreApplication instance (see the \ref MyApp-qt.cpp file for an example of this). \example MyApp-qt.cpp This file is an example of how to configure Log4cxx in a Qt application. \example com/foo/config-qt.h This header file is for Log4cxx configuration in a Qt application. \example com/foo/config-qt.cpp This file is an example of how to use the Qt event loop to monitor the Log4cxx configuration file. apache-log4cxx-1.3.1/src/site/markdown/download.md.in0000644000175100001770000000720514721727031022013 0ustar runnerdockerDownload {#download} === # Download Apache Log4cxx ${LOG4CXX_RELEASE_VERSION} Apache Log4cxx ${LOG4CXX_RELEASE_VERSION} is distributed under the [Apache License, version 2.0](https://www.apache.org/licenses/LICENSE-2.0.html). 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 Log4cxx ${LOG4CXX_RELEASE_VERSION} (tar.gz) | [source archive](${LOG4CXX_SOURCE_MIRROR_URL}.tar.gz) | [sha512](${LOG4CXX_DISTRIBUTION_URL}.tar.gz.sha512) [sha256](${LOG4CXX_DISTRIBUTION_URL}.tar.gz.sha256) | [GnuPG signature](${LOG4CXX_DISTRIBUTION_URL}.tar.gz.asc) | | Apache Log4cxx ${LOG4CXX_RELEASE_VERSION} (zip) | [source archive](${LOG4CXX_SOURCE_MIRROR_URL}.zip) | [sha512](${LOG4CXX_DISTRIBUTION_URL}.zip.sha512) [sha256](${LOG4CXX_DISTRIBUTION_URL}.zip.sha256) | [GnuPG signature](${LOG4CXX_DISTRIBUTION_URL}.zip.asc) | It is essential that you verify the integrity of the downloaded files using the PGP or SHA512 signatures. Please read [Verifying Apache HTTP Server Releases](https://httpd.apache.org/dev/verification.html) for more information on why you should verify our releases. The PGP signatures can be verified using PGP or GPG. First download the [KEYS](${APACHE_LOGGING_DISTRIBUTION_URL}/KEYS) as well as the asc signature file for the relevant distribution. Make sure you get these files from the [main distribution directory](${APACHE_LOGGING_DISTRIBUTION_URL}/), rather than from a mirror. Then verify the signatures using: ~~~ % gpg --import KEYS % gpg --verify ${LOG4CXX_SOURCE_PACKAGE_FILE_NAME}.tar.gz.asc ${LOG4CXX_SOURCE_PACKAGE_FILE_NAME}.tar.gz ~~~ * ${LOG4CXX_SOURCE_PACKAGE_FILE_NAME} is signed by ${LOG4CXX_RELEASE_MANAGER} (${LOG4CXX_RELEASE_MANAGER_KEY}) Alternatively, you can verify the SHA512 signature on the files. A unix program called sha512 or sha512sum is included in many unix distributions. ## Previous Releases | Version | Release Date | | :--------------------------: | :----------------------: | | [1.2.0](${LOG4CXX_DOCUMENTATION_URL}/1.2.0/download.html) | Jan-2024 | | [1.1.0](${LOG4CXX_DOCUMENTATION_URL}/1.1.0/download.html) | May-2023 | | [1.0.0](${LOG4CXX_DOCUMENTATION_URL}/1.0.0/download.html) | Jan-2023 | | [0.13.0](${LOG4CXX_DOCUMENTATION_URL}/0.13.0/download.html) | Aug-2022 | | [0.12.1](${LOG4CXX_DOCUMENTATION_URL}/0.12.1/download.html) | Sept-2021 | | [0.11.0](${LOG4CXX_DOCUMENTATION_URL}/0.11.0/download.html) | Aug-2020 | | [0.10.0](${LOG4CXX_DOCUMENTATION_URL}/0.10.0/download.html) | 2008 | apache-log4cxx-1.3.1/src/site/markdown/2-get.md0000644000175100001770000000167514721727031020522 0ustar runnerdockerGet {#get} === * @subpage download * @subpage changelog * @subpage license apache-log4cxx-1.3.1/src/site/markdown/threading.md0000644000175100001770000001201514721727031021537 0ustar runnerdockerThreading {#threading} === [TOC] Log4cxx is designed to be thread-safe under under normal usage. This means that logging itself is always thread-safe, however there are certain circumstances that can cause threading issues with Log4cxx. ## Unexpected Exit {#unexpected-exit} In multithreaded applications, it is possible to call `exit()` from any thread in the application. When this happens, other threads in the application may continue to run and attempt to log information. As of version 12 of Log4cxx, this should not cause the library to crash. We recommend that a graceful exit be performed whenever possible, and that all threads be terminated properly before returning from `main()`. See [LOGCXX-322][3] for more information. ## Signal Handling with Log4cxx {#signal-handling} Under certain configurations, Log4cxx may create new threads in order to do tasks(e.g. network comms, other async operations). On Linux/POSIX systems, this can lead to undesirable signal delivery, as signals can be delivered to any thread in the process. This can be most clearly seen if your application uses the [sigwait(3)][4] system call, as the thread that calls sigwait may not be the thread that actually gets the signal. By default, Log4cxx configures itself to block all signals to new threads that it creates on Linux/POSIX systems. See the [section on configuring](@ref configuring) for more details on how to configure. There are three main ways to handle signals coming to your process. All of these ways of handling signals are supported by Log4cxx in order to provide flexibility to users of the library. These three ways are: 1. Write to a file descriptor in a signal handler, notifying your main event loop of a signal. If you use Qt, [their documentation][2] has information on this method of handling a signal. 2. (Linux-only) Use [signalfd(2)][1] to create a file descriptor that notifies you of a signal. This is a special case of (1). 3. Block signals in newly created threads, ensuring that signals can only be sent to threads of your choosing. If you need to use option #3(for example, because you are using sigwait), Log4cxx provides a mechanism for defining methods to be called at two main points in the lifecycle of a thread: 1. Just before the thread starts 2. Just after the thread starts These two points are intended to let client code determine how best to start threads. Log4cxx provides a basic implementation of these for POSIX in order to block signals to the new threads that it creates. Once a new thread is created, there is also a callback function that lets client code do operations on the thread directly. A sample method in Log4cxx has a callback to name the thread in order to make debugging nicer. In order to use these callback functions, use the [ThreadUtility](@ref log4cxx.helpers.ThreadUtility) class. You can configure the ThreadUtility class in several different ways by using the [ThreadUtility::configure](@ref log4cxx.helpers.ThreadUtility.configure) method with several pre-defined configurations. In the event that you need special signal handling, you can implement your own functions, and use the [ThreadUtility::configureFuncs](@ref log4cxx.helpers.ThreadUtility.configureFuncs) method in order to customize exactly what happens. ### Configuring Thread {#configuring} To tell Log4cxx what to do by default when starting a new thread, the enum [ThreadConfigurationType](@ref log4cxx.helpers.ThreadConfigurationType) may be used to configure the library appropriately. By default, all signals on POSIX systems will be blocked to ensure that other threads do not get signals. To change this default, a simple change to your configuration files may be done. Example to disable the automatic signal blocking with XML configuration: ``` ... ``` Example to disable the automatic signal blocking with properties configuration: ``` log4j.threadConfiguration=NoConfiguration ``` [1]: https://man7.org/linux/man-pages/man2/signalfd.2.html [2]: https://doc.qt.io/qt-5/unix-signals.html [3]: https://issues.apache.org/jira/browse/LOGCXX-322 [4]: https://man7.org/linux/man-pages/man3/sigwait.3.html apache-log4cxx-1.3.1/src/site/markdown/stacktrace.md0000644000175100001770000000477214721727031021731 0ustar runnerdockerStacktrace Support {#stacktrace-support} === When debugging a code base and an assertion is hit, it is often useful to have a stacktrace as part of an assertion in order for you to tell where you are in the code to know why it is buggy. Generating a stacktrace can be done with [Boost Stacktrace](https://www.boost.org/doc/libs/1_81_0/doc/html/stacktrace.html), or using the [stacktrace](https://en.cppreference.com/w/cpp/header/stacktrace) header if you are using a C++23 compatible compiler. In order to enable stacktraces when using the `LOG4CXX_ASSERT` family of macros, simply define `LOG4CXX_ENABLE_STACKTRACE` in your buildsystem. If you are using a compiler that does not support C++17 and the `__has_include` macro, Boost Stacktrace must be installed and available on your system. If your compiler supports the `__has_include` macro, then it will search for Boost Stacktrace, followed by searching for ``. Both implementations will insert an entry into the MDC named `stacktrace` that may then be inserted into log statements. When using the [PatternLayout](@ref log4cxx.PatternLayout), this may be accomplished by using the `%%X{stacktrace}` conversion pattern. ## Putting the stacktrace into the MDC If you want a stacktrace in any part of your code(not just on assertions), the following snippet of code may be used to insert a stacktrace into the current MDC: ~~~{.cpp} ::log4cxx::MDC mdc_("stacktrace", LOG4CXX_EOL + boost::stacktrace::to_string(boost::stacktrace::stacktrace())); ~~~ This may be inserted at any point in your application, giving you access to the current stacktrace in any log statement, not just in assert statements. apache-log4cxx-1.3.1/src/site/log4cxx-flow.drawio0000644000175100001770000002773214721727031021206 0ustar runnerdocker apache-log4cxx-1.3.1/src/site/doxy/0000755000175100001770000000000014721727031016412 5ustar runnerdockerapache-log4cxx-1.3.1/src/site/doxy/DoxygenLayout.xml0000644000175100001770000001557014721727031021757 0ustar runnerdocker apache-log4cxx-1.3.1/src/site/doxy/Doxyfile.in0000644000175100001770000035757614721727031020554 0ustar runnerdocker# 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. # # Doxyfile 1.9.6 # This file describes the settings to be used by the documentation system # doxygen (www.doxygen.org) for a project. # # All text after a double hash (##) is considered a comment and is placed in # front of the TAG it is preceding. # # All text after a single hash (#) is considered a comment and will be ignored. # The format is: # TAG = value [value, ...] # For lists, items can also be appended using: # TAG += value [value, ...] # Values that contain spaces should be placed between quotes (\" \"). # # Note: # # Use doxygen to compare the used configuration file with the template # configuration file: # doxygen -x [configFile] # Use doxygen to compare the used configuration file with the template # configuration file without replacing the environment variables or CMake type # replacement variables: # doxygen -x_noenv [configFile] #--------------------------------------------------------------------------- # Project related configuration options #--------------------------------------------------------------------------- # This tag specifies the encoding used for all characters in the configuration # file that follow. The default is UTF-8 which is also the encoding used for all # text before the first occurrence of this tag. Doxygen uses libiconv (or the # iconv built into libc) for the transcoding. See # https://www.gnu.org/software/libiconv/ for the list of possible encodings. # The default value is: UTF-8. DOXYFILE_ENCODING = UTF-8 # The PROJECT_NAME tag is a single word (or a sequence of words surrounded by # double-quotes, unless you are using Doxywizard) that should identify the # project for which the documentation is generated. This name is used in the # title of most generated pages and in a few other places. # The default value is: My Project. PROJECT_NAME = "Apache Log4cxx" # The PROJECT_NUMBER tag can be used to enter a project or revision number. This # could be handy for archiving the generated documentation or if some version # control system is used. PROJECT_NUMBER = "Version ${LOG4CXX_RELEASE_VERSION}" # Using the PROJECT_BRIEF tag one can provide an optional one line description # for a project that appears at the top of each page and should give viewer a # quick idea about the purpose of the project. Keep the description short. PROJECT_BRIEF = # With the PROJECT_LOGO tag one can specify a logo or an icon that is included # in the documentation. The maximum height of the logo should not exceed 55 # pixels and the maximum width should not exceed 200 pixels. Doxygen will copy # the logo to the output directory. PROJECT_LOGO = # The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path # into which the generated documentation will be written. If a relative path is # entered, it will be relative to the location where doxygen was started. If # left blank the current directory will be used. OUTPUT_DIRECTORY = ${LOG4CXX_REL_BIN_TO_SRC_DIR} # If the CREATE_SUBDIRS tag is set to YES then doxygen will create up to 4096 # sub-directories (in 2 levels) under the output directory of each output format # and will distribute the generated files over these directories. Enabling this # option can be useful when feeding doxygen a huge amount of source files, where # putting all generated files in the same directory would otherwise causes # performance problems for the file system. Adapt CREATE_SUBDIRS_LEVEL to # control the number of sub-directories. # The default value is: NO. CREATE_SUBDIRS = NO # Controls the number of sub-directories that will be created when # CREATE_SUBDIRS tag is set to YES. Level 0 represents 16 directories, and every # level increment doubles the number of directories, resulting in 4096 # directories at level 8 which is the default and also the maximum value. The # sub-directories are organized in 2 levels, the first level always has a fixed # number of 16 directories. # Minimum value: 0, maximum value: 8, default value: 8. # This tag requires that the tag CREATE_SUBDIRS is set to YES. CREATE_SUBDIRS_LEVEL = 8 # If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII # characters to appear in the names of generated files. If set to NO, non-ASCII # characters will be escaped, for example _xE3_x81_x84 will be used for Unicode # U+3044. # The default value is: NO. ALLOW_UNICODE_NAMES = NO # The OUTPUT_LANGUAGE tag is used to specify the language in which all # documentation generated by doxygen is written. Doxygen will use this # information to generate all constant output in the proper language. # Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Bulgarian, # Catalan, Chinese, Chinese-Traditional, Croatian, Czech, Danish, Dutch, English # (United States), Esperanto, Farsi (Persian), Finnish, French, German, Greek, # Hindi, Hungarian, Indonesian, Italian, Japanese, Japanese-en (Japanese with # English messages), Korean, Korean-en (Korean with English messages), Latvian, # Lithuanian, Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, # Romanian, Russian, Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, # Swedish, Turkish, Ukrainian and Vietnamese. # The default value is: English. OUTPUT_LANGUAGE = English # If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member # descriptions after the members that are listed in the file and class # documentation (similar to Javadoc). Set to NO to disable this. # The default value is: YES. BRIEF_MEMBER_DESC = YES # If the REPEAT_BRIEF tag is set to YES, doxygen will prepend the brief # description of a member or function before the detailed description # # Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the # brief descriptions will be completely suppressed. # The default value is: YES. REPEAT_BRIEF = YES # This tag implements a quasi-intelligent brief description abbreviator that is # used to form the text in various listings. Each string in this list, if found # as the leading text of the brief description, will be stripped from the text # and the result, after processing the whole list, is used as the annotated # text. Otherwise, the brief description is used as-is. If left blank, the # following values are used ($name is automatically replaced with the name of # the entity):The $name class, The $name widget, The $name file, is, provides, # specifies, contains, represents, a, an and the. ABBREVIATE_BRIEF = "The $name class" \ "The $name widget" \ "The $name file" \ is \ provides \ specifies \ contains \ represents \ a \ an \ the # If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then # doxygen will generate a detailed section even if there is only a brief # description. # The default value is: NO. ALWAYS_DETAILED_SEC = NO # If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all # inherited members of a class in the documentation of that class as if those # members were ordinary class members. Constructors, destructors and assignment # operators of the base classes will not be shown. # The default value is: NO. INLINE_INHERITED_MEMB = NO # If the FULL_PATH_NAMES tag is set to YES, doxygen will prepend the full path # before files name in the file list and in the header files. If set to NO the # shortest path that makes the file name unique will be used # The default value is: YES. FULL_PATH_NAMES = NO # The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path. # Stripping is only done if one of the specified strings matches the left-hand # part of the path. The tag can be used to show relative paths in the file list. # If left blank the directory from which doxygen is run is used as the path to # strip. # # Note that you can specify absolute paths here, but also relative paths, which # will be relative from the directory where doxygen is started. # This tag requires that the tag FULL_PATH_NAMES is set to YES. STRIP_FROM_PATH = # The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the # path mentioned in the documentation of a class, which tells the reader which # header file to include in order to use a class. If left blank only the name of # the header file containing the class definition is used. Otherwise one should # specify the list of include paths that are normally passed to the compiler # using the -I flag. STRIP_FROM_INC_PATH = # If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but # less readable) file names. This can be useful is your file systems doesn't # support long names like on DOS, Mac, or CD-ROM. # The default value is: NO. SHORT_NAMES = NO # If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the # first line (until the first dot) of a Javadoc-style comment as the brief # description. If set to NO, the Javadoc-style will behave just like regular Qt- # style comments (thus requiring an explicit @brief command for a brief # description.) # The default value is: NO. JAVADOC_AUTOBRIEF = YES # If the JAVADOC_BANNER tag is set to YES then doxygen will interpret a line # such as # /*************** # as being the beginning of a Javadoc-style comment "banner". If set to NO, the # Javadoc-style will behave just like regular comments and it will not be # interpreted by doxygen. # The default value is: NO. JAVADOC_BANNER = NO # If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first # line (until the first dot) of a Qt-style comment as the brief description. If # set to NO, the Qt-style will behave just like regular Qt-style comments (thus # requiring an explicit \brief command for a brief description.) # The default value is: NO. QT_AUTOBRIEF = NO # The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a # multi-line C++ special comment block (i.e. a block of //! or /// comments) as # a brief description. This used to be the default behavior. The new default is # to treat a multi-line C++ comment block as a detailed description. Set this # tag to YES if you prefer the old behavior instead. # # Note that setting this tag to YES also means that rational rose comments are # not recognized any more. # The default value is: NO. MULTILINE_CPP_IS_BRIEF = NO # By default Python docstrings are displayed as preformatted text and doxygen's # special commands cannot be used. By setting PYTHON_DOCSTRING to NO the # doxygen's special commands can be used and the contents of the docstring # documentation blocks is shown as doxygen documentation. # The default value is: YES. PYTHON_DOCSTRING = YES # If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the # documentation from any documented member that it re-implements. # The default value is: YES. INHERIT_DOCS = YES # If the SEPARATE_MEMBER_PAGES tag is set to YES then doxygen will produce a new # page for each member. If set to NO, the documentation of a member will be part # of the file/class/namespace that contains it. # The default value is: NO. SEPARATE_MEMBER_PAGES = NO # The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen # uses this value to replace tabs by spaces in code fragments. # Minimum value: 1, maximum value: 16, default value: 4. TAB_SIZE = 4 # This tag can be used to specify a number of aliases that act as commands in # the documentation. An alias has the form: # name=value # For example adding # "sideeffect=@par Side Effects:^^" # will allow you to put the command \sideeffect (or @sideeffect) in the # documentation, which will result in a user-defined paragraph with heading # "Side Effects:". Note that you cannot put \n's in the value part of an alias # to insert newlines (in the resulting output). You can put ^^ in the value part # of an alias to insert a newline as if a physical newline was in the original # file. When you need a literal { or } or , in the value part of an alias you # have to escape them by means of a backslash (\), this can lead to conflicts # with the commands \{ and \} for these it is advised to use the version @{ and # @} or use a double escape (\\{ and \\}) ALIASES = usage="\par Example usage:^^" # Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources # only. Doxygen will then generate output that is more tailored for C. For # instance, some of the names that are used will be different. The list of all # members will be omitted, etc. # The default value is: NO. OPTIMIZE_OUTPUT_FOR_C = NO # Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or # Python sources only. Doxygen will then generate output that is more tailored # for that language. For instance, namespaces will be presented as packages, # qualified scopes will look different, etc. # The default value is: NO. OPTIMIZE_OUTPUT_JAVA = NO # Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran # sources. Doxygen will then generate output that is tailored for Fortran. # The default value is: NO. OPTIMIZE_FOR_FORTRAN = NO # Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL # sources. Doxygen will then generate output that is tailored for VHDL. # The default value is: NO. OPTIMIZE_OUTPUT_VHDL = NO # Set the OPTIMIZE_OUTPUT_SLICE tag to YES if your project consists of Slice # sources only. Doxygen will then generate output that is more tailored for that # language. For instance, namespaces will be presented as modules, types will be # separated into more groups, etc. # The default value is: NO. OPTIMIZE_OUTPUT_SLICE = NO # Doxygen selects the parser to use depending on the extension of the files it # parses. With this tag you can assign which parser to use for a given # extension. Doxygen has a built-in mapping, but you can override or extend it # using this tag. The format is ext=language, where ext is a file extension, and # language is one of the parsers supported by doxygen: IDL, Java, JavaScript, # Csharp (C#), C, C++, Lex, D, PHP, md (Markdown), Objective-C, Python, Slice, # VHDL, Fortran (fixed format Fortran: FortranFixed, free formatted Fortran: # FortranFree, unknown formatted Fortran: Fortran. In the later case the parser # tries to guess whether the code is fixed or free formatted code, this is the # default for Fortran type files). For instance to make doxygen treat .inc files # as Fortran files (default is PHP), and .f files as C (default is Fortran), # use: inc=Fortran f=C. # # Note: For files without extension you can use no_extension as a placeholder. # # Note that for custom extensions you also need to set FILE_PATTERNS otherwise # the files are not read by doxygen. When specifying no_extension you should add # * to the FILE_PATTERNS. # # Note see also the list of default file extension mappings. EXTENSION_MAPPING = # If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments # according to the Markdown format, which allows for more readable # documentation. See https://daringfireball.net/projects/markdown/ for details. # The output of markdown processing is further processed by doxygen, so you can # mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in # case of backward compatibilities issues. # The default value is: YES. MARKDOWN_SUPPORT = YES # When the TOC_INCLUDE_HEADINGS tag is set to a non-zero value, all headings up # to that level are automatically included in the table of contents, even if # they do not have an id attribute. # Note: This feature currently applies only to Markdown headings. # Minimum value: 0, maximum value: 99, default value: 5. # This tag requires that the tag MARKDOWN_SUPPORT is set to YES. TOC_INCLUDE_HEADINGS = 3 # When enabled doxygen tries to link words that correspond to documented # classes, or namespaces to their corresponding documentation. Such a link can # be prevented in individual cases by putting a % sign in front of the word or # globally by setting AUTOLINK_SUPPORT to NO. # The default value is: YES. AUTOLINK_SUPPORT = YES # If you use STL classes (i.e. std::string, std::vector, etc.) but do not want # to include (a tag file for) the STL sources as input, then you should set this # tag to YES in order to let doxygen match functions declarations and # definitions whose arguments contain STL classes (e.g. func(std::string); # versus func(std::string) {}). This also make the inheritance and collaboration # diagrams that involve STL classes more complete and accurate. # The default value is: NO. BUILTIN_STL_SUPPORT = NO # If you use Microsoft's C++/CLI language, you should set this option to YES to # enable parsing support. # The default value is: NO. CPP_CLI_SUPPORT = NO # Set the SIP_SUPPORT tag to YES if your project consists of sip (see: # https://www.riverbankcomputing.com/software/sip/intro) sources only. Doxygen # will parse them like normal C++ but will assume all classes use public instead # of private inheritance when no explicit protection keyword is present. # The default value is: NO. SIP_SUPPORT = NO # For Microsoft's IDL there are propget and propput attributes to indicate # getter and setter methods for a property. Setting this option to YES will make # doxygen to replace the get and set methods by a property in the documentation. # This will only work if the methods are indeed getting or setting a simple # type. If this is not the case, or you want to show the methods anyway, you # should set this option to NO. # The default value is: YES. IDL_PROPERTY_SUPPORT = YES # If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC # tag is set to YES then doxygen will reuse the documentation of the first # member in the group (if any) for the other members of the group. By default # all members of a group must be documented explicitly. # The default value is: NO. DISTRIBUTE_GROUP_DOC = NO # If one adds a struct or class to a group and this option is enabled, then also # any nested class or struct is added to the same group. By default this option # is disabled and one has to add nested compounds explicitly via \ingroup. # The default value is: NO. GROUP_NESTED_COMPOUNDS = NO # Set the SUBGROUPING tag to YES to allow class member groups of the same type # (for instance a group of public functions) to be put as a subgroup of that # type (e.g. under the Public Functions section). Set it to NO to prevent # subgrouping. Alternatively, this can be done per class using the # \nosubgrouping command. # The default value is: YES. SUBGROUPING = YES # When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions # are shown inside the group in which they are included (e.g. using \ingroup) # instead of on a separate page (for HTML and Man pages) or section (for LaTeX # and RTF). # # Note that this feature does not work in combination with # SEPARATE_MEMBER_PAGES. # The default value is: NO. INLINE_GROUPED_CLASSES = NO # When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions # with only public data fields or simple typedef fields will be shown inline in # the documentation of the scope in which they are defined (i.e. file, # namespace, or group documentation), provided this scope is documented. If set # to NO, structs, classes, and unions are shown on a separate page (for HTML and # Man pages) or section (for LaTeX and RTF). # The default value is: NO. INLINE_SIMPLE_STRUCTS = NO # When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or # enum is documented as struct, union, or enum with the name of the typedef. So # typedef struct TypeS {} TypeT, will appear in the documentation as a struct # with name TypeT. When disabled the typedef will appear as a member of a file, # namespace, or class. And the struct will be named TypeS. This can typically be # useful for C code in case the coding convention dictates that all compound # types are typedef'ed and only the typedef is referenced, never the tag name. # The default value is: NO. TYPEDEF_HIDES_STRUCT = NO # The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This # cache is used to resolve symbols given their name and scope. Since this can be # an expensive process and often the same symbol appears multiple times in the # code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small # doxygen will become slower. If the cache is too large, memory is wasted. The # cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range # is 0..9, the default is 0, corresponding to a cache size of 2^16=65536 # symbols. At the end of a run doxygen will report the cache usage and suggest # the optimal cache size from a speed point of view. # Minimum value: 0, maximum value: 9, default value: 0. LOOKUP_CACHE_SIZE = 0 # The NUM_PROC_THREADS specifies the number of threads doxygen is allowed to use # during processing. When set to 0 doxygen will based this on the number of # cores available in the system. You can set it explicitly to a value larger # than 0 to get more control over the balance between CPU load and processing # speed. At this moment only the input processing can be done using multiple # threads. Since this is still an experimental feature the default is set to 1, # which effectively disables parallel processing. Please report any issues you # encounter. Generating dot graphs in parallel is controlled by the # DOT_NUM_THREADS setting. # Minimum value: 0, maximum value: 32, default value: 1. NUM_PROC_THREADS = 1 #--------------------------------------------------------------------------- # Build related configuration options #--------------------------------------------------------------------------- # If the EXTRACT_ALL tag is set to YES, doxygen will assume all entities in # documentation are documented, even if no documentation was available. Private # class members and static file members will be hidden unless the # EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES. # Note: This will also disable the warnings about undocumented members that are # normally produced when WARNINGS is set to YES. # The default value is: NO. EXTRACT_ALL = YES # If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will # be included in the documentation. # The default value is: NO. EXTRACT_PRIVATE = NO # If the EXTRACT_PRIV_VIRTUAL tag is set to YES, documented private virtual # methods of a class will be included in the documentation. # The default value is: NO. EXTRACT_PRIV_VIRTUAL = NO # If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal # scope will be included in the documentation. # The default value is: NO. EXTRACT_PACKAGE = NO # If the EXTRACT_STATIC tag is set to YES, all static members of a file will be # included in the documentation. # The default value is: NO. EXTRACT_STATIC = NO # If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined # locally in source files will be included in the documentation. If set to NO, # only classes defined in header files are included. Does not have any effect # for Java sources. # The default value is: YES. EXTRACT_LOCAL_CLASSES = YES # This flag is only useful for Objective-C code. If set to YES, local methods, # which are defined in the implementation section but not in the interface are # included in the documentation. If set to NO, only methods in the interface are # included. # The default value is: NO. EXTRACT_LOCAL_METHODS = NO # If this flag is set to YES, the members of anonymous namespaces will be # extracted and appear in the documentation as a namespace called # 'anonymous_namespace{file}', where file will be replaced with the base name of # the file that contains the anonymous namespace. By default anonymous namespace # are hidden. # The default value is: NO. EXTRACT_ANON_NSPACES = NO # If this flag is set to YES, the name of an unnamed parameter in a declaration # will be determined by the corresponding definition. By default unnamed # parameters remain unnamed in the output. # The default value is: YES. RESOLVE_UNNAMED_PARAMS = YES # If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all # undocumented members inside documented classes or files. If set to NO these # members will be included in the various overviews, but no documentation # section is generated. This option has no effect if EXTRACT_ALL is enabled. # The default value is: NO. HIDE_UNDOC_MEMBERS = NO # If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all # undocumented classes that are normally visible in the class hierarchy. If set # to NO, these classes will be included in the various overviews. This option # will also hide undocumented C++ concepts if enabled. This option has no effect # if EXTRACT_ALL is enabled. # The default value is: NO. HIDE_UNDOC_CLASSES = NO # If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend # declarations. If set to NO, these declarations will be included in the # documentation. # The default value is: NO. HIDE_FRIEND_COMPOUNDS = NO # If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any # documentation blocks found inside the body of a function. If set to NO, these # blocks will be appended to the function's detailed documentation block. # The default value is: NO. HIDE_IN_BODY_DOCS = NO # The INTERNAL_DOCS tag determines if documentation that is typed after a # \internal command is included. If the tag is set to NO then the documentation # will be excluded. Set it to YES to include the internal documentation. # The default value is: NO. INTERNAL_DOCS = NO # With the correct setting of option CASE_SENSE_NAMES doxygen will better be # able to match the capabilities of the underlying filesystem. In case the # filesystem is case sensitive (i.e. it supports files in the same directory # whose names only differ in casing), the option must be set to YES to properly # deal with such files in case they appear in the input. For filesystems that # are not case sensitive the option should be set to NO to properly deal with # output files written for symbols that only differ in casing, such as for two # classes, one named CLASS and the other named Class, and to also support # references to files without having to specify the exact matching casing. On # Windows (including Cygwin) and MacOS, users should typically set this option # to NO, whereas on Linux or other Unix flavors it should typically be set to # YES. # Possible values are: SYSTEM, NO and YES. # The default value is: SYSTEM. CASE_SENSE_NAMES = YES # If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with # their full class and namespace scopes in the documentation. If set to YES, the # scope will be hidden. # The default value is: NO. HIDE_SCOPE_NAMES = NO # If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then doxygen will # append additional text to a page's title, such as Class Reference. If set to # YES the compound reference will be hidden. # The default value is: NO. HIDE_COMPOUND_REFERENCE= NO # If the SHOW_HEADERFILE tag is set to YES then the documentation for a class # will show which file needs to be included to use the class. # The default value is: YES. SHOW_HEADERFILE = YES # If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of # the files that are included by a file in the documentation of that file. # The default value is: YES. SHOW_INCLUDE_FILES = YES # If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each # grouped member an include statement to the documentation, telling the reader # which file to include in order to use the member. # The default value is: NO. SHOW_GROUPED_MEMB_INC = NO # If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include # files with double quotes in the documentation rather than with sharp brackets. # The default value is: NO. FORCE_LOCAL_INCLUDES = NO # If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the # documentation for inline members. # The default value is: YES. INLINE_INFO = YES # If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the # (detailed) documentation of file and class members alphabetically by member # name. If set to NO, the members will appear in declaration order. # The default value is: YES. SORT_MEMBER_DOCS = YES # If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief # descriptions of file, namespace and class members alphabetically by member # name. If set to NO, the members will appear in declaration order. Note that # this will also influence the order of the classes in the class list. # The default value is: NO. SORT_BRIEF_DOCS = NO # If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the # (brief and detailed) documentation of class members so that constructors and # destructors are listed first. If set to NO the constructors will appear in the # respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS. # Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief # member documentation. # Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting # detailed member documentation. # The default value is: NO. SORT_MEMBERS_CTORS_1ST = NO # If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy # of group names into alphabetical order. If set to NO the group names will # appear in their defined order. # The default value is: NO. SORT_GROUP_NAMES = NO # If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by # fully-qualified names, including namespaces. If set to NO, the class list will # be sorted only by class name, not including the namespace part. # Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. # Note: This option applies only to the class list, not to the alphabetical # list. # The default value is: NO. SORT_BY_SCOPE_NAME = NO # If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper # type resolution of all parameters of a function it will reject a match between # the prototype and the implementation of a member function even if there is # only one candidate or it is obvious which candidate to choose by doing a # simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still # accept a match between prototype and implementation in such cases. # The default value is: NO. STRICT_PROTO_MATCHING = NO # The GENERATE_TODOLIST tag can be used to enable (YES) or disable (NO) the todo # list. This list is created by putting \todo commands in the documentation. # The default value is: YES. GENERATE_TODOLIST = YES # The GENERATE_TESTLIST tag can be used to enable (YES) or disable (NO) the test # list. This list is created by putting \test commands in the documentation. # The default value is: YES. GENERATE_TESTLIST = YES # The GENERATE_BUGLIST tag can be used to enable (YES) or disable (NO) the bug # list. This list is created by putting \bug commands in the documentation. # The default value is: YES. GENERATE_BUGLIST = YES # The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or disable (NO) # the deprecated list. This list is created by putting \deprecated commands in # the documentation. # The default value is: YES. GENERATE_DEPRECATEDLIST= YES # The ENABLED_SECTIONS tag can be used to enable conditional documentation # sections, marked by \if ... \endif and \cond # ... \endcond blocks. ENABLED_SECTIONS = # The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the # initial value of a variable or macro / define can have for it to appear in the # documentation. If the initializer consists of more lines than specified here # it will be hidden. Use a value of 0 to hide initializers completely. The # appearance of the value of individual variables and macros / defines can be # controlled using \showinitializer or \hideinitializer command in the # documentation regardless of this setting. # Minimum value: 0, maximum value: 10000, default value: 30. MAX_INITIALIZER_LINES = 30 # Set the SHOW_USED_FILES tag to NO to disable the list of files generated at # the bottom of the documentation of classes and structs. If set to YES, the # list will mention the files that were used to generate the documentation. # The default value is: YES. SHOW_USED_FILES = YES # Set the SHOW_FILES tag to NO to disable the generation of the Files page. This # will remove the Files entry from the Quick Index and from the Folder Tree View # (if specified). # The default value is: YES. SHOW_FILES = YES # Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces # page. This will remove the Namespaces entry from the Quick Index and from the # Folder Tree View (if specified). # The default value is: YES. SHOW_NAMESPACES = YES # The FILE_VERSION_FILTER tag can be used to specify a program or script that # doxygen should invoke to get the current version for each file (typically from # the version control system). Doxygen will invoke the program by executing (via # popen()) the command command input-file, where command is the value of the # FILE_VERSION_FILTER tag, and input-file is the name of an input file provided # by doxygen. Whatever the program writes to standard output is used as the file # version. For an example see the documentation. FILE_VERSION_FILTER = # The LAYOUT_FILE tag can be used to specify a layout file which will be parsed # by doxygen. The layout file controls the global structure of the generated # output files in an output format independent way. To create the layout file # that represents doxygen's defaults, run doxygen with the -l option. You can # optionally specify a file name after the option, if omitted DoxygenLayout.xml # will be used as the name of the layout file. See also section "Changing the # layout of pages" for information. # # Note that if you run doxygen from a directory containing a file called # DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE # tag is left empty. LAYOUT_FILE = src/site/doxy/DoxygenLayout.xml # The CITE_BIB_FILES tag can be used to specify one or more bib files containing # the reference definitions. This must be a list of .bib files. The .bib # extension is automatically appended if omitted. This requires the bibtex tool # to be installed. See also https://en.wikipedia.org/wiki/BibTeX for more info. # For LaTeX the style of the bibliography can be controlled using # LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the # search path. See also \cite for info how to create references. CITE_BIB_FILES = #--------------------------------------------------------------------------- # Configuration options related to warning and progress messages #--------------------------------------------------------------------------- # The QUIET tag can be used to turn on/off the messages that are generated to # standard output by doxygen. If QUIET is set to YES this implies that the # messages are off. # The default value is: NO. QUIET = NO # The WARNINGS tag can be used to turn on/off the warning messages that are # generated to standard error (stderr) by doxygen. If WARNINGS is set to YES # this implies that the warnings are on. # # Tip: Turn warnings on while writing the documentation. # The default value is: YES. WARNINGS = YES # If the WARN_IF_UNDOCUMENTED tag is set to YES then doxygen will generate # warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag # will automatically be disabled. # The default value is: YES. WARN_IF_UNDOCUMENTED = YES # If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for # potential errors in the documentation, such as documenting some parameters in # a documented function twice, or documenting parameters that don't exist or # using markup commands wrongly. # The default value is: YES. WARN_IF_DOC_ERROR = YES # If WARN_IF_INCOMPLETE_DOC is set to YES, doxygen will warn about incomplete # function parameter documentation. If set to NO, doxygen will accept that some # parameters have no documentation without warning. # The default value is: YES. WARN_IF_INCOMPLETE_DOC = YES # This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that # are documented, but have no documentation for their parameters or return # value. If set to NO, doxygen will only warn about wrong parameter # documentation, but not about the absence of documentation. If EXTRACT_ALL is # set to YES then this flag will automatically be disabled. See also # WARN_IF_INCOMPLETE_DOC # The default value is: NO. WARN_NO_PARAMDOC = NO # If WARN_IF_UNDOC_ENUM_VAL option is set to YES, doxygen will warn about # undocumented enumeration values. If set to NO, doxygen will accept # undocumented enumeration values. If EXTRACT_ALL is set to YES then this flag # will automatically be disabled. # The default value is: NO. WARN_IF_UNDOC_ENUM_VAL = NO # If the WARN_AS_ERROR tag is set to YES then doxygen will immediately stop when # a warning is encountered. If the WARN_AS_ERROR tag is set to FAIL_ON_WARNINGS # then doxygen will continue running as if WARN_AS_ERROR tag is set to NO, but # at the end of the doxygen process doxygen will return with a non-zero status. # Possible values are: NO, YES and FAIL_ON_WARNINGS. # The default value is: NO. WARN_AS_ERROR = NO # The WARN_FORMAT tag determines the format of the warning messages that doxygen # can produce. The string should contain the $file, $line, and $text tags, which # will be replaced by the file and line number from which the warning originated # and the warning text. Optionally the format may contain $version, which will # be replaced by the version of the file (if it could be obtained via # FILE_VERSION_FILTER) # See also: WARN_LINE_FORMAT # The default value is: $file:$line: $text. WARN_FORMAT = "$file:$line: $text" # In the $text part of the WARN_FORMAT command it is possible that a reference # to a more specific place is given. To make it easier to jump to this place # (outside of doxygen) the user can define a custom "cut" / "paste" string. # Example: # WARN_LINE_FORMAT = "'vi $file +$line'" # See also: WARN_FORMAT # The default value is: at line $line of file $file. WARN_LINE_FORMAT = "at line $line of file $file" # The WARN_LOGFILE tag can be used to specify a file to which warning and error # messages should be written. If left blank the output is written to standard # error (stderr). In case the file specified cannot be opened for writing the # warning and error messages are written to standard error. When as file - is # specified the warning and error messages are written to standard output # (stdout). WARN_LOGFILE = #--------------------------------------------------------------------------- # Configuration options related to the input files #--------------------------------------------------------------------------- # The INPUT tag is used to specify the files and/or directories that contain # documented source files. You may enter file names like myfile.cpp or # directories like /usr/src/myproject. Separate the files or directories with # spaces. See also FILE_PATTERNS and EXTENSION_MAPPING # Note: If this tag is empty the current directory is searched. INPUT = src/main/include \ src/site/markdown \ ${LOG4CXX_REL_BIN_TO_SRC_DIR}/markdown # This tag can be used to specify the character encoding of the source files # that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses # libiconv (or the iconv built into libc) for the transcoding. See the libiconv # documentation (see: # https://www.gnu.org/software/libiconv/) for the list of possible encodings. # See also: INPUT_FILE_ENCODING # The default value is: UTF-8. INPUT_ENCODING = UTF-8 # This tag can be used to specify the character encoding of the source files # that doxygen parses The INPUT_FILE_ENCODING tag can be used to specify # character encoding on a per file pattern basis. Doxygen will compare the file # name with each pattern and apply the encoding instead of the default # INPUT_ENCODING) if there is a match. The character encodings are a list of the # form: pattern=encoding (like *.php=ISO-8859-1). See cfg_input_encoding # "INPUT_ENCODING" for further information on supported encodings. INPUT_FILE_ENCODING = # If the value of the INPUT tag contains directories, you can use the # FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and # *.h) to filter out the source-files in the directories. # # Note that for custom extensions or not directly supported extensions you also # need to set EXTENSION_MAPPING for the extension otherwise the files are not # read by doxygen. # # Note the list of default checked file patterns might differ from the list of # default file extension mappings. # # If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cpp, # *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, # *.hh, *.hxx, *.hpp, *.h++, *.l, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, # *.inc, *.m, *.markdown, *.md, *.mm, *.dox (to be provided as doxygen C # comment), *.py, *.pyw, *.f90, *.f95, *.f03, *.f08, *.f18, *.f, *.for, *.vhd, # *.vhdl, *.ucf, *.qsf and *.ice. FILE_PATTERNS = *.c \ *.cc \ *.cxx \ *.cpp \ *.c++ \ *.java \ *.ii \ *.ixx \ *.ipp \ *.i++ \ *.inl \ *.idl \ *.ddl \ *.odl \ *.h \ *.hh \ *.hxx \ *.hpp \ *.h++ \ *.cs \ *.d \ *.php \ *.php4 \ *.php5 \ *.phtml \ *.inc \ *.m \ *.markdown \ *.md \ *.mm \ *.dox \ *.py \ *.pyw \ *.f90 \ *.f95 \ *.f03 \ *.f08 \ *.f \ *.for \ *.tcl \ *.vhd \ *.vhdl \ *.ucf \ *.qsf # The RECURSIVE tag can be used to specify whether or not subdirectories should # be searched for input files as well. # The default value is: NO. RECURSIVE = YES # The EXCLUDE tag can be used to specify files and/or directories that should be # excluded from the INPUT source files. This way you can easily exclude a # subdirectory from a directory tree whose root is specified with the INPUT tag. # # Note that relative paths are relative to the directory from which doxygen is # run. EXCLUDE = ${LOG4CXX_SOURCE_DIR}/src/main/include/log4cxx/private # The EXCLUDE_SYMLINKS tag can be used to select whether or not files or # directories that are symbolic links (a Unix file system feature) are excluded # from the input. # The default value is: NO. EXCLUDE_SYMLINKS = NO # If the value of the INPUT tag contains directories, you can use the # EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude # certain files from those directories. # # Note that the wildcards are matched against the file with absolute path, so to # exclude all test directories for example use the pattern */test/* EXCLUDE_PATTERNS = # The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names # (namespaces, classes, functions, etc.) that should be excluded from the # output. The symbol name can be a fully qualified name, a word, or if the # wildcard * is used, a substring. Examples: ANamespace, AClass, # ANamespace::AClass, ANamespace::*Test # # Note that the wildcards are matched against the file with absolute path, so to # exclude all test directories use the pattern */test/* EXCLUDE_SYMBOLS = # The EXAMPLE_PATH tag can be used to specify one or more files or directories # that contain example code fragments that are included (see the \include # command). EXAMPLE_PATH = src/examples/cpp src/examples/config # If the value of the EXAMPLE_PATH tag contains directories, you can use the # EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and # *.h) to filter out the source-files in the directories. If left blank all # files are included. EXAMPLE_PATTERNS = * # If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be # searched for input files to be used with the \include or \dontinclude commands # irrespective of the value of the RECURSIVE tag. # The default value is: NO. EXAMPLE_RECURSIVE = NO # The IMAGE_PATH tag can be used to specify one or more files or directories # that contain images that are to be included in the documentation (see the # \image command). IMAGE_PATH = src/site/images # The INPUT_FILTER tag can be used to specify a program that doxygen should # invoke to filter for each input file. Doxygen will invoke the filter program # by executing (via popen()) the command: # # # # where is the value of the INPUT_FILTER tag, and is the # name of an input file. Doxygen will then use the output that the filter # program writes to standard output. If FILTER_PATTERNS is specified, this tag # will be ignored. # # Note that the filter must not add or remove lines; it is applied before the # code is scanned, but not when the output code is generated. If lines are added # or removed, the anchors will not be placed correctly. # # Note that doxygen will use the data processed and written to standard output # for further processing, therefore nothing else, like debug statements or used # commands (so in case of a Windows batch file always use @echo OFF), should be # written to standard output. # # Note that for custom extensions or not directly supported extensions you also # need to set EXTENSION_MAPPING for the extension otherwise the files are not # properly processed by doxygen. INPUT_FILTER = # The FILTER_PATTERNS tag can be used to specify filters on a per file pattern # basis. Doxygen will compare the file name with each pattern and apply the # filter if there is a match. The filters are a list of the form: pattern=filter # (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how # filters are used. If the FILTER_PATTERNS tag is empty or if none of the # patterns match the file name, INPUT_FILTER is applied. # # Note that for custom extensions or not directly supported extensions you also # need to set EXTENSION_MAPPING for the extension otherwise the files are not # properly processed by doxygen. FILTER_PATTERNS = # If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using # INPUT_FILTER) will also be used to filter the input files that are used for # producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES). # The default value is: NO. FILTER_SOURCE_FILES = NO # The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file # pattern. A pattern will override the setting for FILTER_PATTERN (if any) and # it is also possible to disable source filtering for a specific pattern using # *.ext= (so without naming a filter). # This tag requires that the tag FILTER_SOURCE_FILES is set to YES. FILTER_SOURCE_PATTERNS = # If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that # is part of the input, its contents will be placed on the main page # (index.html). This can be useful if you have a project on for instance GitHub # and want to reuse the introduction page also for the doxygen output. USE_MDFILE_AS_MAINPAGE = src/site/markdown/index.md # The Fortran standard specifies that for fixed formatted Fortran code all # characters from position 72 are to be considered as comment. A common # extension is to allow longer lines before the automatic comment starts. The # setting FORTRAN_COMMENT_AFTER will also make it possible that longer lines can # be processed before the automatic comment starts. # Minimum value: 7, maximum value: 10000, default value: 72. FORTRAN_COMMENT_AFTER = 72 #--------------------------------------------------------------------------- # Configuration options related to source browsing #--------------------------------------------------------------------------- # If the SOURCE_BROWSER tag is set to YES then a list of source files will be # generated. Documented entities will be cross-referenced with these sources. # # Note: To get rid of all source code in the generated output, make sure that # also VERBATIM_HEADERS is set to NO. # The default value is: NO. SOURCE_BROWSER = NO # Setting the INLINE_SOURCES tag to YES will include the body of functions, # classes and enums directly into the documentation. # The default value is: NO. INLINE_SOURCES = NO # Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any # special comment blocks from generated source code fragments. Normal C, C++ and # Fortran comments will always remain visible. # The default value is: YES. STRIP_CODE_COMMENTS = YES # If the REFERENCED_BY_RELATION tag is set to YES then for each documented # entity all documented functions referencing it will be listed. # The default value is: NO. REFERENCED_BY_RELATION = NO # If the REFERENCES_RELATION tag is set to YES then for each documented function # all documented entities called/used by that function will be listed. # The default value is: NO. REFERENCES_RELATION = NO # If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set # to YES then the hyperlinks from functions in REFERENCES_RELATION and # REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will # link to the documentation. # The default value is: YES. REFERENCES_LINK_SOURCE = YES # If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the # source code will show a tooltip with additional information such as prototype, # brief description and links to the definition and documentation. Since this # will make the HTML file larger and loading of large files a bit slower, you # can opt to disable this feature. # The default value is: YES. # This tag requires that the tag SOURCE_BROWSER is set to YES. SOURCE_TOOLTIPS = YES # If the USE_HTAGS tag is set to YES then the references to source code will # point to the HTML generated by the htags(1) tool instead of doxygen built-in # source browser. The htags tool is part of GNU's global source tagging system # (see https://www.gnu.org/software/global/global.html). You will need version # 4.8.6 or higher. # # To use it do the following: # - Install the latest version of global # - Enable SOURCE_BROWSER and USE_HTAGS in the configuration file # - Make sure the INPUT points to the root of the source tree # - Run doxygen as normal # # Doxygen will invoke htags (and that will in turn invoke gtags), so these # tools must be available from the command line (i.e. in the search path). # # The result: instead of the source browser generated by doxygen, the links to # source code will now point to the output of htags. # The default value is: NO. # This tag requires that the tag SOURCE_BROWSER is set to YES. USE_HTAGS = NO # If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a # verbatim copy of the header file for each class for which an include is # specified. Set to NO to disable this. # See also: Section \class. # The default value is: YES. VERBATIM_HEADERS = YES #--------------------------------------------------------------------------- # Configuration options related to the alphabetical class index #--------------------------------------------------------------------------- # If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all # compounds will be generated. Enable this if the project contains a lot of # classes, structs, unions or interfaces. # The default value is: YES. ALPHABETICAL_INDEX = YES # The IGNORE_PREFIX tag can be used to specify a prefix (or a list of prefixes) # that should be ignored while generating the index headers. The IGNORE_PREFIX # tag works for classes, function and member names. The entity will be placed in # the alphabetical list under the first letter of the entity name that remains # after removing the prefix. # This tag requires that the tag ALPHABETICAL_INDEX is set to YES. IGNORE_PREFIX = #--------------------------------------------------------------------------- # Configuration options related to the HTML output #--------------------------------------------------------------------------- # If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output # The default value is: YES. GENERATE_HTML = YES # The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a # relative path is entered the value of OUTPUT_DIRECTORY will be put in front of # it. # The default directory is: html. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_OUTPUT = html # The HTML_FILE_EXTENSION tag can be used to specify the file extension for each # generated HTML page (for example: .htm, .php, .asp). # The default value is: .html. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_FILE_EXTENSION = .html # The HTML_HEADER tag can be used to specify a user-defined HTML header file for # each generated HTML page. If the tag is left blank doxygen will generate a # standard header. # # To get valid HTML the header file that includes any scripts and style sheets # that doxygen needs, which is dependent on the configuration options used (e.g. # the setting GENERATE_TREEVIEW). It is highly recommended to start with a # default header using # doxygen -w html new_header.html new_footer.html new_stylesheet.css # YourConfigFile # and then modify the file new_header.html. See also section "Doxygen usage" # for information on how to generate the default header that doxygen normally # uses. # Note: The header is subject to change so you typically have to regenerate the # default header when upgrading to a newer version of doxygen. For a description # of the possible markers and block names see the documentation. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_HEADER = src/site/doxy/header.html # The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each # generated HTML page. If the tag is left blank doxygen will generate a standard # footer. See HTML_HEADER for more information on how to generate a default # footer and what special commands can be used inside the footer. See also # section "Doxygen usage" for information on how to generate the default footer # that doxygen normally uses. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_FOOTER = src/site/doxy/footer.html # The HTML_STYLESHEET tag can be used to specify a user-defined cascading style # sheet that is used by each HTML page. It can be used to fine-tune the look of # the HTML output. If left blank doxygen will generate a default style sheet. # See also section "Doxygen usage" for information on how to generate the style # sheet that doxygen normally uses. # Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as # it is more robust and this tag (HTML_STYLESHEET) will in the future become # obsolete. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_STYLESHEET = # The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined # cascading style sheets that are included after the standard style sheets # created by doxygen. Using this option one can overrule certain style aspects. # This is preferred over using HTML_STYLESHEET since it does not replace the # standard style sheet and is therefore more robust against future updates. # Doxygen will copy the style sheet files to the output directory. # Note: The order of the extra style sheet files is of importance (e.g. the last # style sheet in the list overrules the setting of the previous ones in the # list). # Note: Since the styling of scrollbars can currently not be overruled in # Webkit/Chromium, the styling will be left out of the default doxygen.css if # one or more extra stylesheets have been specified. So if scrollbar # customization is desired it has to be added explicitly. For an example see the # documentation. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_EXTRA_STYLESHEET = src/site/doxy/customdoxygen.css # The HTML_EXTRA_FILES tag can be used to specify one or more extra images or # other source files which should be copied to the HTML output directory. Note # that these files will be copied to the base HTML output directory. Use the # $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these # files. In the HTML_STYLESHEET file, use the file name only. Also note that the # files will be copied as-is; there are no commands or markers available. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_EXTRA_FILES = # The HTML_COLORSTYLE tag can be used to specify if the generated HTML output # should be rendered with a dark or light theme. # Possible values are: LIGHT always generate light mode output, DARK always # generate dark mode output, AUTO_LIGHT automatically set the mode according to # the user preference, use light mode if no preference is set (the default), # AUTO_DARK automatically set the mode according to the user preference, use # dark mode if no preference is set and TOGGLE allow to user to switch between # light and dark mode via a button. # The default value is: AUTO_LIGHT. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_COLORSTYLE = AUTO_LIGHT # The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen # will adjust the colors in the style sheet and background images according to # this color. Hue is specified as an angle on a color-wheel, see # https://en.wikipedia.org/wiki/Hue for more information. For instance the value # 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300 # purple, and 360 is red again. # Minimum value: 0, maximum value: 359, default value: 220. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_COLORSTYLE_HUE = 220 # The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors # in the HTML output. For a value of 0 the output will use gray-scales only. A # value of 255 will produce the most vivid colors. # Minimum value: 0, maximum value: 255, default value: 100. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_COLORSTYLE_SAT = 100 # The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the # luminance component of the colors in the HTML output. Values below 100 # gradually make the output lighter, whereas values above 100 make the output # darker. The value divided by 100 is the actual gamma applied, so 80 represents # a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not # change the gamma. # Minimum value: 40, maximum value: 240, default value: 80. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_COLORSTYLE_GAMMA = 80 # If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML # page will contain the date and time when the page was generated. Setting this # to YES can help to show when doxygen was last run and thus if the # documentation is up to date. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_TIMESTAMP = NO # If the HTML_DYNAMIC_MENUS tag is set to YES then the generated HTML # documentation will contain a main index with vertical navigation menus that # are dynamically created via JavaScript. If disabled, the navigation index will # consists of multiple levels of tabs that are statically embedded in every HTML # page. Disable this option to support browsers that do not have JavaScript, # like the Qt help browser. # The default value is: YES. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_DYNAMIC_MENUS = YES # If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML # documentation will contain sections that can be hidden and shown after the # page has loaded. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_DYNAMIC_SECTIONS = NO # With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries # shown in the various tree structured indices initially; the user can expand # and collapse entries dynamically later on. Doxygen will expand the tree to # such a level that at most the specified number of entries are visible (unless # a fully collapsed tree already exceeds this amount). So setting the number of # entries 1 will produce a full collapsed tree by default. 0 is a special value # representing an infinite number of entries and will result in a full expanded # tree by default. # Minimum value: 0, maximum value: 9999, default value: 100. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_INDEX_NUM_ENTRIES = 100 # If the GENERATE_DOCSET tag is set to YES, additional index files will be # generated that can be used as input for Apple's Xcode 3 integrated development # environment (see: # https://developer.apple.com/xcode/), introduced with OSX 10.5 (Leopard). To # create a documentation set, doxygen will generate a Makefile in the HTML # output directory. Running make will produce the docset in that directory and # running make install will install the docset in # ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at # startup. See https://developer.apple.com/library/archive/featuredarticles/Doxy # genXcode/_index.html for more information. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. GENERATE_DOCSET = NO # This tag determines the name of the docset feed. A documentation feed provides # an umbrella under which multiple documentation sets from a single provider # (such as a company or product suite) can be grouped. # The default value is: Doxygen generated docs. # This tag requires that the tag GENERATE_DOCSET is set to YES. DOCSET_FEEDNAME = "Doxygen generated docs" # This tag determines the URL of the docset feed. A documentation feed provides # an umbrella under which multiple documentation sets from a single provider # (such as a company or product suite) can be grouped. # This tag requires that the tag GENERATE_DOCSET is set to YES. DOCSET_FEEDURL = # This tag specifies a string that should uniquely identify the documentation # set bundle. This should be a reverse domain-name style string, e.g. # com.mycompany.MyDocSet. Doxygen will append .docset to the name. # The default value is: org.doxygen.Project. # This tag requires that the tag GENERATE_DOCSET is set to YES. DOCSET_BUNDLE_ID = org.doxygen.Project # The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify # the documentation publisher. This should be a reverse domain-name style # string, e.g. com.mycompany.MyDocSet.documentation. # The default value is: org.doxygen.Publisher. # This tag requires that the tag GENERATE_DOCSET is set to YES. DOCSET_PUBLISHER_ID = org.doxygen.Publisher # The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher. # The default value is: Publisher. # This tag requires that the tag GENERATE_DOCSET is set to YES. DOCSET_PUBLISHER_NAME = Publisher # If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three # additional HTML index files: index.hhp, index.hhc, and index.hhk. The # index.hhp is a project file that can be read by Microsoft's HTML Help Workshop # on Windows. In the beginning of 2021 Microsoft took the original page, with # a.o. the download links, offline the HTML help workshop was already many years # in maintenance mode). You can download the HTML help workshop from the web # archives at Installation executable (see: # http://web.archive.org/web/20160201063255/http://download.microsoft.com/downlo # ad/0/A/9/0A939EF6-E31C-430F-A3DF-DFAE7960D564/htmlhelp.exe). # # The HTML Help Workshop contains a compiler that can convert all HTML output # generated by doxygen into a single compiled HTML file (.chm). Compiled HTML # files are now used as the Windows 98 help format, and will replace the old # Windows help format (.hlp) on all Windows platforms in the future. Compressed # HTML files also contain an index, a table of contents, and you can search for # words in the documentation. The HTML workshop also contains a viewer for # compressed HTML files. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. GENERATE_HTMLHELP = NO # The CHM_FILE tag can be used to specify the file name of the resulting .chm # file. You can add a path in front of the file if the result should not be # written to the html output directory. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. CHM_FILE = # The HHC_LOCATION tag can be used to specify the location (absolute path # including file name) of the HTML help compiler (hhc.exe). If non-empty, # doxygen will try to run the HTML help compiler on the generated index.hhp. # The file has to be specified with full path. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. HHC_LOCATION = # The GENERATE_CHI flag controls if a separate .chi index file is generated # (YES) or that it should be included in the main .chm file (NO). # The default value is: NO. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. GENERATE_CHI = NO # The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc) # and project file content. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. CHM_INDEX_ENCODING = # The BINARY_TOC flag controls whether a binary table of contents is generated # (YES) or a normal table of contents (NO) in the .chm file. Furthermore it # enables the Previous and Next buttons. # The default value is: NO. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. BINARY_TOC = NO # The TOC_EXPAND flag can be set to YES to add extra items for group members to # the table of contents of the HTML help documentation and to the tree view. # The default value is: NO. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. TOC_EXPAND = NO # If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and # QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that # can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help # (.qch) of the generated HTML documentation. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. GENERATE_QHP = NO # If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify # the file name of the resulting .qch file. The path specified is relative to # the HTML output folder. # This tag requires that the tag GENERATE_QHP is set to YES. QCH_FILE = # The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help # Project output. For more information please see Qt Help Project / Namespace # (see: # https://doc.qt.io/archives/qt-4.8/qthelpproject.html#namespace). # The default value is: org.doxygen.Project. # This tag requires that the tag GENERATE_QHP is set to YES. QHP_NAMESPACE = org.doxygen.Project # The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt # Help Project output. For more information please see Qt Help Project / Virtual # Folders (see: # https://doc.qt.io/archives/qt-4.8/qthelpproject.html#virtual-folders). # The default value is: doc. # This tag requires that the tag GENERATE_QHP is set to YES. QHP_VIRTUAL_FOLDER = doc # If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom # filter to add. For more information please see Qt Help Project / Custom # Filters (see: # https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom-filters). # This tag requires that the tag GENERATE_QHP is set to YES. QHP_CUST_FILTER_NAME = # The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the # custom filter to add. For more information please see Qt Help Project / Custom # Filters (see: # https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom-filters). # This tag requires that the tag GENERATE_QHP is set to YES. QHP_CUST_FILTER_ATTRS = # The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this # project's filter section matches. Qt Help Project / Filter Attributes (see: # https://doc.qt.io/archives/qt-4.8/qthelpproject.html#filter-attributes). # This tag requires that the tag GENERATE_QHP is set to YES. QHP_SECT_FILTER_ATTRS = # The QHG_LOCATION tag can be used to specify the location (absolute path # including file name) of Qt's qhelpgenerator. If non-empty doxygen will try to # run qhelpgenerator on the generated .qhp file. # This tag requires that the tag GENERATE_QHP is set to YES. QHG_LOCATION = # If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be # generated, together with the HTML files, they form an Eclipse help plugin. To # install this plugin and make it available under the help contents menu in # Eclipse, the contents of the directory containing the HTML and XML files needs # to be copied into the plugins directory of eclipse. The name of the directory # within the plugins directory should be the same as the ECLIPSE_DOC_ID value. # After copying Eclipse needs to be restarted before the help appears. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. GENERATE_ECLIPSEHELP = NO # A unique identifier for the Eclipse help plugin. When installing the plugin # the directory name containing the HTML and XML files should also have this # name. Each documentation set should have its own identifier. # The default value is: org.doxygen.Project. # This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES. ECLIPSE_DOC_ID = org.doxygen.Project # If you want full control over the layout of the generated HTML pages it might # be necessary to disable the index and replace it with your own. The # DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top # of each HTML page. A value of NO enables the index and the value YES disables # it. Since the tabs in the index contain the same information as the navigation # tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. DISABLE_INDEX = NO # The GENERATE_TREEVIEW tag is used to specify whether a tree-like index # structure should be generated to display hierarchical information. If the tag # value is set to YES, a side panel will be generated containing a tree-like # index structure (just like the one that is generated for HTML Help). For this # to work a browser that supports JavaScript, DHTML, CSS and frames is required # (i.e. any modern browser). Windows users are probably better off using the # HTML help feature. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can # further fine tune the look of the index (see "Fine-tuning the output"). As an # example, the default style sheet generated by doxygen has an example that # shows how to put an image at the root of the tree instead of the PROJECT_NAME. # Since the tree basically has the same information as the tab index, you could # consider setting DISABLE_INDEX to YES when enabling this option. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. GENERATE_TREEVIEW = YES # When both GENERATE_TREEVIEW and DISABLE_INDEX are set to YES, then the # FULL_SIDEBAR option determines if the side bar is limited to only the treeview # area (value NO) or if it should extend to the full height of the window (value # YES). Setting this to YES gives a layout similar to # https://docs.readthedocs.io with more room for contents, but less room for the # project logo, title, and description. If either GENERATE_TREEVIEW or # DISABLE_INDEX is set to NO, this option has no effect. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. FULL_SIDEBAR = NO # The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that # doxygen will group on one line in the generated HTML documentation. # # Note that a value of 0 will completely suppress the enum values from appearing # in the overview section. # Minimum value: 0, maximum value: 20, default value: 4. # This tag requires that the tag GENERATE_HTML is set to YES. ENUM_VALUES_PER_LINE = 4 # If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used # to set the initial width (in pixels) of the frame in which the tree is shown. # Minimum value: 0, maximum value: 1500, default value: 250. # This tag requires that the tag GENERATE_HTML is set to YES. TREEVIEW_WIDTH = 250 # If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to # external symbols imported via tag files in a separate window. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. EXT_LINKS_IN_WINDOW = NO # If the OBFUSCATE_EMAILS tag is set to YES, doxygen will obfuscate email # addresses. # The default value is: YES. # This tag requires that the tag GENERATE_HTML is set to YES. OBFUSCATE_EMAILS = YES # If the HTML_FORMULA_FORMAT option is set to svg, doxygen will use the pdf2svg # tool (see https://github.com/dawbarton/pdf2svg) or inkscape (see # https://inkscape.org) to generate formulas as SVG images instead of PNGs for # the HTML output. These images will generally look nicer at scaled resolutions. # Possible values are: png (the default) and svg (looks nicer but requires the # pdf2svg or inkscape tool). # The default value is: png. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_FORMULA_FORMAT = png # Use this tag to change the font size of LaTeX formulas included as images in # the HTML documentation. When you change the font size after a successful # doxygen run you need to manually remove any form_*.png images from the HTML # output directory to force them to be regenerated. # Minimum value: 8, maximum value: 50, default value: 10. # This tag requires that the tag GENERATE_HTML is set to YES. FORMULA_FONTSIZE = 10 # The FORMULA_MACROFILE can contain LaTeX \newcommand and \renewcommand commands # to create new LaTeX commands to be used in formulas as building blocks. See # the section "Including formulas" for details. FORMULA_MACROFILE = # Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see # https://www.mathjax.org) which uses client side JavaScript for the rendering # instead of using pre-rendered bitmaps. Use this if you do not have LaTeX # installed or if you want to formulas look prettier in the HTML output. When # enabled you may also need to install MathJax separately and configure the path # to it using the MATHJAX_RELPATH option. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. USE_MATHJAX = NO # With MATHJAX_VERSION it is possible to specify the MathJax version to be used. # Note that the different versions of MathJax have different requirements with # regards to the different settings, so it is possible that also other MathJax # settings have to be changed when switching between the different MathJax # versions. # Possible values are: MathJax_2 and MathJax_3. # The default value is: MathJax_2. # This tag requires that the tag USE_MATHJAX is set to YES. MATHJAX_VERSION = MathJax_2 # When MathJax is enabled you can set the default output format to be used for # the MathJax output. For more details about the output format see MathJax # version 2 (see: # http://docs.mathjax.org/en/v2.7-latest/output.html) and MathJax version 3 # (see: # http://docs.mathjax.org/en/latest/web/components/output.html). # Possible values are: HTML-CSS (which is slower, but has the best # compatibility. This is the name for Mathjax version 2, for MathJax version 3 # this will be translated into chtml), NativeMML (i.e. MathML. Only supported # for NathJax 2. For MathJax version 3 chtml will be used instead.), chtml (This # is the name for Mathjax version 3, for MathJax version 2 this will be # translated into HTML-CSS) and SVG. # The default value is: HTML-CSS. # This tag requires that the tag USE_MATHJAX is set to YES. MATHJAX_FORMAT = HTML-CSS # When MathJax is enabled you need to specify the location relative to the HTML # output directory using the MATHJAX_RELPATH option. The destination directory # should contain the MathJax.js script. For instance, if the mathjax directory # is located at the same level as the HTML output directory, then # MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax # Content Delivery Network so you can quickly see the result without installing # MathJax. However, it is strongly recommended to install a local copy of # MathJax from https://www.mathjax.org before deployment. The default value is: # - in case of MathJax version 2: https://cdn.jsdelivr.net/npm/mathjax@2 # - in case of MathJax version 3: https://cdn.jsdelivr.net/npm/mathjax@3 # This tag requires that the tag USE_MATHJAX is set to YES. MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest # The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax # extension names that should be enabled during MathJax rendering. For example # for MathJax version 2 (see # https://docs.mathjax.org/en/v2.7-latest/tex.html#tex-and-latex-extensions): # MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols # For example for MathJax version 3 (see # http://docs.mathjax.org/en/latest/input/tex/extensions/index.html): # MATHJAX_EXTENSIONS = ams # This tag requires that the tag USE_MATHJAX is set to YES. MATHJAX_EXTENSIONS = # The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces # of code that will be used on startup of the MathJax code. See the MathJax site # (see: # http://docs.mathjax.org/en/v2.7-latest/output.html) for more details. For an # example see the documentation. # This tag requires that the tag USE_MATHJAX is set to YES. MATHJAX_CODEFILE = # When the SEARCHENGINE tag is enabled doxygen will generate a search box for # the HTML output. The underlying search engine uses javascript and DHTML and # should work on any modern browser. Note that when using HTML help # (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) # there is already a search function so this one should typically be disabled. # For large projects the javascript based search engine can be slow, then # enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to # search using the keyboard; to jump to the search box use + S # (what the is depends on the OS and browser, but it is typically # , /

apache-log4cxx-1.3.1/src/site/doxy/customdoxygen.css0000644000175100001770000000101014721727031022024 0ustar runnerdocker.navpath li.center { list-style-type:none; float:none; padding-left:10px; padding-right:10px; background-image:none; background-repeat:no-repeat; background-position:right; color:#364D7C; font-size: 8pt; line-height: 100%; text-align: center; } code { border-radius: 3px; padding: 3px 4px; background-color: #f7f7f9; border: 1px solid #e1e1e8; } /* make the links in the footer a bit more obvious */ .navpath a { color: #265ED0; } apache-log4cxx-1.3.1/src/site/doxy/header.html0000644000175100001770000000512014721727031020526 0ustar runnerdocker $projectname: $title $title $treeview $search $mathjax $extrastylesheet
$projectname  $projectnumber
$projectbrief
$projectbrief
$searchbox
apache-log4cxx-1.3.1/src/site/doxy/DTDs/0000755000175100001770000000000014721727031017210 5ustar runnerdockerapache-log4cxx-1.3.1/src/site/doxy/DTDs/xhtml-lat1.ent0000644000175100001770000002677714721727031021736 0ustar runnerdocker apache-log4cxx-1.3.1/src/site/doxy/DTDs/xhtml-special.ent0000644000175100001770000001004314721727031022470 0ustar runnerdocker apache-log4cxx-1.3.1/src/site/doxy/DTDs/xhtml-symbol.ent0000644000175100001770000003303014721727031022356 0ustar runnerdocker apache-log4cxx-1.3.1/src/site/doxy/DTDs/xhtml1-transitional.dtd0000644000175100001770000007655714721727031023653 0ustar runnerdocker %HTMLlat1; %HTMLsymbol; %HTMLspecial; apache-log4cxx-1.3.1/src/site/resources/0000755000175100001770000000000014721727031017441 5ustar runnerdockerapache-log4cxx-1.3.1/src/site/resources/images/0000755000175100001770000000000014721727031020706 5ustar runnerdockerapache-log4cxx-1.3.1/src/site/resources/images/expanded.gif0000644000175100001770000000006414721727031023165 0ustar runnerdockerGIF89a! , j ;apache-log4cxx-1.3.1/src/site/resources/images/collapsed.gif0000644000175100001770000000006514721727031023344 0ustar runnerdockerGIF89a! , D`c5 ;apache-log4cxx-1.3.1/src/site/resources/images/od.gif0000644000175100001770000001315514721727031022004 0ustar runnerdockerGIF89aT   !!!"""###$$$%%%&&&'''((()))***+++,,,---...///000111222333444555666777888999:::;;;<<<===>>>???@@@AAABBBCCCDDDEEEFFFGGGHHHIIIJJJKKKLLLMMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\\\]]]^^^___```aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqqrrrssstttuuuvvvwwwxxxyyyzzz{{{|||}}}~~~! ,T  H*\ȰÇ#J|ŋ3jȱǏ C8ɓ(S\ɲ˗0cʜIsEj "ϟ@ Jѣ'+"]'ӧPJJjOXQʵׯ`K֮#Ӫ]˶ڲp=+,]w.ͫ_|X\È#,LBǃBV,s2b-jg1 -4U }*?6]dMckWƭ5K˾MNx6jPd;"ڌUbGKh5$9rhji݊l*zi`tM奨]ݙ|efLǝ[}\4bxٵYpufSwSNa %҇Agᒐy)hi*KJcvPjy頫I%'z7볣Y$kKJv&_ʢЦG+`*2JblWmj`tH~J- ,$l  ܑŲŝ,4Fuqz 6L+J,a fJI4L>uSM7[N<4\g~].Mm>Sh .5-wjmVe?7mm7 x}]ou3ηފؓϚxtVεC9WJg.⥛~ B3;.0>$n{̿ݟ8'Fڞȧ'LO0pZ_7˳//ce޻Z<_s4xA`H$:Ozx r(VzJƌէ(MЂ:!g5 m' +2ҿ4CЅ )xC;!}*"vMC4"Ք0!2pOSV֣$>&-R͉^"E.dd6jkdܖwGpA[zux 9̊AqxʷH&Gyrxƚ}+d/yV\h>qw?ҕ!Unwr(X*0\_hOq4,JSr[q%ȼ }$0)Is(K #@FO? 4a:樏Xs>* ܼy);2gM `J鈔s&ƭsPEd+7Irrs ޘ,N*M}B$ϔn]J.#u2̎j3F3KM)3pUQ6cA ČX8B/u l[.vd+]gfؒvylw-1v]cr5K=e6@"u6 Ѻ^63[ϖx"j|7Ϲ7W[&zñw7$o%w ˬrK j≎ODRu]r2[?!F{=a|AhmwIps/-]`tp?}?쪮%noޯnolYֹ;du}| -PԳcO'yx1ܗjnxD7o7*fzr~g=TM\򥾼q&Yi2xYȣ9aV{2='a/0~;toߴsr6فxfO@.zkذֵ-[[Frtk1m]G}cV z)Sw&m} xRl$XcՂ꓂*X1X3h45|7F94;h=x?AȁCmEh\GxIhKNMOQ(SUXXWY[c](*_HacXBeHgXihkOmxo\qȆsKuwjyb{e}b8xP8y(uhHxh舑r(}|e8r{vl'F^gᆊOƊ+ 'FfڦƋ拂&aF\.#A.hV"/GwnhS&`GXۨ_eckdvhDmHMPOToP~^V(*⢈Rqr8ǃb[-,7LH+gCIu!RGFRETj R9XR/LEYâS1.-S;vk&*5t IU 9h!U.9V]be/zVxu[bz;㔎WUyl2V”V\LV'iz]nSQm pZ/])`st2,3))ćTrIr%boW&N՗9rSOsOkQb9,{2%RD24)aEd]a#(y/E.T|M^i{T"uYgw`1y1VI"i:94Pw\ɂ"{u79cDyrp9qPni*_~ #">J:*Cz2ڡc&`W8w\b#Nd8)J d a))$I/ʅ a5Ţ;+z- `A IX_MzzG:1ʠɤYz.!ZA|cu*J35ba6I5@k6\*v21y H3NY*Ħqi9ZʧzpjsoΩhۗd F{cKdL8CW:@fMW~xz?j|*kzM}(WǍدǮ iʯϺgʪIP%*G +Ӭղ&‘qʬYU[#ii$[s9j"őE$ʪF[ %B;yPˉRڮLu4zHڴEz`k7ڵI*VlKy@ (z=XÏ+;Y%DGvIm7aʻsy/,#Ѻ\η)< z.Md &Tցyt%ŘӤN*rX(֕_\{K {7̷ΔN7eOw)OirEpΘVkГmć='ҷ\ o\i[ƛΟkmGrLȥܜ5۞WE`Uݿ]ŝWÛF˾&kola TL?ʻ2Kl{͝޴$Ir|`GEʝݽmhmKՓ}͌o s{K}-zᬉZލۤ'[=鬬-L]Ŕaj A&V-NĜ>ǨZK7- }y :]Oi:n[<$c|:l\F',~ن nn|,:uM:Q?EmC腎.JÍ耋~;țX(3Qv~CϹS4Ř;apache-log4cxx-1.3.1/src/site/resources/images/logos/0000755000175100001770000000000014721727031022031 5ustar runnerdockerapache-log4cxx-1.3.1/src/site/resources/images/logos/ls-logo.jpg0000644000175100001770000012167314721727031024121 0ustar runnerdockerJFIFHH 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-log4cxx-1.3.1/src/site/resources/images/logos/maven-feather.png0000644000175100001770000000640214721727031025263 0ustar runnerdockerPNG  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-log4cxx-1.3.1/src/site/resources/images/logos/logo.png0000644000175100001770000000042314721727031023476 0ustar runnerdockerPNG  IHDRd-bKGD pHYs  tIME 3ݭiTXtCommentCreated with GIMPd.ewIDATx nH@\y^IENDB`apache-log4cxx-1.3.1/src/site/images/0000755000175100001770000000000014721727031016674 5ustar runnerdockerapache-log4cxx-1.3.1/src/site/images/log4cxx-flow.png0000644000175100001770000017644514721727031021760 0ustar runnerdockerPNG  IHDR0sRGB tEXtmxfile%3Cmxfile%20host%3D%22app.diagrams.net%22%20modified%3D%222023-12-11T03%3A49%3A59.577Z%22%20agent%3D%22Mozilla%2F5.0%20(Windows%20NT%2010.0%3B%20Win64%3B%20x64)%20AppleWebKit%2F537.36%20(KHTML%2C%20like%20Gecko)%20Chrome%2F119.0.0.0%20Safari%2F537.36%22%20etag%3D%22crr75VEQ795rjd7o6sOP%22%20version%3D%2222.1.7%22%20type%3D%22device%22%3E%3Cdiagram%20id%3D%22C5RBs43oDa-KdzZeNtuy%22%20name%3D%22Page-1%22%3E7VvZVts6FP2arNKHZHmIneSRhOnem0IZWuCJJRxhuyhWKjtTv%2F5KtuRRJAbsDBQe2kiRZUlnn7O3jpSGPhgvTgmYON%2FwCKKGpowWDf2ooWmq2mvT%2F1jNMqrptLWowibuiDdKKq7dP5BXKrx26o6gn2kYYIwCd5KttLDnQSvI1AFC8Dzb7Amj7FsnwIaFimsLoGLtrTsKnKi2q3WS%2BjPo2o54s2r2om%2FGQDTmM%2FEdMMLzVJV%2B3NAHBOMg%2BjReDCBiiyfW5faf5S0aPpun%2F176v8GP%2Fn835z%2BbUWcnr3kkngKBXlBt19yWM4CmfL34XIOlWECCp94Isk6Uht53gjGiH1X68RcMgiU3OJgGmFZhEjjYxh5AQ4wnvN0T9gLeTGVl6I0OmWFp%2BRFh6zmqOnER4u%2BgJd6%2BS0t%2BQPBzbDvWQWwI1hiBR4j6wHq2w4EOMMKEfuVhD7KuRhQMfC7J4I6T2n7JteU28PGUWHBFO51DHBAbrurPjNqx8aVwyi13CvEYBmRJGxCIQODOsmAG3CfsuF1id%2FqBm%2F4VMNALMBhi23Y9O%2FQDi%2BAD2LJbtDC8OG0P7u4ejo77P06%2FrsAKs9PccQN4PQHhgs1peMniJ40LOvW%2BjYDvc6uuMfrrjDaDJICLlcssvm0b0SMi2HHXnyeRQzV4nZOKGqZSk2HaBcPc02D66aLvcVGzpIsKBlvroxwsgidKuyzv6Tt26bySJvjpyacDy0MnfuHb0WQU0HSOC2Bab4%2B9htuWwNR5HZbUnceSWcDSN0YUtOrYA4%2BIwkMzEV2R%2FiOhn2z26cCHMMUhN2dXx9dnF8MjCY84ePw49ddzSMbwDFYnYOwitohnEM1g4FpAwjQAubZHCxbFACRyRNFXMv7Tj8ykdBMimAblGhlI6bSyHKR2iySkaUaRhOKGlbNQR6ISI%2BOO3JmwroebeHJg4fHEDa2v4ClDIn5i60SwTcD4q3iMjiL15IeTEYZwX8EMbYmO0DapI7plLBhKi1caaA8ZYD3BUTiQ5R3rjPoiL97HA6GFo0WmtHwTntZyi0BRmlzwwHmezR%2BvtEHvkhA0u%2Fg9OC%2B9meDwVFo6%2FcsitDa%2BSdosROzKOoep50AfTZc%2FVT1x9T5F0CaAKm%2BofTQZJEa4OrIO4SxMq8GsNFoXZf9eFZTbh7eVkhvxmFUrZ1AB3bTghb7Pso%2Ba4mGGNoRtmxn3o6kZJWcMXWIMvSY1I%2BW7YroqMUUVRqgN1maW%2BlTF2KAwlC6liF%2Fv4D4pu0lYMLXAcOEGKX1FS%2FepbxJ1xQpCXG1elH13ug%2FL25lzc9l78Cfn8NvP7kWzrCbrlmS6yhO8qxRiymNO2Tsjd4nyvJSiQs4M2B4eAsth45hMqOqg5LAX7mSYW%2FcmtbBSn94E13vJWm%2FSd8qbJFrghT3EkMnwrLUKsosBnio0dMi%2FGLujUQQM6Lt%2FmGDkaz9hqjaci9FvGEdSa6yEZcG14mNX%2FpZG%2BmRT5nJNpaXpJj%2BVeKsqj1Nd2ScqEeny%2BevbdEs15ZSJi34It1SNqv1SDpV2LtJ3DSPbRXU5A%2Fk8y53D7ZDHC4n8bo%2BnDq%2Foamb1BYzeadRmLkvaVM1NBYRiOvQwVjqKQ9%2BvKU8uosaSnLWW3ZTXpnqM3Bl1r%2BR2TM0n2qrjQ3PvZI%2Baia5JsN1MfBVxc990T6mDoEPLghPm58mmnL2W%2FZs%2FEXwpEVbok8krZYwJTHtm2d52N0qLbVkFUVrRlHYmLmj1BGnR7wZUW3f%2FVNt%2BRBWxJ65btnW6WfD0OhuWbcWzHklsuYK%2F2MVTGl9EvNq3MCLkTAVhRO%2BJ3oTD69XEES2rWuJBbyCOFK89DRxoPbPn2OUEDy6CmFbYiEL%2BYhoQk3DiDB6%2BLFe2a9JQ7%2BW2STJp2JNJw05d0lCEmpqPTepa0Y6Si2DiYGprKUZtq7kM5U2suNVcRmlWrCmZcUgIWKYa8DD%2FYqTU23LSfOk%2BRb69cPoEZNEIKo2pWjEhcg6nAQFoh3lSqywpwtKgbS2rt5sVZUXrSIJIT7KKSeyXclo7KLnfHiTKnupJ26lVh4iyXLBqNH%2FhlYTcrtTsSGi5risJUlNsl5X37%2BBPcm9%2BlWPWvVMtXErM3yOKJlTYqa7tKM7OVr%2FlXbVe0l9yhbuWL%2BFOht9HQzRcMCs4wGskp%2F1fojrKuw77teXObXNU1WiZai%2F1l7Wd5FKNpnRbHdmd%2BfwhZImAQIvJjz4juyU%2FndWP%2Fwc%3D%3C%2Fdiagram%3E%3C%2Fmxfile%3E21 IDATx^U}7u!,.Y %f 'PX_jڒҰM*Xg ?4S),jTK&F;ԩ8k~85օ.y泇s=syLa嵟猒l}hjjZsر."7'O[p  ! "r!!5[.H@U@Pu8AΨ@G\dV٩ $.@PN )@PNSk# -r6(@Pn@(A@PEʬ@+@P+q (b a"]  eF(@P@ȹ@a뽩]zuS|!Yfl߾]cVҍ5\#W]uUҗz8@ cy]QKA9jQC@ 倠7pu]'O?nEd֬YrJkko^xAn6yd2;vgسg̘1=uY|̞=[yO=>|Xx}[n83;~}ޥ4L8]]]r-x}/ s[ǿe;v?9#('%u@ȾAM\x|w;m۶ɤIkفeC?`P0+xaWC綾^Zmjx /jX^pW_=⿵MNӾk_5h_^(ޱcqYv7D~I(: d_ b;ܽ^4u&d~rwz;fw5P0e &ӽ_zcLkVrНfB/"ݻ/U6]'n[@HJ 0kg}֛Xc[-(-w~PP60keBl<43 V%_$=A9 e @> (J;/| ޮzSFfGޝuGi/r>^4 E ('\+8GiSlB)Xt|]5_@5EyYa CAYa;C녖_p׋͛7ˏ~^ ( ʺl.{G%YhI~.M~WGcFEԢ @~ Rs6:=}ojZWG_= {A9! A5ف6Own˾?r=?58'o$('͵@ȶA9Gk ( X\/ Euƌ @}8+NF@ r \2=rz\@ &(ۯMfO=omTItz|kq;C#DJ߷o%Xtf|/ z>vZA9*IA@ Cť^:j^yw&=kjnfY喬?WlٲEN>=iAO{ᇽoݎc~"(G-J{ W\M5xwe5:u,_\M6<ު1A}K/䵡e=.Iyv܃wlA\_~>GGP@ȵATa?1̸nJe۶m;BAJ$m$ת~!̙;A즇 1r,%KN<߿Pg  PAYGʝ3Wg'nذAM.:` *|PO8(èu{[tvv޿;}}}W# @Yޘ ܹs7/]tԂ ̚5K͵Nwp+;sG~r;#D@ g455-8qbǩS āBhnnhmm=rĉ|p/sI@H[ kA9m/W^DKWg~! @&W :MP<2 @pHd4rx  .GF  BPnS@@v[F ) |ė%(G Js  A9kyd  A١h+8@ (c]1@ (;4 t" (w ; @R`G9%/KP@@r>A9(@@!C@W q*  $@PǺ (c 8$@Pvh2 AQ  Ce&T@@ HuAP<2 @pHd4rx 5@P22@HI#,A9bPC@X|#@@MF]!(7ǩ  @A9날yd  A١h+8@`G9k߹ed  ;)G|YrĠ4 GF  BPnS@@ r>A9(@@!C@W q*  r~A9s@@ %vSAi@ (c 1@ (;45t2߱GDd~ZC{   (goI,"[Ex."D # nݘZz*"D䭀/ȥ"r9@@l.)F@ (1BwCDvu7Rf7VUG@,rvCЮ2ٝOz  Uf7<E@  }{WR9nC@32QeivDDCmr'# [e棞WEDz9@ (gYv&g2 #@Pvg.ɒO]?Ot7yWp  HrWE]K.kڵk?x裏VfxHt@pFTԑI&g>3gMN<)_?8~B9YS  0B1[oƍG{ɓeo@p@$Ѕ%"o۲dg׮]k_~Su5s(  `Y 瞛0gΜ~_2uU8@ (2.GeJq  pAUQ9lש[+q  /PaOrX)C@~!@Pvp%Zv-8@@9@[+q  PtvY#ua8@*@Pvc#G;$Jq QUvX-8@(A99Ш[+q  P$r:h=r!RV@@g9zän9! @ paJrX)C@< ]gR y (?N#6ua8@&@PwFG;tJq Ilf9[+q  r3z-8@ȃA9Yt=rX Jq dY9,ua8@*@P`VR Y (76kGBrX)C@ 럱B#n9! @VTQV@@ ga[+q  A9 9,ua8@\ (98:8@ (W ꑫ=8@R (W9Ir4  GxR1(! @ GqQ#.M# @呜#Gn9d.  K#7jj嚸8@R (PKR}\C[wu< )(_^x|{7n[=rHnw$S؅PZk=Te6;]"oP:ƹdCe}}kRy'K_׬Yu\}w i  Ul^4~ "B_^U/{rwk^M&wqp5azǎ^`z饗z/TWa[~ivy9Ní6{;㕀h\C~wG~V Q̤Do(k.pf AYK/tkf߅_|2>r+k POPu=rФ% x…^-">lo_/^4(i@LP꫇w@衇cDqT⏣-ǡZsv^."K5{KɻEUb~*[y IDAT}e 5;OQżkelV3mΗiô~VVXqeu|$<}.zݠwSA37n\w(L>k-hG>< zVgh+s4A /0– dT\zjAYa~{M[[vIk!wa28 m;x(A!y?W.({/~1(u˩AY?y{KGZfAPozt=xL;P1.ߝ2;m_Lyw~\ eJ9 f#@7 ^lڴkWf<&Muxe}]r&(Cn ʅGgΜ%ދ&ڲ; \-;j^8?fGҎ%"rН1AYu˩A 5}^3=A~m:Xr%Z/qðeJʽjphFyCۑ }e{3M3U7K8`7FJi_0j6B#W fAwT[AAټ5gv&t N@erl~w\FYw{wGMLvsh-7nXG -|u8eD~MåJ﬙xw -)ַ%wu׈Qmʯ3~'1Ղrлo3_SK B;ʕ#(XRjApՂ>}%SCewз?Y.+WlnQin_K&]/zaꢵ]/&L ,HSLЏe];(ve;sf;hGY3!hg\l_l EG3T[NF#p<'"4W5(GYlj+(?a~ƤRrؠZlcWF9C(kuS. ?h~8h%AArFuis."W"B`m"izaa<J]/ʽCWa޺OW}u;Ah.;7obߚ_^C|c˵χ)L r3=t>-gb/4(לWz8} K>E2A Az䢮ƝuˉsLPV: ىlvW|2AYdQ #gqs[ lyEA.f}_`G9ʨ .D@ )z_سgΜ&uY@-}"2 zO7]DP5[5_6:Tw'~ْ}u`Ii>ali?9m~rԾC+|vB GFhsk!Vr`ng8ߪ Zw(N 1hV#(guw('N*eH5X?l v;nQ^5G9>q5GPnDs,ړ첋r ڍ4e_?SPv=ePs MMӧn_-j߯'(/2;A5ʕvM;c5vh.Wl~a(y"(Y~A=r_& 犖Ex„ {׳qys={؟?>[|11v{Ey5pԩ^zGy{WTG#I$:OZ8>/eri[9(Afddop^A;M? fk(Z#G `/j߯'(kw_dYF//@j G%"T :rJ59 A놌 j`9N? 솹}ܹseLg%Q<T :XWf@z!$h7\}qФUl/Th7ͺ/{0i~`hվ_m1FUJA\4e*jW-(ؒQ#(S\me 8QSΥfÿqc"?mڴe_j=5es=ͻ_sPjI&g>3gl(Coe-o &v!z'Nپ~)T녾[m]/-ߎ?.v ѦAcu7ek~jAYfjQi(~ 85ּ>ـ)w!~ٯlt Q}es=r6=.@ؠ)E?(jLM]a *0ӜonygSzalƨmko=g^/wݲ74T[Qe-WCcLQ믿EĮPV#ϩsA5ݖMpmdGX2A9a^\҈n-~Q]P*sAYk5h [\.(w?uej Н'(@"[*8)Peݎ-e2QF=rF/\P޾}7gyFgFa>;(W'ywCZl>geҗ.]*YjQE?"(ǡJY7("[}D/@=2kOl(φz(?'Q뵫OP&*HPL[+2ʯ[FV@ |ٕ֧Fœ=h8(Yr4â9~c)r2Yv30It1v.XFID,@=rĠ4rf9\VQ ʠnks= 1rc~NMPvzz\Qe-8c4ȩsl1Ou\'@ \rn9 !BzdVUU{A9sG3(kϨ[nl~8rf> /bzb;[\7'ݟ#z@A9uL #@=r!W冦 PVK/Ο?jww802L$}<w>/"?KC\\ u)\zL2CtB@0Ν;wҥKG-X`̬YvBqoo۷Ν;Ϗ= -ܝ/zsA4tꖓ[ȅj'N8uԴwFOl#'NXBՠ}nUȑQ p9($P\@GǕV@(Aٛꖋ#ћ" EDP.MuEZ z9@QYUGJ  B K;f8-"B=rg1# @Ar|"-SY -٠\bnHGN  P8e0 l9` < @kSڌ@' u[A#(@H[ WAIrګ*S#.M# <e u9\#pR  5(+9u/ZF=r-Z Q 9({F-GTiztܹ* Ha]Q\\Q">F@ej3GdU@r* ߼QB { HhAٛZ\#9/ @ 2(&eV=M]A@OAYOݲ?#;0 t@.(zPVS9%x. %&C92JB@#a[iR2@@R*14 D*@Pn9e&B=rĠ4  +S9GZA@dս[nTT@HUpN#4NA@gᧂV#0@pZ\P\z# 7[L n -;_H n -Sl@pWnzM  覦Pu#Gph @ (G;/[9ECk  A9ym2/ZD@w1MꖩGi, 8+@PwjrQL=r@@Mre_ \@ ('3/[9U@@]rse\\ @ ('?5N-S  A9yqnztWE@7͋3u#2 +@PNynҮ[9@@YSJ2nL>@@7Ku#3@ (5/-Sք@pWUL=M@@YS#-SD3@pS漘^ERL=ۓL@@Mbeݟ\z  ݝ=nzL,D@gNM`B-SI  Ayԫu#goB1 )@Pvs^ꂺeꑫ}@@6rm^Nmꖻ&]{ﱏ>hS3  @F8KOEdW@@7nC8/"e X|,r>Q  Ce&T@@ HuAP<2 @pHd4rx 5@P22@HI#,A9bPC@X|#@@MF]!(7ǩ  @A9날yd  A١h+8@`G9k߹ed  ;)G|YrĠ4 GF  BPnS@@ r>E-A*Y-"7H_icEd,"O烄Q   sZYCtY_Ϯ~   SµeA^+"qyPD/0nRvK{]ȫ@@ʎMHݩ5(e^*_{gYvY#"WZ;zbY."g/!  P'(kú{_M6]EdvCM ! @Y_ޠM֠|t7ya|(2 @@ (c9D58kY~0tyr;fCQ  ܭ}>[B @(cM1zF  @P5& )sI@ȷA9KP<2 @pHd4rx  .GF  r#-̷~ZC{   (goI,"[}0/"PD # nݘZz*"D䭀/ȥ"r9@@l.)F@ (1BwCDvu7Rf7VUG@,rvCЮ2ٝOz  Uf7<E@  }{WR9nC@32QeivDDCmr'# [e棞WEDz9@ (gYv&g2 #@Pvg.ɒO]?Ot7yWp  HrWE]K.kڵk?x裏VfxHt@pFTԑI&g>3gMN<)_?8~B9YS  0B1[oƍG{ɓeo@p@$Ѕ%"o۲dg׮]k_~Su5s(  `Y 瞛0gΜ~_2uU8@ (2.GeJq  pAUQ9lש[+q  /PaOrX)C@~!@Pvp%Zv-8@@9@[+q  PtvY#ua8@*@Pvc#G;$Jq QUvX-8@(A99Ш[+q  P$r:h=r!RV@@g9zän9! @ paJrX)C@< ]gR y (?N#6ua8@&@PwFG;tJq Ilf9[+q  r3z-8@ȃA9Yt=rX Jq dY9,ua8@*@P`VR Y (76kGBrX)C@ 럱B#n9! @VTQV@@ ga[+q  A9 9,ua8\ hjjZ(SeLrV۩ ?0rx+̮@2]#zNrN&aDF+}[J/ܝZsXʉQs2ӪG>t}ݲm61C7zWeݲe;V?W9sF/_./p_O?˱͏cGWmB96aVwMb=#('FͅRbPN\yW-J¥&@P.ڌ"(@ւrȕم}G+xׯӧˍ7;"&>,Wmn^ﵷKeܹsn6oVtK/xuk}7s &?<܇qƍQ.OYfɵ^+|A;+uExb1 ,"ωȩ*cΜ9#^륾gϞXߡɪfg͚5}v?>'w iLZ KAىzJAY_K_l4q?Ǐ.0VKfΜ9IwLx SN+W[wvSOy}1c0U;;vٳG!Βj?(-W\ psMAY_&N(k׮Z%'Nͅ&(0 2ӪG,5&Mڦ=8xL. Q6zH>꫽;kkj A}شi+l?ԩ[1 hP> "oPa9(0u賟|ʏ~שr\\rwϼ󦿼^x{G߯z}{/XqAݻW-Piӿt~~;fE+מmGaG\ʩ#ҝڅ 1苑)Cy{ޙՠl^pud֙?(k5%zÿsm^Aٔzk~#>RP־RLPV: |En  Һ`oa3K/晿wwTK4x&s=™`Ù>%xAAY_9V~ww Mw05ޔ ]1^, SG5(vL]5\ՁUC.l?]*젬/pekoN;pZP6F-ge'$Wcv?8^+4_Bñb q8SAacntrwky=GydgUDs-oüCϺm߅# ?Gd_٠Ow~g:F:h?ʯpC_LN\v]`>ISlS1@.(-??8y6A>T;X]TkP֝c Q`Yۇr\^}г]Fa]aƢv_']._ *(Lc~D5wvvzAܖwwNR ;?=g8lRaӔ!Lݚg^hniϮl^?T/v3xoy@nzΉq(W KHtow4?QcGٽz@;f߾}ޝqor3RrרeG9̽+e) ;aށ$(;Hp9(+s5] !@r$AA5 s۸k5(\Κ^ey_v`jh.6_uu+껀;gm*ekȾ]a~D2/\(zPz]/XDٙ+zꄀ}׋rtl2?t\+]+ﮙЛ׻@ ]ywݰgRPt AlFm^m| _!rv^車J"pH A};RA(<Y (܋OK#zG=ío]9|-ͪ@;YkG2"2_}} n0+Eqw0 f-rN ]ʫ@ҋ0.2Y ޼P\~#H" (G&YAF A48rΏ9\ (8+ 08KE AYѨ[NeqQݘzQ8rYECPyn#pAٵI?йdy uˉT.H=r*\[z|B*(f/]s< -K,VL}eG9&XuJ AY[vjEꑣq" (G&YAF AYNrcG$Ţ 6%( u^#g{}nʹ#( >( Q38it(tqYE(JPֹn9C+z M]-A3AEP"eO_#;>At_Y 5PeoR[vsmS+, 2k ʥn١%N=CAW.@Pn#(3@)rP@ݲ?#;0 tʵyhr.A~,GN "Р@sscǎ5gU@_'O<08886c ([\;z,i 9o޼/8ptttܑ. b (dn9e6Q@(Դaٲen޼yLiVXqv֭V9M@ [nxYozqifyf/CwJZv1eʔ+D+!@PVn9F=rĠ4@ǏqӮ]ƥ.%KN<߿4Ks9 (W n9H=r4kZ9s*}wmnφ 一i9r)nQ#GnSp_/Ο?jww80ܟz{ vvv޿;}}}!%r٢n9ӈGSȠa;wKZ`Yf 9벆^ٷoٝ;w=z[d^Am^-9$!/MMM'Nqԩi-^F@@7Ku#3@ (5/-Sք@pWUL=M@@YS#-SD3@pS漘^ERL=ۓL@@Mbeݟ\z  ݝ=nzL,D@gNM`B-SI  Ayԫu#goB1 )@Pvs^ꂺeꑫ}@@6rm^Nmꖻ&]{ﱏ>hS3  @F8KOEdW@@7nC8/"e X|,r>Q  Ce&T@@ HuAP<2 @pHd4rx 5@P22@HI#,A9bPC@X|#@@MF]!(7ǩ  @A9날yd  A١h+8@`G9k߹ed  ;)G|YrĠ4 GF  BPnS@@ r>A9(@@!C@W q*  r~A9s@@ %vSAi@ (c 1@ (;4 t" A| r>Q  Ce&"r9VD"tT@@ 7|Le-AYG!y/ |0 @@rxZkP"E6+mQiו~   A9rT5(k'Ro_*_{gYvY#"WZ;zbY."gR-E@ ('% -=/Sa&n"GDf L(@@A=7(k5(>M~ED^}01  A٩ݙ|Giiւ>ԧewfӶyFN!.!  @ٚ/"RNjH5/^&"OT^.>gnw[=/n1 (@Ṕ[E]ПE"rrt@ȤA9&]")5S z7@@ ( i"2ǷɯB4)OG@l ;A&gw>9 8&@PvlBjW8@&@P&]J&=g@2"@PDUٞLz n ݚzz_v@@ @eEDǝ.?@(RPԴxĉN688 @ss@kk'N C ! I "(?~sn^t 5k%mB sر.22t]/&O<08886cD  @.?K%BQe׵M! @#y FV  @N9" \f '@PNϞ+)@P@@&rM\AمY _9 ʹR e'NU (>@@ r\#Rr4 e, 37et@L *(2wቺ駟v9t萬YFo/ݻe˖-2vlt;s,_\/^,W]uU#]LJׯӧˍ7OT  &(k ~eϞ=2c L_<TO%(@@NB徾>or#vbNo'Y7m$iڻm.>]W^ֺuwnOCEd֬YrJkk\rxGyҤI^/oqcg̙ / EEǨ_O=w\_vi4@IAY×]Sf$d^>ke۶m2uT/0^zq5x;v5>{l-rwyGuqZj7ps=^;:>src> 藶4ѿԟre-/!mcǎbL| 5s0 )Pl @.١kos޽{Gj+0C}7;mjj6mڈ][- fU&j s?(KO~.\pxyfZG{, AΟvNC@ vAτ94%>L9-/'[nQavP8>ڿ mvm+e;|9?((3&3~\=ƔQZ6qWvep/WLPg@@NBr5傲Bɓ®wR;r頠l\c2!+_Ds̎r?Ŝ "(]٠^莪BP=W]l.rAex|]lۥ+ϔQF9qE@: _\>fZ~a׾+CPم^ֻ^-ta?seS녹76jw+]CfܭҎӧ 4us &Pb ;vsky(i#ZMP9) " @A9eݶK_}f|Kn`hB!#!FPnT@@ A9 z/c izg>|ػ 6m/ zw1"\ ߿k.Ν;\״w=xOгǧkرc8䛾XKԞGy A9Ģ@hXPCk0xʕn>!;5k Bu>Nw˶mۼs?~<}]wyVcL4iD{5xcͣ[n%T{!k:\# @p')bԩ#{JovowSsr쿮z~AP &(2-+Gg{/\6(i/qMk`@Scǎq.awNs/lewn-V:hڿCvGYwôC5qq0 )@PuVq=} l0qFٹspIFؠKMMqP0^eD# {fL:ADb5ʕ A\!嚸8@ (za¾3abҥ]!Lجlwza=[s r$Cyۆ&w0wۨ;v ߖkzװzQġ#(@@h@^ZV0a2u Q  3.޲ S a9c'@@ r"\$JJ/Ԥ-@('@PfmdN) dRi+v ŞF @R夤Nd(i@*Y (gn0  (grڊir# A9)iA92JB@^4779vXK[[3'Oɓlh @r{{[===3͛7iTqF|@@@.rSSӆe˖ݻy1LVXqv֭Vkd@\eP---o=z ז\Ѳ)S  \!"o3@@y 2~7ڵk\uȂ%KN<߿4   meU윹jg{lذAMD@2$,"looqSQYꪖ[tvv޿;}}}eo@(͉a;wKZ`Yf ḷWwvΝG=C@ ʥɛԴxĉN688ؒIZ[[8qghhh7@)P "\(@@ *": Y (gmƂKP<2 @pHd4rx  .GF  BPnS@@v[F ) |ė%(G Js  A9kyd  A١h+8@ (c]1@ (;4 t" (w ; @R`G9%/KP@@r>A9(@@!C@W q*  $@PǺ (c 8$@Pvh2 AQ  Ce&"|]D Dd'"UC{   (gsI{"2$""r/""?Dd5  Aٍy[Dl49   (gw5h@>&"c!&gwR9 #@Pvg.Wz9@ (g{Yػ&g{.= 8&@PvlB*Q ur   $@P]O&#@@wE==رcW}S?88!A@)@P%}̘1n%Knܸ5GˇWYvms~C  @:R: &lꪫZ֮];~v?<k?U"DJ}  @fOW'NگM\~}_+t_|EYzɃ8q>y6 \K/S6lhXwO'V:Ǐ|8@(Aٽ\r7Z[[/߰a_W#O?9~05NC  @L=\~}뭷[Z^9~"Fla@@ 'n?]]]c/_X6mڤw3f̾'N< "_bB  &S]jժ1_墋.J7gΜ˿|\KK%. 8&@PN~Bښٳ,_}7=^{C=4m۶MMMyܹow  ) 47tUV˒z+_wQ}ѺS·<@@ʻ??]]]=6p5k֜~p_뗷7"  (;e7̙3nݺusj1S^O}JUK@@583&MzpԨQW[n7Z~GԨQJO02  pAE';{wuu\Vrtƍ577e ?{qBo|C]t_>}Zw,Cfh  crm=z_ }ҧ5wfOG}o S>, CF@ +O|.Zկ~U?6ndo˺u>|d``@1p5@@~ry;Ə~ƬY+_g?^ziԩSEdgI> d@|$i[[ۃ9^ۿltW^Svg@(@Pw|WW? k?=ȑ#BDȅ  PAYI&}K.4 /\>mDァ}q O#q.8'0iĉ;N:5mppŹҡZ[[8qghhHQUgß &$aR5WueiYUTܮâ"JSH&$ DQXP&#ݕ.`XQZ3&B&ē̽wνWmHΟ缟3gysYVIvvvv]RRov3rrrVJm۶jkk'`AKR@tc<rpii)"y>wO>EL  \x~5iҤ׮];X?8duvv.#DUb5 effw [8Ÿq-0;LB̊ӧ!^z>m:֭[ԩSFG74@߾}z555.4(++ =Swo`N&K^{Co'N=$Hzgo{AICaM޼yk&V oM6 "|gNNNlMo„ rs.\^^{ﵝ5pHSy&.RT~{GGTۂA(vʷx<Ç/ ),,4 Ʊ O>,aYawm캙Ƿ :lEƓ÷~p7ӛVPzB(X +60գK|x([~EbA &e5bUʖdP{^w>hLagO=w_~;A m$MP60ƷB!Cx;::~dɒ M_~V3|6%寪#33󵶶6.+MA@uʪ{ -),%P 8pq{{C ,zGegg[ 9^bEOppDyc,//X6 ͢mƌ~^Aܹs;UUU4bĈ:#>Z{ϟ /@cƌ ]/yWˏ6inDD>b-b~;&h/q<ŚdsJZv-};ߡ0#O䷳?pw/8"k{n<|~,݈Pv,BY%+ykXh-[GJ6i;ǗǕH) xߏ%9ߨ;a+XLBb*NW`S2ʣZW_zAs̉hg,)yg‘`A('9YCQ0aBX`/ eabH}z;}CզTF#XiPUAEOiaA/5`h-=PcDjH:E{ԓ,ķi3DcBYF2˗|.뉎DFGC na=nIoX=% `Pvт%fZx@ο2G9ZW.8Qf!Ybiڈf)rjEE<e 3'GY#rUL9r ~i%%%wc^h(ˑhBɓ4~hDY>S6l ++#`"PNzv}rW()n[Ȁq$+JmC(F?dC馛zެo~q_d wMO !o~sN Nj7BꅶX_YE젭!Gš?-R/z* GK[YCOD9|r F"}!U/D]iY( q̩#wW~=%p 7xS*U{g@e=zGD/(=F:777:Z jiiNJuP`jHT(2dHw݁K.\|d[h"6&?9~mɳ~ů9(ZNA(v"j 渄2;;`/KG2F\}F/pO~EszJ{r&2/ZJf|>裸8@D9:(N ^v]DĔ.X(+cc(CV^ݣRT{0:1r;.)Ԗ 4H]HeI?}纫"ErQ NLjoeJEZ^Zƈ(z .G}E@@?΍~饗BP_в7BiShC4h^FYC|%͌W(+F?73%H,cY)׺{@Ge旫EJV?_nG(kk'[&UNOtZ@(hp2!KecyjGksEn& ;wQ\K7QqD+Q z IDATe1ݶm;v,\K^juFJ7 VNDc+"ʑJj1^XP e19 @tQ6qxhBYDGV QC(.\z(%vv!PK]@a'2(}LݡC<\5- vHE2B9Zhk e^cR7Y IBz-||b$݋(,++#"jQzΝK)/IDW9 >͏vbG>+\IL{!`*GSmm-E[+hѱM,3u(s?G|^({ׇ3|rjGXXF-7& ,4PNH,֕;`EO7G}СCYݶIWs4ϧM]_sϞ=aKKK{仉!+xg-K@"]c)"mb\?fTgT<6qD>刜6q[?2y5ԑ ["jcz/_z'\':::Q[IyPd({pFa@k @([OH,?YYY3-ZZp!edd8g"SQ[qr~ܸqQq]V!EWղPEYJDm ՞֎&-?Pkڦ~(Դ͈>'HB8 5?}4\C/?~>Mh0tgPv_Zr\b٣ZW_zAsI)Tl >,pq,leaBY\?*Ʃ\0gg<-DRb%1zi^a>!$> DbBS/=rv|嗜Os( VA([Y@L,;dzr]QUUȂe;`X")GYۗ䛾ٴ'(m'r,OF(j}Q~9<@ޗ͋IA 'SP6/O+Xļ#[\Y(Ph$# Mٕ/x p U7gZ`Aף>ڏD+V|'gddԜ>}E򗉌> Q @(cs@(c8BYdȐ!|mK,[8'`A ߦWUUՑZ[[>6g6 iOB9A(c8BY{^w0_bxꩧɾ}_.!߁ Mkza?J"Ŋ[C~_)ZB|ɒ%CoobX$r}r S`0 e-Co>}X0ׇokmm/ ynk `s6wC(AcDBY0>||_aaJla|>_6O>@ mL)@%]eP#''gٷKfO0q‚zx뭷kmmm]DD@ddd3srrRgfN)0twtt L! $,dee-k3*++|6R@ccc6z *@ x<7oy5פ;]?0Mv(J[X8M( =Yu|饗:q鶠nJN2okҍ *۷oC=ƥ<eeezjUWWbf `- e8oׯc%%%_-Zh\`-]̖4>,|^]]]Nq^{c \ѣG3~a4Z㴋!Է>Nʂy ZryzGn}t*e;Ʒ}jժ xԩSDԜ201@nwifF뮓7o KhXjH,8"''czyyz·-]tfff}kk+YI=Ka@$3|PD߾}ue Q\x~5iҤ׮];i'n1gΜ;v8}beJ |UUU5d֬YR_~o;x6LQ0@ )ywIIIo5fhN Y߿m=ӿ B PHo[o?UUU9ӦM3 5mz@goA @Q.۷ӎ?~IGGGVhesWW+8 ͖ ç :tyAAy|_f[>_7պ1#|.Y|ߺGz%oocgohPrtzY7\O"^7|D\"XIB96m`?٠#FX[?˼شi/%U^H+ܝտG>=Xy睧gL˖-;][[̙3+'iK1vhѢ ,Ap@x zϬXkϟ{YHia`)ew7YYYfk,$ g/ ac peu:袋%O۶m _?G!@@@҄Anno~UUU9'Nm~+ZdIC---|Fݝ@@@Ҝ}6@1wWfVVVݻ}ݓǎ[LD?2a)ABY ?cAy'Oܷ=jԨ>W644t8qKDO30ڂ|MBٞ!os\+^:aÆ>go`5ABY ?$jЁ.Ͽȑ#uˉ5@@@@e'~Dt;iQX "ʩ@C('#9 ) C@@@@A :%NQR/⤆    eoe+PN$!" <    P6d PN!|L    \-}(HBYAir@@@PCI6jցؔM' lb    PV)q>DՋ89BB[}qdA a SS8} lb    PV)q'04= PR u   6%lSIfC(߇X tJ&A( A@@@@e=oӅp; ؋3D_:×X" qDf#eD""!"UDsL4@(s;dD)DMDmDq*<":nϥjP~HĊ'h6h/U&2 |MBپD4PZ)":d:CBY_$b6hr"@@@"Pʈ&ۗ@@@@1ʊ9$s8\z r.    G%lgb   PVZRt饗>?/A@@@@'e{""QQQAᬋIv(P:גHޱcIX'C, A@@@ e{"Y,bٞ΄   jPV/(!HX    6e.HX3a- l. lR @(a]\"bN   jPV?l]B"bY}B @(ퟤD2IJ΅u   jPV?deu @@@& j:VMBY="!s4,PZ1U$C,lX   6eucHXV@@@@mjR a Sd;MB9IHXN1; S%D2r6fPrjHXN&   jP?Jde7fPQZ$C,[0 -D2IJu3MBJ$C,[)0  -E2IJ3MB\Z$C,90: #D2IJy#MB8J$C,I0* #E2IJ#MBX8Z$C,Y0 OZde6 FP1I+ l̦(   jPN?i)!8@@@@m'E2rrA@@& %v>&MNJ    rb @@@$_ c0XC D^:  "Y?+X(IBY[ q b9h   ];-   )%?Db@@@rёC$! @@@,!3D b@@@4碅H6maCKB'OdcWYç8s̙dاOK" HpC,[ہSA(;ЩX(HB Θn^{<OxENs҄ o׵JDuaB#Hk)}@,m'W|ᇴdɒX4ֳ0e=@қ@ eD 8f&SoDYxz-[zDx,'9׎/!T#Ѽz6|&QCoA M k }X6@8nM `r )=[_s5G`/O2 H9YkDɓ'#[o;ߘf(/-R/DDY[.^ ɩymHBنN '${rXT.Bc]]]\B[DTTNVz!E:Õ6nz+8QRRB~?,9,$IDz"^8ͯ}@$,e[ ƂBIBYX 6UB-eqs@$# q5  `$ 2 gӂrZ023S}{hH'ϜY0*8#݊EMBbctN#4b= pPXd ? D1 @(;X .!5 l!lLdN. `t˦msH6/FO+in,@("!1lhL. X'I(C,u "<9m @(pdPXNfX"Ș" @(ױf PXNzۘ3D9\1*2$@ ]2r.f = Hg Ȏ1D P1$$2v$@ ݅2r.FX 26$@B/wѧcd+(cPF@( b9 hDɡ$DB9!l  {;vA,8+yID3o&  p2$@B\h l$] B;081@Pie^&@Ő >Nh =@(GX @ ~3C ؛bـ D1$GB99~   {wgC,ԣDr!lW  p A$ MAxh-$ G"UD1~Z "?!uH M@\YDuQeQeQ?"#暀A@ !r fo(&ǰ #K!%vɉo$pN6h1@PND8Bo0@;Q.sDT. f9h1@ZPNi-IN~a0WXADDԟ^3GKV@n1@P6i)!< "z-`rpM64Hƹ:2DqGHZBDÛ& OBY?+=-B,C$ jt`rD9o<2ۃ`: P6(9Z,C$atR79\ J"r 6쁆!GM7tȑ#*ya  .Lq7rXH{B(k@_~`^ѣG> \XCBFqXH6oBY4o]Gl;v>/r% QQQQ[cc4@LnGeds7!u@BUXXx c̙'~Q[osHG{b" ceҼIAnn+Wp vniituB#H#8ۖb"ٚ͡ceҸxzy8#g͚5z`O퍯7Z @([_[ed6 u@J&E.kk]]k֬Y #X~=B>@FBZB,C$[)tR6rn**_-=2e b"Zh   lo3B(뀔fMy<s?ްݻ+b60PNɩ :fP)]ddd>|~vAAnjjZm~ iKB9uWJ,C$n#BYthQF644dgg䶶6ůL S %2Drj7!u@rxW^^ &۲eKUk:u={knnq!<  {"b"9@: 9I5cƌK׭[7uC IZ=?TPN%NXHV:PɡMFQVVv%KRĪ*F":2C01XLBb1T,C$x@(&333ԸKJJRZ*++ O&)7 -e8yo޽&O ˈ9ؙ3E,C$lVA(&K 6aѣ]ҁ|ܱ#G&*e a  $$P lB|)v?_PP0ܞ 8z(_LT =~ v$ j;Yu: ٹ>vث}>_RB_y@ @(Τ2Da!H6m 6 h̙'~\kͮ  %l=XHsuX  ,..r6 .쬫;·5}=@}A\b">ai|O>};$1Ow>7o^b#(k͚5z`_UD qp. r?mDS;^ZWW5kVj-1aSqqq( M!" S`He (XH6Jo~m+v;+ГO>I@ @?G.^?;DF\.W֭[]EERvÿLb;sX@:9{z9XH3uXQ(s=8Ѓ>HO?4g$d|>]1@KDka5 #zed:R媪*Σo2<<nQ={ɓ'QGyjkk^ |=q]]]7M?>͝;7s~8߲e ":'ddd>|~vAAA=ݴk->|Ŏ^ HGzX,WTTPee%dr(Ge˖ѡCS/]d i;G(s?"LT__.9r$aÆ3R/ܟ5!';;[_'jkk[ZkmmA@Z6k6eȪ1nԈH`駟vWtY4ܹ3|(sG9>oaUVu^}~a:vyt^D333ԸKJJ= ZHʂ퓉h&$PvFPvuEq3ΞND7nHӧxbشiS6HBYEor7]}̉'o"޽&O ˈV`tPvfPvQ 6l~CCÐѣGs)\>ؑ#GVs} M  pegl egQPvR:|AA ߟo/ѣ|1IkSSS}0W!` @PvPv!mGdz}رW|le#45 m|r]`ʆ`TvW-d*,,|Æ 2̜9k-EX @({_! ?" rssw_re͵ .쬫;·5s@  E"egBYm?w>7oږ:5kp@0,"X `C6tZ!GeuXrչf͚lT\\ BSa9 6 l'0BY$7SY.n֭"nⱒ)SX.&V΍@@B{B~DDY=?x<^?~z֥E{@ %5il,@@ 8 o j?)SrÇ_X:  `e+(?S9k1ܟ5!';;1]4mmm|_---MBl֌!e TZGޕs„ lْeݴ)SN=gϞ}\>.O_x@(CKݶR_#(>F5cƌK׭[7hJbs83| ! ?F[kGQVVv%K̟ 3Bjjj>kmm2(33?N^SS.))I5aTVVlooLDA@ egl egBz?N'7nKPv!M>vث}>_2y6 *Pnkllu C~x@JiǏ#1~YYYlz>PS*{'yf*,,|Æ #؁̙3Orl&vk;;;.))s7ƌC999^ommӶmBg`0أ3639~,Y\\<|ʕ͙J`…uuu[ZZ&U]'pդI.^v cE9sNر@ DB~d13lǻn̛71-Y^o  ^[ #mE3gŋn{.jZv@ 0 B9;B9!|Yrչf͚eܨɖ֯_OšP(4|\V[L6m/2e b"Z& `233;zh- 7ʊ8%I3 xw7>x<^?~||=1@KDk`,T}~衇Ԡ,SOP3BHAU1_X5|삂,455qÇѱ ֏Gs7oL]$P՞~qC(삐Zÿ=9a„q[lɲsaoj L:={577sPj6$pljpq,Ceot{<]3f̸tݺu :C I5QB%N+cXJ;2B*)|w#htNNeee.YDy'@ TUUQMMg72K;ʉKǞ:s|i%T&fffnqm;3@mm-'nS'KbC1cF]y+:;C^#oĈtOʪyDm{ OND7nHӧx@86m[ol2ndFbO?M]vYx`{'|hdDt);w.M0B\ BY-$c T2 ~]}̉'9XhKwɓ'2"Um|tӳ>p;¦/]8=I(9:sN3f ׇE/BKnį{'uօ<EK?ydw[CDy}r]-cp5ka; D{DUjB*Zk ϖ 6l~CCÐѣGϋV89rd5Ud|oFzW“yYgZ">%*$zjW1Ϝ9k-5n"DJ=ǏE)"]r%=R/.srENS5Db}͚5lٲpNeP—~mzbE6?<ꪫQNdӥie8>]s<{%߂ܝW\?HHBY!)fԦ%g-!bN rXpag]]ᖖů)I(k=ʇDo݇='ovśJs0!?b~-\Aua>cFsvC!L>rԭ$݄xzyC=rIDN BOvcǎ GG}D-'D'_QvKWSNqv%",ڹ*(ť"f_-Bf*>g^[*YBf+ob}qK:MqYiӦ&~}E7:Z >pyXvp;~Q\\ BSgD{rv1bo@( ߞ#2=&=7+K9Stʳ\.W֭[]EEKFhsY #rZ1 a}ʲc6_ڢNnoBD`",X4߈}h?E~cM@tƍ nGSLa\_e+Sy.*;SA(x<^洀XވʢI+HX<NA'G$GkqH1]•kPSuq:n7"Մ)7$V~M(k/و9 r_pΣ%w^ ^"Z8\ ܈BCErۗ ﶝC9u+qPX5|삂^)*U%)Z-]!Z:ZڀB9]<GxmlP)!ZYD"ʱ"G7JlkOE{(G ĵ>bGGǂ#8B(;ѥ2/ ̿ݷ&ukM.DVɱB977gF*lhh͕cr H[q{"Zy#G쑖!D`II 8q/K6ܛ] (s2|կ9_.UM Y([dBaG=d ?p?rgG"9ʉe^ _|M7v !i,Yßcc(Lt0>!gSͯMAVSXpgBjBY{Zkιz[;|.ϴo>YB(;Ս GH+?}wuWNMMݗA@IE]N8D43Pfb\]' B#WnsDb<8jǚ_UXR% SEBE ={=s e- }# w9Cp ,xT e;ܒB9y|(3(BeEarDGvث}>_J bR2gѱʵy,+R48@@eBٮ;ne+O`tNNeeeSAhN^MMg7сtZ;֚BYmcr~?@ "&H/vtt,&H9y\sMCz-6m!eEYqCsGx>=~xG/޽{J` њG@@߾}z555.pqSO= B~Pv r\u[nu7*F5GSL Bb"ZoxU\ѣG3~K.;B9y*`j\.ֺ:׬YT XL`T\\"y ,96m̗_~yVK뮻Nn޼yC0,Pv!Gxnz͛g֬YC^7 ㅽ0Fڊ*ϙ3gŋme7=@uu5]P ?Pv.Pv s,..rLQU%pκ---\IU;a \x~5iҤ׮];i'[̙3;>@DA(Ϗ,Pv/sd*,,|Æ ͙F`̙'~|Hj4λKJJ|ͮ1cD~fq~ڶm[Lň(x,Pڦ-dz}رW|l ԝBWhkllu ub]o߾wN;~%Zeddgee}Ҳ"@BB~*, v/((s-SXIѣ\#> kܘ @y SegaÆohh2zhfL8p߶wȑ#08@ZPv!GZ%nf'Nvff8ݻwɓۃ`>HKp;3UXO`:mܸq#M_#M6ѭʦ6q @@Mj%^ % 5kjj%%=; RYYY0@F mB(;ÏXEy%K *F":Wg4 u@Ae8 &*O 1cƥ֭in`ii?|4q` &P6 B([ 9+//o mٲ%˱¦Nz|Ϟ=͗A&s0 B9Xh ٨Q r{k[D˿~?@!Ӕ&H/vtt,HO X5 &n|pŨ 0x}>{"{+@KDkRdHCp:3UI`ۺuHM l)SBP1wR4 @(+LPN@\.ֺ:׬Y膦X~=HBDdB_Hr"O`w>7oV؊֬YC^7 9W1`@Pv!GB};\… vniioM\pe'xB~*A ;//oWaa6llc̙3O"6XKAHB^Pv x<ǎ{v\6\MSCWhkllu  @ @(;#Va3n~?'??f֫cѣGFrkSSS}0W` @PvPv {X2lذ CFmm{ǎ9Rh s@(;cS@(;ÏX} ۷gN8Ѿݻwɓۃ`Z<=^ @( m&pӉhƍitO,6m󏍪2i* R77,Ia ZA5ٵ(,[ CQ @ܤB Ll14ANts3qm<|Ν鷇q8  e5B FV9jm6mڞŋ%V. JPV#j^O`b;yeΜ9zvieDtXYG 1q 0b,^X9>Leee,[9@(ne5/C`fsWWW;VZ׻vjtEe# %F!Ո#0|TVV6~5k|[   x Ո#0ϊ~uȑE~x}:s֬Y3/y "՝0@HB90S8h"7QXA"%)S$+Dtرc+>ǏSII ׇU@GB9yl=n"#hn1ٓc|yrٜNg'nZ/  Eȷ!Ʌ{D4d@)999g+**[~}l޼\./A@  S <ӅfMN0` : p8>+--}~j{/_y^#=c>H'tҏn9lr<1蕀%77iƌ9qDhUl^p斎כ00NYU^> jcKy7I nmE9ټ79GWWoy}rf  e)K{hjS=A('Q2Z;ƏO86n$uƍ{ I(Oxn߽{wB 4PLej=zu ]3gP/iT__O&MJ ^5qDzׂݻw}]p [^v݄ hCҔ$~)ѧ1ݨW9jm6mZ,x"{^^+ac 0(SeV{?8ϟo:u*4dI.]SN5~?c,Z2G3f_~9 ӧyIDATҥKu/ٷ 6Ν; lb;yeΜ9q?n,X[FDTʏ9ϝ;ɚ,c=,˻Ϝ9}o߿e/51b,^xľ>|X$/ "  R^^^n:f>wlB555W^dxBׯ_ׄ& ٳgk,;::4hD&XOpI'|X!4x *((X8Xʹm6 #x ZTTDG|x'N7|3H}eNdy.k{r=i~ᇵǍ|E<󴶶KRA87`n9 e>l6wuuc*n۱k.fݸ@&/ArE,YY0X( |饗yB 1*B+2"*˙Vq3˖- S3wPfbE;{!TYL,عDC&˙cM|g=;C@Wdv{SYY۷f͚uuu7|>o}@B@_"n233nooBG0===Vt\z_Q_x-{`6*PaP , ꩅpKCĂ&=g9)(Ce, U/;77_9r䧔ǢE~xbʻvR򳏹9Ӆu?{{{ygxy*^7,6`̙:#p9*..6CCK.f(r,HH,3"̋"-c!‹B544 NIX|,f]=\|m\CիWӝ;w4 GOFG9fK~~~ mmm~Oьk@@V۷3Qvޣcǎ ެ7pDW.zKIB^(vvRՅƍscc)S˗͛7?rhY:03%20`tV -rD-^ϺI2cql6צM2z~ ׃Y *61oe]FH(s^yꩧ>o"PN1pL?} e7f?@ rt ~e@*@(2H(4`ʦ ; @(nj 7O]DSk}oӦClo҃>l-]0~@('(5 @(WP,wzl37O: EZ Պ)PYn,#hBhJ"?$KM6F&r{{Y'xkJ"t>!yӧ咒:vfO4U-{xgF&C MQ'A@ nq#&|lٲA[n[-*"[ZZd1ggϞc;lwd B!p@&5*\?YYYaz駩U\jeٍt*e#e&rv$; n  o CBB3׮]J'{9M(`bp\,T9_WP Qb!|p\(ef]h@(GC rxgY4޺uKʼ=\4BVt|ȋBŰ\~npB@,EVY(|OSSE[~4Pmh`X$x6%/A  l8+%RL3iIA@p 2 g ^  `a(J .\;a|4tT,x^!ϻ @lT #;XXr0N7n b>[p|2PMDoѮD2X `p He>| ?W_}eh9,Xn+{΋ yv~٭P,#j Ɠ}y!F3,+|L[ . @(2,0 @@ ʯ*y<m*>8<|2/+o%o%7{`vZٳgM Y-toX%-_}Piy}Qaazq\;-m^xBP󞾼n9BJ/@^CDhԀX#X@@j@(!1b><իWkXtV YumE[a`Ci~Y܎Xt9裏*߭؛Wn}xY׶mF-Y9{@( ̂."ʉg|  PV0p @  ʜ9޿eHWʢ F./șpCK2x-Ca~+Lĉf9y.Ր[ }\K<ҋd(u§(r߯p @@@  YYYf]/"TS ygHttvwwk\.W]7eFEYSS2tA9CGOs+ج!,|I8kl_@4DJ,l Ѡ*e|q8HH ET8(`"B`A`iM0[!KǸ|NianVXp\ KXDNNRmKcEXcJn#;apache-log4cxx-1.3.1/src/site/images/fix.gif0000644000175100001770000000026514721727031020154 0ustar runnerdockerGIF89a-H/Ʊ8)&#騦rT:$TRTxwv!,b9 ^+_'nYE1REAeWܮQ!{pKe0`!5 VJ`Q7  );apache-log4cxx-1.3.1/src/site/CMakeLists.txt0000644000175100001770000000373014721727031020172 0ustar runnerdocker# # 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. # file(RELATIVE_PATH LOG4CXX_REL_BIN_TO_SRC_DIR "${LOG4CXX_SOURCE_DIR}" "${CMAKE_CURRENT_BINARY_DIR}") find_package( Doxygen REQUIRED dot ) set(LOG4CXX_SOURCE_PACKAGE_FILE_NAME "apache-log4cxx-${LOG4CXX_RELEASE_VERSION}") set(LOG4CXX_SOURCE_MIRROR_URL "https://www.apache.org/dyn/closer.cgi/logging/log4cxx/${LOG4CXX_RELEASE_VERSION}/${LOG4CXX_SOURCE_PACKAGE_FILE_NAME}") set(APACHE_LOGGING_DISTRIBUTION_URL "https://www.apache.org/dist/logging") set(LOG4CXX_DOCUMENTATION_URL "https://logging.apache.org/log4cxx") set(LOG4CXX_DISTRIBUTION_URL "${APACHE_LOGGING_DISTRIBUTION_URL}/log4cxx/${LOG4CXX_RELEASE_VERSION}/${LOG4CXX_SOURCE_PACKAGE_FILE_NAME}") set(LOG4CXX_RELEASE_MANAGER "ASF Logging Services RM") set(LOG4CXX_RELEASE_MANAGER_KEY "077E8893A6DCC33DD4A4D5B256E73BA9A0B592D0") configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/doxy/Doxyfile.in ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile ) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/markdown/download.md.in ${CMAKE_CURRENT_BINARY_DIR}/markdown/download.md ) add_custom_target( doc_doxygen ALL COMMAND ${DOXYGEN_EXECUTABLE} ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile WORKING_DIRECTORY ${LOG4CXX_SOURCE_DIR} COMMENT "Generate site with Doxygen" VERBATIM ) apache-log4cxx-1.3.1/src/site/xdoc/0000755000175100001770000000000014721727031016364 5ustar runnerdockerapache-log4cxx-1.3.1/src/site/xdoc/building/0000755000175100001770000000000014721727031020161 5ustar runnerdockerapache-log4cxx-1.3.1/src/site/xdoc/building/index.xml0000644000175100001770000001353014721727031022014 0ustar runnerdocker Building Apache log4cxx

The project supports different build tools on different platforms, have a look at the menu to find the platform you need. If your environment is not covered already, feel free to ask about it on one of the Mailing Lists or leave a bug in our Issue Tracker. In this case it would be very helpful of course if you could already provide some patches to support your environment or at least provide some technical details about the build tools, compiler etc. you use.

Autotools will link all tests into a single executable (testsuite). The cmake build generates a number of executables which can be run using the ctest tool. Some unit tests will fail if sed and gzip are not available.

The following table provides an overview about the environments some of the team members have access to and therefore normally should work out of the box or at least were used sometimes in the past. This list by no means tells something about how good the support on each platform is, it's just a guide.

Environments in use
OS Architecture Environment Compiler Architecture
Windows 7 x64 Win32 MS Visual Studio 2008 x86 and x64
MS Visual Studio 2010 (Pro)
MS Visual Studio 2010 (Express)
MS Visual Studio 2012
MS Visual Studio 2013 (Express)
Embarcadero C++ Builder XE 4 x86
MinGW gcc 4.5.4 x86 and x64
gcc 4.6.4
Cygwin gcc 4.8.2
Windows 10 x64 Win32 MS Visual Studio 2019 (Community) x86
Debian x86 Posix gcc x86
clang
Ubuntu and Scientific Linux x64 gcc 4.5 x86 and x64
gcc 4.6
gcc 4.7
gcc 4.8
gcc 7.5
Intel 11.1
Intel 12.1
Intel 13.1
Red Hat gcc
Mac OS X 10.9 Mavericks Xcode 5.0.2 x64
Raspian armv7 gcc 8.3 armv7
Ubuntu 20.04 armv8 gcc 9.10 aarch
apache-log4cxx-1.3.1/liblog4cxx.pc.in0000644000175100001770000000204614721727031016706 0ustar runnerdocker# 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. prefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ Name: @LOG4CXX_LIB_NAME@ Description: @LOG4CXX_LIB_NAME@ C++ logging framework Version: @VERSION@ Libs: -L${libdir} -l@LOG4CXX_LIB_NAME@ Cflags: -I${includedir} Requires.private: apr-1 apr-util-1 apache-log4cxx-1.3.1/liblog4cxx-qt.pc.in0000644000175100001770000000206214721727031017326 0ustar runnerdocker# 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. prefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ Name: @LOG4CXX_LIB_NAME@ Description: @LOG4CXX_LIB_NAME@ C++ logging framework(Qt support) Version: @VERSION@ Libs: -L${libdir} -l@LOG4CXX_LIB_NAME@-qt Cflags: -I${includedir} Requires: lib@LOG4CXX_LIB_NAME@ apache-log4cxx-1.3.1/KEYS0000644000175100001770000003477414721727031014411 0ustar runnerdockerThis file contains the PGP&GPG keys of various Apache developers. Please don't use them for email unless you have to. Their main purpose is code signing. Apache users: pgp < KEYS Apache developers: (pgpk -ll && pgpk -xa ) >> this file. or (gpg --fingerprint --list-sigs && gpg --armor --export ) >> this file. Apache developers: please ensure that your key is also available via the PGP keyservers (such as pgpkeys.mit.edu). pub 1024D/2E114322 2005-06-11 [expires: 2010-06-10] Key fingerprint = A1A2 B554 6D43 31B2 A41E 1C07 BE16 C95D 2E11 4322 uid Curt Arnold sig 3 2E114322 2005-06-11 Curt Arnold sub 2048g/209ECE57 2005-06-11 [expires: 2010-06-10] sig 2E114322 2005-06-11 Curt Arnold -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1.4.3 (Darwin) mQGiBEKrSNQRBAC4J7udOBoC5+gVxBaPAbjXfnq12l5Pau1WD+UothePNGjI2hOp +Rnzikk3ISgyrjiX3A8ScZYbu3iXvMpF4zknkGLdmerpf4Gz9xGeushwun+UFaFL MX5u7LWJo9wDKzbcJJit1j/qGEg/HRp5fnVYCh0/l4dLansL60NhxtYdxwCguu2e wZMZFroaiIXqnce7+cGDRq8D/2HgKGtEJHY3z8OtUqncWbW+RAQqdcT0Z+bMB8o6 0UCHxUoJrFS1lA62qU3kcZ8ACPoh9xDW4X47EgNPELX81alymTI5FdqiDK7RIwzE JlOH/8JJgC6eSwiUXJ0cOJwpMonitcpMLouxuURuPSpfE5b1mQ1gFzN5MBL8xlZQ 8IO6A/9qWwyWyQBoJud0RDIsVRosdoSBZtw9PHsURgsqfNsS2NXTWK4HjxExw1KO AXmRlALfrH8yAShy/AyiUrwlKHG2WPTe6Etygjlr4dIxqTiCOoi+qv+H8SXW4Qy3 SnyozJ2RlKoYG0oDTbVMsPhOFdytHjConDLL9vS14j4kN9zWB7QgQ3VydCBBcm5v bGQgPGNhcm5vbGRAYXBhY2hlLm9yZz6IZAQTEQIAJAUCQqtI1AIbAwUJCWYBgAYL CQgHAwIDFQIDAxYCAQIeAQIXgAAKCRC+FsldLhFDIs5CAJ9roOB39ithHoCLaDJx l14efLwgNgCfcDBYutNX5W627kCeheDqhQbTqTi5Ag0EQqtJBRAIAN8maiGIO44S dc9Ep3CAm0aXDeR8IQ/F253WcMQtkFBjeHEDd6/+EFT52vswMI6ZJDVV/A7pe4VM XAdNutFmUG2gy9OJOu8gMuO3jTCLxUXyQYNF/RasOAQJgc7q1N5QgKtXVH2InQ21 vHvlHM1fVe4rYDPr4JL2lZHe0P8kTzeQ7jI5pQnfYRJmS8I5AMQYFOiM48Pd7Sbs Wu/rym7ikcmKUe6ZE59hSioneVP31CDMNRxCAQJVS1mZxTozsAEoh+cvmRjOD1Es 0iXvu6Sfe8+sLRL+7CNUZgixE1UFbdnNxuZGlG9qs0LGP7hDWijT1/Y4SHz4ovXx k0oocmFtiLcAAwcIAMbY7K99hLAFVaU2ukxCSp1TNPcD+IB3gtpRieKaZvBn/LGe CO+fNAogkw537lmpLk4nI+JiP/xWohyJ9lyEpW7yD4c9AHKNjqvEWD5Bhpnw4qKJ ohQSVQwEeJRsftY4D0jCP9xbgPiq5woBzHWNok3BVaHqLK0fd0/+KygnT+k6cR22 Mus9RsEisXk9Oj5lvC0miDOWof4vk2Ll8/H3xt4CXAr13n5Yj2632HolOHrFUQXT gwc9v5CNIihOQMEiXFxHh743qbsUZktjxeYH7r8wSCV93/QQ4qELiWoUzndpkCRT lEKenucAv6f5qqZqG7pVW8S48T99HwzwqgFX5VOITwQYEQIADwUCQqtJBQIbDAUJ CWYBgAAKCRC+FsldLhFDIjnoAJ9ECOIrTH3adnVLOkHZnewyp2ssxwCgtLjlwZ7/ 4QtL3W5Id3nKxPFiI+c= =9ut1 -----END PGP PUBLIC KEY BLOCK----- pub 4096R/70C9C3D0 2010-02-17 [expires: 2012-02-17] Key fingerprint = 28F5 F554 39C7 1A8F 2B1E 58C4 D3EC 4990 70C9 C3D0 uid carnold@apache.org (CODE SIGNING KEY) sig 3 70C9C3D0 2010-02-17 carnold@apache.org (CODE SIGNING KEY) sig 2E114322 2010-02-17 Curt Arnold sub 4096R/0E434FF3 2010-02-17 [expires: 2012-02-17] sig 70C9C3D0 2010-02-17 carnold@apache.org (CODE SIGNING KEY) -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.14 (Darwin) mQGiBEKrSNQRBAC4J7udOBoC5+gVxBaPAbjXfnq12l5Pau1WD+UothePNGjI2hOp +Rnzikk3ISgyrjiX3A8ScZYbu3iXvMpF4zknkGLdmerpf4Gz9xGeushwun+UFaFL MX5u7LWJo9wDKzbcJJit1j/qGEg/HRp5fnVYCh0/l4dLansL60NhxtYdxwCguu2e wZMZFroaiIXqnce7+cGDRq8D/2HgKGtEJHY3z8OtUqncWbW+RAQqdcT0Z+bMB8o6 0UCHxUoJrFS1lA62qU3kcZ8ACPoh9xDW4X47EgNPELX81alymTI5FdqiDK7RIwzE JlOH/8JJgC6eSwiUXJ0cOJwpMonitcpMLouxuURuPSpfE5b1mQ1gFzN5MBL8xlZQ 8IO6A/9qWwyWyQBoJud0RDIsVRosdoSBZtw9PHsURgsqfNsS2NXTWK4HjxExw1KO AXmRlALfrH8yAShy/AyiUrwlKHG2WPTe6Etygjlr4dIxqTiCOoi+qv+H8SXW4Qy3 SnyozJ2RlKoYG0oDTbVMsPhOFdytHjConDLL9vS14j4kN9zWB7QgQ3VydCBBcm5v bGQgPGNhcm5vbGRAYXBhY2hlLm9yZz6IZwQTEQIAJwIbAwUJCWYBgAIeAQIXgAUC S3t0VgULCQgHAwUVCgkICwUWAgMBAAAKCRC+FsldLhFDIrS6AJ92lpskwBHNNWLw XsHLaFSGh9n9tACfT0dOv3wec7oM+lt2x81S0uqcbZq5Ag0EQqtJBRAIAN8maiGI O44Sdc9Ep3CAm0aXDeR8IQ/F253WcMQtkFBjeHEDd6/+EFT52vswMI6ZJDVV/A7p e4VMXAdNutFmUG2gy9OJOu8gMuO3jTCLxUXyQYNF/RasOAQJgc7q1N5QgKtXVH2I nQ21vHvlHM1fVe4rYDPr4JL2lZHe0P8kTzeQ7jI5pQnfYRJmS8I5AMQYFOiM48Pd 7SbsWu/rym7ikcmKUe6ZE59hSioneVP31CDMNRxCAQJVS1mZxTozsAEoh+cvmRjO D1Es0iXvu6Sfe8+sLRL+7CNUZgixE1UFbdnNxuZGlG9qs0LGP7hDWijT1/Y4SHz4 ovXxk0oocmFtiLcAAwcIAMbY7K99hLAFVaU2ukxCSp1TNPcD+IB3gtpRieKaZvBn /LGeCO+fNAogkw537lmpLk4nI+JiP/xWohyJ9lyEpW7yD4c9AHKNjqvEWD5Bhpnw 4qKJohQSVQwEeJRsftY4D0jCP9xbgPiq5woBzHWNok3BVaHqLK0fd0/+KygnT+k6 cR22Mus9RsEisXk9Oj5lvC0miDOWof4vk2Ll8/H3xt4CXAr13n5Yj2632HolOHrF UQXTgwc9v5CNIihOQMEiXFxHh743qbsUZktjxeYH7r8wSCV93/QQ4qELiWoUzndp kCRTlEKenucAv6f5qqZqG7pVW8S48T99HwzwqgFX5VOITwQYEQIADwUCQqtJBQIb DAUJCWYBgAAKCRC+FsldLhFDIjnoAJ9ECOIrTH3adnVLOkHZnewyp2ssxwCgtLjl wZ7/4QtL3W5Id3nKxPFiI+eZAg0ES3tyxgEQAMiGGFkj5EOkQv6EYFtWvd65Y6yn dpNIbOb/o9SszVu4kO1OHdemWg4OwXERb1+Ozl9NamOvW0ypH8qzFu4rhpoiUev0 DV93afBkhW6Mvd8D459okgnlfb/K7c3H72gHmuJKZkyNmLgyzX63BjgIbpjR83/N RC578BjoJbYCe0bKR9bCE+MxxCQzUO+tcUrk8o00zEhqycmw1B7gFLWL5MAf50h8 37/gbCcv9Q902kYfqsd5I7wPj4SRPnowN8vPlNtiwqMDqCl5rUmCrulfvSoNaJ/1 bEu7L9+/ptontfnr3kMJksGsoPo+Cf8xkGZL1D+80TxrBRf4CILQRF8dm+K8+4ms VMsPccCINw/AZh+GkIjJ+SfQpIE4Rx6OMd6JSmCuMnom4O8ZbJ9QYcuS1uf4r32M C6MQZrENvEFj1MaSZoRPXNdI/vwCKE5Hc1enB7bEHD6yayE3SgIGYVC+YPJkh0Ch fAANRSlw7arrL13UB6xwzAnzhIK7BzADsbGDMAMmIh+rvb6Xxb6iQCh/q7iGPpRz AXkmusLsbk6hMP4d8W5puJQTdy7a4t2DIX//9LYpl+DeYCww9DbXTwIays/WLnpo Jxj8R1G75gfUIC+kvFl+OiIOR7579yw5Ar35DmqG8RIwxW9cv+at3u63WhYwdhqB 4Dm5hujWYluYoAZvABEBAAG0OmNhcm5vbGRAYXBhY2hlLm9yZyAoQ09ERSBTSUdO SU5HIEtFWSkgPGNhcm5vbGRAYXBhY2hlLm9yZz6JAjwEEwEKACYFAkt7csYCGwMF CQPCZwAFCwkIBwMFFQoJCAsEFgIBAAIeAQIXgAAKCRDT7EmQcMnD0FNcD/oDWhmZ sikg42VV4SnaaIGUgjHoNT5NKWHhgeEXWAu44Y1r9X0+a6/xvtr69MfbExn9CJWJ 6vuyY9bpLcNNB49NLxhKD/IEpAUdGYcGGn1+AkkX/Sa7Y2SE5F9snJ2aSn+BctdP JNHgEQxWGXGHAFPEdw73RudqsDUvcIat+uU8H/ZdrXX1F2NiUp7rjHqYvizXgy5p Es99n00gCiz3eKg2l816v1ClDRAufFDj/JHghL4Yx+wUJN0cFBOAZHzDZgtcSUuv Jb2B2f31vjqJ5cGzSQ1KhRIqoIwUm+LYOtuCAbboW9P9GPbib6oavRXRbz/SAoIX BbYGWnA4aYQGT1r/FrLHZOmY6kw2izOPryXXxu1qAblFDc1C6XNHtNWx3uuTE/TL haePHai9N0rJLuJCwHSveY5Lc8LF6cE2sV+kFsyMUwzaxLHg4G2XpnVIx5mEM+Fr Hb89t8rThdE2n+qwUgCzlYgNEjAb1wf/xqUwXL7r/3rwKYkamq7Y7ljY9BTRX6VY XsDEiCPs2XSNQtZfTajkei/WN0/SJDQZfIbK9wPqQXTA4DxZ5qJaTa5hS/ueksYH tCK6pH3L8ov92ZbDcfxwq3u9wGl3GT1abFIfyfX53FXaoCXSi+g7F+a3hv6nmy0E 1zT26YXh3xRIPJ2x8gGCATHsGHabfnrRespQeYhGBBARCgAGBQJLe3TDAAoJEL4W yV0uEUMianUAn1+KjhbSeXIcMrxWK6WaCHojo0StAJ9GiDT+6t4AnRXCIJtob6uZ tN17tLkCDQRLe3LGARAAq9WmSZRtHLuOG8gmYesNeyfPqTdOgak+dgT4nnMIMnlN Y23k3oMIgSBeiYyFMDoTXPYsxVZW24mrMhi9D1XhsDygn534iD94ptrLpnDG+56z 0aHdGjS8eUhEK636uNLT47ZEm8997fWCiqQQzX7UP9ttP9DKLkseiZ97jtN5To+7 n5Kmog082k0208p2jJqVw9aqoeXh4520nRaqiD2QQg2onQLCAz7UH7RllVzhqH9Z G3HcI0RXw3q6FP33XlGNQuxhV9IPna9/43TXHaOsstwtJjvOaPfzGDS7BAmIKZx6 rbL7VYcIheZ+qXuVoRrwb0facxJfkTcLUy8aRQappDxk9FpWByEK2hEsWiw+CkI6 maFoyCvC/io5L3ZwWL3C+7wMZ1Qi8DvT93NbLboxhW5XRZk9gb1vlJSalTMbGNUV tOiV+SbwfkMQX1xOMFbDx2u5orcJ0h9/Ox1LJEuoTHx68nXLB1e9ioLfQPATM+70 JhXGAHmjp8rkY6Jdua0MbamQtUXfJAZv/pJrukWNWmT5UFYY0DNNcypfaqm0l4g9 ZFwwUaraWrMkcsrvmmZ+6JASSwA1a6RwXYLtsMLX0boaUKEvDPqnIbeF3jJnztLN MDWsGeW2NXYfuIaHMTUM7oVGgpDP+TG1IlOQU0lrSbw4Sm3AlA25tOF3jgGZtaMA EQEAAYkCJQQYAQoADwUCS3tyxgIbDAUJA8JnAAAKCRDT7EmQcMnD0MzLEACRQ6Em nkRbNupza9airUj2vrXj4I5ZN9jvgnvZcBVSmbKDEZR0akHFXaEes4d9AVh95y91 HuOHiiJ1hUZ0TGlk52ML5FEE68dDxvORUven9DiUdTAgLBJ5rUvfzj3tf6R4BNmM rzyEA0UCAthqTd1nCdjhwIT6z4BiEVGsBHVAN7mYl+blHqssvuRgNAWrdPFRGYJP cXI7wQc051WCHWXzi6b4h7oiIwlfsx7818S7ITHGM1AxTFl5rIqs9K4oHFTbcg1g sLbJFM0NJ4l1yQZG/9Vldo0RmDdMSc5KgwPa48nf8LHsL3qtcQuvy/b1CIhf8UqZ OWabhVa25xQFTRPmN5ND6wAsvx/zYr0/NF7RfJ3gTn8jCif8LZLVtYYP8zj4TgIL ZhP46YwxaLkyibh+7/R+obszGVt06yqefNYuzfAXpX+2/pDUVQ532AAVD5g4enX7 eAxMda//UAC+WxfCqE6c3CWhXlGaborCsP5auhBg0rbi3/dgPySwMugBfVksa16X X6y36kjw1MRZuhJi4WQGRLX4yjd6sGnWDoY5c/4G89JZKzjWsuNrSJIZRWrzgn84 NLAXpK81RMPkWukePN4ZQ1WEi0IH6AbBBbmQhIRR1bnGR48ZXH+/piJTNi9yKOPi wlp15dJcNo0puq0ZbuZjPboQjg8PQaGtlMVN6A== =EKia -----END PGP PUBLIC KEY BLOCK----- pub 4096R/778C3033 2017-07-06 Schl.-Fingerabdruck = A468 E054 E594 9AC5 8FA7 5A0E F649 2CB4 778C 3033 uid [ uneing.] Thorsten Schning sig 3 778C3033 2017-07-06 Thorsten Schning sub 4096R/BF561FB0 2017-07-06 sig 778C3033 2017-07-06 Thorsten Schning -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v2 mQINBFleTPEBEAC6rmakh64dyRHRmim5X424UuT96wcubwatZrk0yaIrjhAd90Jo rxp5B63B9sw2bEhjafYF4Kcb4mV5AP6nEdu8dWQCj0c7Hb0DXQedRnQI/ALW21Gm nh/C/BGd2zGZE8LCNfLwyxfI1EUCPPC2bfNhoiIMbHoaDBR7HcgE1Zxtl7TuZ9hU GztU3ClKSlEhwK4pCUcSLF3dsvpyuddkG7+DCPqjARCCKkRDYPF2JdL1M2oFHNIM ihnhsT6klZgqtltXPL9/XMhpUyfQ+OhJzqUYrfXq7LSxGKSeb3QvBPgfqK4F/GLQ GblKV5Y4d7LFxPymGq2KCXDLDTkawsjAYFYcBHlYMq9Eg0e26edU7dqj6Am8ZzxO E7FomsWXOjV26I7m0XQRMw9HsJjG+xlt+j8z1HoDK5yWopgj8DyBpnVrTZS0VCto vmLaJSWojwnqO0sRXvZcKBJQ02FJpZWROSrFdPbiHa22pCdhM7dR4tYcSWwU6R5G Azyd8ssojLqKO84jqoUCJ5pOl1/wTJrLbtRNzKaBcU3zTCwhWOwemq0XWe9QuJ/Z 2+GCz4wR19zt5u8Ri6dG2eAdF9XFW9n9JZJ8nd5x8mmyQu3shHCvO3B/HM5AePcp eu5TQZmGlc3Ns+ckP3FNe/WiJ9N70bhSXCdRxNqxcS0BZxaAuWmlBz0+PwARAQAB tCpUaG9yc3RlbiBTY2jDtm5pbmcgPHRzY2hvZW5pbmdAYXBhY2hlLm9yZz6JAjcE EwEKACEFAlleTPECGwMFCwkIBwMFFQoJCAsFFgIDAQACHgECF4AACgkQ9kkstHeM MDM7xw/+NzJnf+pEkM2xhMpRI3byykPuzQB4MfQguwMuHAK2qL28L6jAfQL99ecQ UE87cGjbvYP4x3Z1XwWmg4VvTOYsq9nV3xYrfPOacXMzzSpoVuSpXljEnXsdwPXX ryAgu09vdJtkbVxyx0ypvB2bAoNJrtW8F9vc24XOQREgWp2hbmaGtT7FlCrGab1M CKFMujOS83tFwFpD7oAStbyWZX8AgHktM4HzjeJcqqRtX2EdTTq/3X4tiyI+vpgD rBkjZ9amDG75dMBgcNbdUPGoQdd7/jU2DfcxGSl0i673Kgo6tSt2ecVrGBo99SRa heU6sOcpMucsWCjnj3VndVytBOwu3Q+jHKCadDyVW+0MyA38ltAX1Pt6LUS/s0vC HSf7SMFDqO9f7vmi/SQsSbqokcq9QfVXGvC7C8FYN0g9tg2ljQk/uS62nDrFfRkF pqV1r/vhljFhXNpCq0fx2EJWB9r8h1L3I7Bu77wk9uuwHkYnao2Om4vWNApt/WBO DsIFEGcDBIkXqUqomOm3b9kh39nKs+mwkrP+U+sUgHNAv6Idi/AHocTul2IU807s 8PUnYHzr6EYc2zX02bA/c7hNwV59PUdalYilS1flbyY+7enyWjcfpZH4asa6iw+O wq+gPhdqh5fK51oNH3elolf2y/1S5HDjNJ63aPQTFpJkbGToT3W5Ag0EWV5M8QEQ AN8MjLx959At1Kw5z+Us4taIBEUta3ROg42PEnboVZE+D1pTP77Y/1MXiJsU07Iw ovcnRKiL8clcjWyOhFkjzGjaNbhR9ERolw9mDBHOf3fRrH9tmep7zy4exB7/R1N6 STIE+wbJNcFckwHJr1Xi5duas5sMPIvxdcMF6jgXkto7i5348KhzASVUOoWxsB27 FqZfbzv6YZldkri8D0wHXVrxZ5ZbSSFrTHprmrHdom7uuaen57eJickhLNn9mGhb 4pMWTQGfQrRLDZm8tcHpNgjmOp0/vkJOOLkRlKJIg2SECtb758dS1U2O9SIWoVet oaQquWu19tIyvOZe3fLHNHxp8eJFMpRfV3mLaVBQ2eCmkUohglYzcSzjtifhmf03 AE+tSDdDOc2y0De7SpGJCUu2cGbvWU9I4LnEoeVrW8nYstuMCGSfO3QH6Qsdcteo qD739K4G0xdAc/uNeCF4osauYJD24FFrKpeD6dHe6aoUewA/M4bizqMgYVdzkR9y AxKZn7ReNh97LxDX2g6mEjX83JGIqaRkK7KwwhNrOjwM7SFU0mHAYylTiu0y9rOc UU/db9tpuGBHnZieDJtRkGT2FDV4rM+xpjrVLW25In0YmoqmdLJt+1auqrDd8qkb 2ksKPQEs7snkw57GQ0gHpb2MxURlz2B14NYk1lbjb9lzABEBAAGJAh8EGAEKAAkF AlleTPECGwwACgkQ9kkstHeMMDPeEhAAsPPGS0doKqdSpMgn8wh58bT/zJt5g4e2 pA2KoRmwCtStgITp6SXC/6Udop5sp0mkc70iotWbM6m/EMJVRvHDYuVGG/d75+vm klb8oAfoK6INJwhHoeu8CRP2qZcQXReNE5sox6mK0wrAKQ8QWydgLs8e+t7QP3r1 HsRPBtQnPQz1SPlA4H10TIIu7SnKAw8vsdRe+5PTnxDRPNz71azflUKXe/b+XN6d Os52APfmPiq0DRUPavMRDgzniTp4CM6uli9JkgnBWr6l1vzYuREV+61r9Nr3ukGM 32v1z6Vee22zQBs8u/PxtzwdcmcuYQ3bOb+D6LO5CXPOdEVN9Cjymy1MNiaAW/ce CCjnyvO7h6VgZZ6BmpDtCBWsFBessKClfXHXhxc7BNvP7rllFBUFAwj1pKA8OKzU z5CFR3men8l45kk+SHkhI1QYl8TNAAQpsI34LDILMzgnx9ROYbapnXxH803qcXrH BMrLvB1F+lyE0N7OJCsWX73PJ2fdXqzCoAT65QEKqVD96UIXjz61fyte825Yhneh x8/KNYEHOYv16HdqMS+fnYuykdHZkSlzWNEAAKIWjAWCeQDwaYYD2iMJH/rdK06J 2x7AKEiEO867ckfVXUhO3h31FOQmLP2IWpoMaK4/aUt8p9gt2k2yM5N6EtWsqbvq XuHxrEdQviQ= =bmEc -----END PGP PUBLIC KEY BLOCK----- pub rsa4096 2015-12-20 [SC] 739A 04DE 604E 6AD8 1CCE 457F 1E4B 1D05 B095 DD52 uid [ unknown] Robert Middleton sig 3 1E4B1D05B095DD52 2015-12-20 Robert Middleton sub rsa4096 2015-12-20 [E] sig 1E4B1D05B095DD52 2015-12-20 Robert Middleton -----BEGIN PGP PUBLIC KEY BLOCK----- mQINBFZ2Ix8BEADNw4XWaGlYmgUBkxtCA4xqont5Bg1R0WZyZ71JkXr/3n16CTLv tel7zSWuOJgajIvKtEXlGkRd1tgVFPtrtRWtGlXColu+M3IDOD0hOYsJwS/rY5fV ZF8XdPt2aUQeX+qiM9aoDd7QLneLcH70t1iGYDSttUirA/GE00T0IskyXlz+mCtw pixgIU9PHhKTHu4x8cq+tNXfsafowEfC++rNXhsk/H6JOqXpYAuZyJDrhnc5qb9L dUmB83Nz1L9RYmS2HJ/sldApurhfDnxg2S7o2zpuQ/ceP7g1YeAs3aBVWdVML9tX ijjIjcgCCkBbWx7OJksJWB4SWLf509yoLqv4vLkBd28BN054kK4kBe4J0p3IeeeI SHymMgSaFvrTV/fwkVCTYUHlSewsQ7UzI6Nt8UiO6/CZulI62kR41+ArpxYFT55F P3z4GBMbpstLB55RFqZWYBfNRVmdal6DU3wLbceYv4V6rvrkQKofE1qsoLMF0IRH pfmUUxYXFcm6UljCoYYN4G0iR0CbfJ08RZDHFU+JDR+6VV/rMxz44AW7d23oySTm E0khiBm+dHqznqOm9BIx9xR509ape2JjEcXwKg14ZqcRjkDJO2CEnnTCmPUVL+Mn JSpNQRPGtQQjzBDvByalaFLeNWc3QAw/G4akwmnECwGyvUsZf/lgucTrSwARAQAB tC5Sb2JlcnQgTWlkZGxldG9uIDxyb2JlcnQubWlkZGxldG9uQHJtNTI0OC5jb20+ iQI4BBMBAgAiBQJWdiMfAhsDBgsJCAcDAgYVCAIJCgsEFgIDAQIeAQIXgAAKCRAe Sx0FsJXdUpMrD/0RxkzFcm2Ncd4lKp0bDkYU+jE1PdUd5utCeIlQ/Q/G2H7TUJGb HGUzSjO8B4vrIzaD/EIt1JGOQkoUJKpFlseODRoE0YJ7aR7vsCHdY6tv9mHN7rus PDzR/beNLZdDmrNLPhL1jg8bWnVtqxbgRzHEM3ByD8AynEUwNphjEf3rDIP258CE vj2C3/hsgOTMbKuGFTHKgnTD6KF7rLM0PZJC4iZksPuwPqd92zx7UG54LI5Cg30O stEa2O1SPhFTeYaaQZX4Ls0o8qGCnFXWBGHkH2uiPZG+zZinMhu+Q4okzbmqohQo VsnjM/AR2Cnjkg8A42xBN/DUVPTDRYXti0vD3URvwanCFUFNaoHr7isMXAmle0eX BbH7tB8VMbuvO9rmLFmQJ0vz8LNgbAZuJlK/l/VQZy4v6jzuyRXbn/3owKYk1oZh Oi3ZOK9BdFjM8Zcwrdxxl9KM67f87Eo3c1l4Jz/4Uen1z5Q5lbx/W6rvralAQfSp wrqWM17ir4ooq4cG5kgGenaIZ/sAOXBbS49EOuqw9+1mHMa1QIKLFhFe9hqjeTrY MoOW2fW9/qseothF9LXvTcuD6gKA5J37W7dSqMJEvSlzMDW18bR+dRTE3T0Fyr0U 4W2v/sC8H0RHxO3BWcpFqf/ktNfDM6+phrMGwYrmwp0tZDdZ/aVeo7SAdLkCDQRW diMfARAAqQKXPhwTBUJoVvO4OA3KblTlak3NSiCInQJB8LNP0+3wx7eUnj3+f3X1 wN0Tb44nz16KAm5dPuTQTJKakayDbRCk+30Jsj87N3Y1iBUcsHWWxnpvobVSGvBD fOmIjhUCruYWMbhGa+k27OCytcrvZCAoV5KloMUc5r+pCZsjbFDGvCTuqtHtAhAU pkb9gwpVwwaYkrYoqoyyhKW4VG0FkUZCMq1WdUY8LumFuCHJUxy3HRvnpahUS/3e W/FIiVpyWgo14dZSl254k3JM4SGEU45Q93i4N+cYC/5x4Xa9IRKtDAvHOzkEudqT /dnMWpPtgQwmwdpK3KuIewtLgADeDzAdu4ABgZ3qi12FfnOy5szR0LnAxbOyEvtW X4eMdv4dswcBFCc5RAwUvTfccJocH++y+1IhEziKcM5W+LDBirP370xjGmx6a1R9 rJh5fvv/Jp104NwuOvz4tQcoMWGRkAbeFKtEFfvchah1nVTx0tl6MkAVtVNdm3Ox ekasZapan+a7aDwmoVvdt3vsrtM2KwH9Es0Uq+ezzGYfelSCOV41jrBWZGVDHYMN JxyGbO0DNXM17Ofi+3/n5KGgZqTz3DCDAxg4IjUzP8IUnNVLw823kQVD7T0ts4m4 YnknoLaNTOwbMtu4r7WDoCAGyN0jDlKhGCMAJzeo+4VYv/1GGlEAEQEAAYkCHwQY AQIACQUCVnYjHwIbDAAKCRAeSx0FsJXdUiGZD/9GOykTs3wzv7eQnwAnPuLDxAnR xCiCOV0bh0Ce0a/I9gBdqIr2tijO5wk8RO0BGjMa/oa+fSC6QRyUaccTEDbOQPyS 5JnDCeDS/QIoCc2DKdBKXv6rVERUO99C+B5fuXnaiW4IJFhme+kx6b1W0kMDtovx mdmR+yrnRDAkD85ThFcPlZfcscwwL3LUeNz4v6xuvTpVbv320IpJMBJL9Eq9GxYn mj9566wNUCmbe8W81j7nadDJERDZm+nq2PreyGChKDdcFf3zVquYIV0YRAXwbW7U 8gIlEsAJLTjxstTs2p10jMq+WfSTPQQ1OnkvYC2IPyXCmcn3R2c8jqkktrhZ7ZQv B+DZr82I6eRf+fBLF8t9tzgMDUd0/BcjdZHtUyi4Y+3inUvN8h8oeRw2U3xQGqM3 piMIZgMkWfrdcDTYMEbWpvPzlH0OuqSt5KG7SpTnJYJDP6H4tJ+rBM057Ce8Q91p 9dw8I0pVtlU9BKGuJp5PgVgDNy1boDFHMIivTwZcSCVCRDTKXJ7YJTQWJor0TXrN FXy/CdxLVIuXp690D+rSGMhqQKvLqPe1EqgSjtAdbp7tcjun9erd0yBYAemkA8ip GyAvCgU1kEohWuo0PUKheYAmPYE2Fy9bLK34oG66GDuVVMG5XfzFJQDszttcvdVx V31GMXQwztHBy+NhCQ== =wVyD -----END PGP PUBLIC KEY BLOCK-----